diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..eb439df --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,70 @@ +import net.minecrell.pluginyml.paper.PaperPluginDescription + +group = "net.hareworks.hcu" +version = "1.0" + +plugins { + kotlin("jvm") version "2.2.21" + kotlin("plugin.serialization") version "2.2.21" + id("de.eldoria.plugin-yml.paper") version "0.8.0" + id("com.gradleup.shadow") version "9.2.2" +} +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") +} + +val exposedVersion = "1.0.0-rc-4" + +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.10-R0.1-SNAPSHOT") + compileOnly("org.jetbrains.kotlin:kotlin-stdlib") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") { + exclude(group = "org.jetbrains.kotlin") + } + compileOnly("com.michael-bull.kotlin-result:kotlin-result:2.1.0") + + compileOnly("net.hareworks.hcu:hcu-core") + compileOnly("net.hareworks:kommand-lib") + compileOnly("net.hareworks:permits-lib") + + compileOnly("net.kyori:adventure-api:4.25.0") + compileOnly("net.kyori:adventure-text-minimessage:4.25.0") + + compileOnly("org.postgresql:postgresql:42.7.8") + compileOnly("org.jetbrains.exposed:exposed-core:$exposedVersion") + compileOnly("org.jetbrains.exposed:exposed-dao:$exposedVersion") + compileOnly("org.jetbrains.exposed:exposed-jdbc:$exposedVersion") + compileOnly("org.jetbrains.exposed:exposed-kotlin-datetime:$exposedVersion") +} +tasks { + withType { + archiveBaseName.set("lands") + } + shadowJar { + archiveClassifier.set("min") + minimize() + dependencies { + exclude(dependency("org.jetbrains.kotlin:kotlin-stdlib")) + } + } +} + +paper { + main = "net.hareworks.hcu.lands.App" + name = "lands" + description = "land plugin" + version = getVersion().toString() + apiVersion = "1.21.10" + serverDependencies { + register("hcu-core") { + required = true + load = PaperPluginDescription.RelativeLoadOrder.BEFORE + } + } + authors = + listOf( + "Hare-K02", + "Kaariyaaa" + ) +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..ba9ecbe --- /dev/null +++ b/gradle.properties @@ -0,0 +1,7 @@ +org.gradle.configuration-cache=true +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.daemon=false + +org.gradle.configuration-cache=true + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..4ac3234 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,2 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..548fb23 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,6 @@ +rootProject.name = "faction" +includeBuild("hcu-core") +includeBuild("hcu-core/kommand-lib") +includeBuild("hcu-core/kommand-lib/permits-lib") + + diff --git a/src/main/kotlin/net/hareworks/hcu/lands/App.kt b/src/main/kotlin/net/hareworks/hcu/lands/App.kt new file mode 100644 index 0000000..3ec21fb --- /dev/null +++ b/src/main/kotlin/net/hareworks/hcu/lands/App.kt @@ -0,0 +1,67 @@ +package net.hareworks.hcu.lands + +import net.hareworks.hcu.core.Main +import net.hareworks.hcu.core.actor.ActorIdentityService +import net.hareworks.hcu.core.player.PlayerIdService +import net.hareworks.hcu.lands.command.LandsCommand +import net.hareworks.hcu.lands.service.LandService +import net.hareworks.hcu.lands.task.VisualizerTask +import org.bukkit.plugin.java.JavaPlugin + +class App : JavaPlugin() { + + var landService: LandService? = null + + var playerIdService: PlayerIdService? = null + + override fun onEnable() { + // Register commands immediately to ensure they are picked up by LifecycleEventManager + LandsCommand(this).register() + + // Defer initialization to ensure hcu-core database connection is ready + server.scheduler.runTaskLater(this, Runnable { + initializeServices() + }, 60L) + } + + private fun initializeServices() { + val db = try { + Main.instance.exposedDatabase() + } catch (e: Exception) { + null + } + + if (db == null) { + logger.severe("hcu-core database not ready. Lands plugin will not function.") + return + } + + val service = LandService(db) + try { + service.init() + } catch (e: Exception) { + logger.severe("Failed to initialize database schema: ${e.message}") + e.printStackTrace() + return + } + this.landService = service + + val actorService = server.servicesManager.load(ActorIdentityService::class.java) + val pIdService = server.servicesManager.load(PlayerIdService::class.java) + + if (actorService == null || pIdService == null) { + logger.severe("Required services (ActorIdentityService/PlayerIdService) not found.") + return + } + this.playerIdService = pIdService + + // Run visualizer every 20 ticks (1 second) + server.scheduler.runTaskTimer(this, VisualizerTask(service), 20L, 10L) + + logger.info("Lands plugin initialized successfully.") + } + + override fun onDisable() { + // Logic to cleanup if necessary + } +} diff --git a/src/main/kotlin/net/hareworks/hcu/lands/command/LandsCommand.kt b/src/main/kotlin/net/hareworks/hcu/lands/command/LandsCommand.kt new file mode 100644 index 0000000..41b8268 --- /dev/null +++ b/src/main/kotlin/net/hareworks/hcu/lands/command/LandsCommand.kt @@ -0,0 +1,237 @@ +package net.hareworks.hcu.lands.command + +import io.papermc.paper.math.Position +import net.hareworks.hcu.lands.App +import net.hareworks.hcu.lands.model.Land +import net.hareworks.hcu.lands.model.Shape +import net.hareworks.hcu.lands.task.LandsVisualizer +import net.hareworks.kommand_lib.kommand +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.format.NamedTextColor +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class LandsCommand( + private val app: App +) { + fun register() { + kommand(app) { + command("lands") { + literal("create") { + string("name") { + executes { + val player = sender as? Player ?: return@executes + val service: net.hareworks.hcu.lands.service.LandService? = app.landService + val playerIdService = app.playerIdService + + if (service == null || playerIdService == null) { + sender.sendMessage(Component.text("Lands service is not ready yet. Please wait.", NamedTextColor.RED)) + return@executes + } + + val name: String = argument("name") + + val playerEntry = playerIdService.find(player.uniqueId) + if (playerEntry == null) { + sender.sendMessage(Component.text("Identity not found.", NamedTextColor.RED)) + return@executes + } + + if (service.createLand(name, playerEntry.actorId, player.world.name)) { + sender.sendMessage(Component.text("Land '$name' created.", NamedTextColor.GREEN)) + } else { + sender.sendMessage(Component.text("Land '$name' already exists.", NamedTextColor.RED)) + } + } + } + } + + literal("delete") { + string("name") { + executes { + val player = sender as? Player ?: return@executes + val service: net.hareworks.hcu.lands.service.LandService? = app.landService + val playerIdService = app.playerIdService + if (service == null || playerIdService == null) { + sender.sendMessage(Component.text("Lands service is not ready yet.", NamedTextColor.RED)) + return@executes + } + + val name: String = argument("name") + + val land: Land? = service.getLand(name) + if (land == null) { + sender.sendMessage(Component.text("Land not found.", NamedTextColor.RED)) + return@executes + } + val playerEntry = playerIdService.find(player.uniqueId) + if (playerEntry == null || (land.actorId != playerEntry.actorId && !player.isOp)) { + sender.sendMessage(Component.text("You do not own this land.", NamedTextColor.RED)) + return@executes + } + + if (service.deleteLand(name)) { + sender.sendMessage(Component.text("Land deleted.", NamedTextColor.GREEN)) + } else { + sender.sendMessage(Component.text("Failed to delete.", NamedTextColor.RED)) + } + } + } + } + + literal("data") { + string("name") { + literal("add") { + literal("cuboid") { + blockCoordinates("pos1") { + blockCoordinates("pos2") { + executes { + val p1: Position = argument("pos1") + val p2: Position = argument("pos2") + val shape = Shape.Cuboid(p1.x(), p1.y(), p1.z(), p2.x(), p2.y(), p2.z()) + val name: String = argument("name") + + updateLandData(sender, name) { parts -> + parts.add(shape) + sender.sendMessage(Component.text("Shape added.", NamedTextColor.GREEN)) + } + } + } + } + } + literal("cylinder") { + blockCoordinates("center") { + float("radius") { + float("height") { + executes { + val c: Position = argument("center") + val r: Double = argument("radius") + val h: Double = argument("height") + val shape = Shape.Cylinder(c.x(), c.y(), c.z(), r, h) + val name: String = argument("name") + + updateLandData(sender, name) { parts -> + parts.add(shape) + sender.sendMessage(Component.text("Shape added.", NamedTextColor.GREEN)) + } + } + } + } + } + } + } + + literal("modify") { + integer("index") { + literal("cuboid") { + blockCoordinates("pos1") { + blockCoordinates("pos2") { + executes { + val index: Int = argument("index") + val p1: Position = argument("pos1") + val p2: Position = argument("pos2") + val shape = Shape.Cuboid(p1.x(), p1.y(), p1.z(), p2.x(), p2.y(), p2.z()) + val name: String = argument("name") + + updateLandData(sender, name) { parts -> + if (index in parts.indices) { + parts[index] = shape + sender.sendMessage(Component.text("Shape modified at index $index.", NamedTextColor.GREEN)) + } else { + sender.sendMessage(Component.text("Index out of bounds.", NamedTextColor.RED)) + } + } + } + } + } + } + literal("cylinder") { + blockCoordinates("center") { + float("radius") { + float("height") { + executes { + val index: Int = argument("index") + val c: Position = argument("center") + val r: Double = argument("radius") + val h: Double = argument("height") + val shape = Shape.Cylinder(c.x(), c.y(), c.z(), r, h) + val name: String = argument("name") + + updateLandData(sender, name) { parts -> + if (index in parts.indices) { + parts[index] = shape + sender.sendMessage(Component.text("Shape modified at index $index.", NamedTextColor.GREEN)) + } else { + sender.sendMessage(Component.text("Index out of bounds.", NamedTextColor.RED)) + } + } + } + } + } + } + } + } + } + + literal("remove") { + integer("index") { + executes { + val name: String = argument("name") + val index: Int = argument("index") + + updateLandData(sender, name) { parts -> + if (index in parts.indices) { + parts.removeAt(index) + sender.sendMessage(Component.text("Shape removed at index $index.", NamedTextColor.GREEN)) + } else { + sender.sendMessage(Component.text("Index out of bounds.", NamedTextColor.RED)) + } + } + } + } + } + } + } + + literal("visualize") { + executes { + val player = sender as? Player ?: return@executes + LandsVisualizer.toggle(player) + } + } + } + } + } + + private fun updateLandData(sender: CommandSender, name: String, action: (MutableList) -> Unit) { + val player = sender as? Player ?: return + val service = app.landService + val playerIdService = app.playerIdService + + if (service == null || playerIdService == null) { + sender.sendMessage(Component.text("Lands service is not ready yet.", NamedTextColor.RED)) + return + } + + val land = service.getLand(name) + if (land == null) { + sender.sendMessage(Component.text("Land not found.", NamedTextColor.RED)) + return + } + + val playerEntry = playerIdService.find(player.uniqueId) + if (playerEntry == null || (land.actorId != playerEntry.actorId && !player.isOp)) { + sender.sendMessage(Component.text("You do not own this land.", NamedTextColor.RED)) + return + } + + if (land.world != player.world.name) { + sender.sendMessage(Component.text("Land is in world '${land.world}', but you are in '${player.world.name}'.", NamedTextColor.RED)) + return + } + + service.modifyLand(name) { data -> + action(data.parts) + } + } +} diff --git a/src/main/kotlin/net/hareworks/hcu/lands/database/LandsTable.kt b/src/main/kotlin/net/hareworks/hcu/lands/database/LandsTable.kt new file mode 100644 index 0000000..30bc481 --- /dev/null +++ b/src/main/kotlin/net/hareworks/hcu/lands/database/LandsTable.kt @@ -0,0 +1,41 @@ +package net.hareworks.hcu.lands.database + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import net.hareworks.hcu.lands.model.LandData +import org.jetbrains.exposed.v1.core.Column +import org.jetbrains.exposed.v1.core.ColumnType +import org.jetbrains.exposed.v1.core.Table +import org.postgresql.util.PGobject + +object LandsTable : Table("lands") { + val name = varchar("name", 64) + val actorId = integer("actor_id") + val world = varchar("world", 64) + val data = json("data", LandData.serializer()) + + override val primaryKey = PrimaryKey(name) +} + +fun Table.json(name: String, serializer: KSerializer): Column = + registerColumn(name, JsonColumnType(serializer)) + +class JsonColumnType(private val serializer: KSerializer) : ColumnType() { + override fun sqlType(): String = "jsonb" + + override fun valueFromDB(value: Any): T { + return when (value) { + is PGobject -> Json.decodeFromString(serializer, value.value ?: "{}") + is String -> Json.decodeFromString(serializer, value) + else -> error("Unexpected value type for JSON column: ${value::class}") + } + } + + override fun notNullValueToDB(value: T): Any { + return PGobject().apply { + type = "jsonb" + this.value = Json.encodeToString(serializer, value) + } + } +} diff --git a/src/main/kotlin/net/hareworks/hcu/lands/model/Land.kt b/src/main/kotlin/net/hareworks/hcu/lands/model/Land.kt new file mode 100644 index 0000000..fc63892 --- /dev/null +++ b/src/main/kotlin/net/hareworks/hcu/lands/model/Land.kt @@ -0,0 +1,55 @@ +package net.hareworks.hcu.lands.model + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +data class Land( + val name: String, + val actorId: Int, + val world: String, + val data: LandData +) + +@Serializable +data class LandData( + val parts: MutableList = mutableListOf() +) + +@Serializable +sealed class Shape { + @Serializable + @SerialName("cuboid") + data class Cuboid( + val x1: Double, val y1: Double, val z1: Double, + val x2: Double, val y2: Double, val z2: Double + ) : Shape() { + fun minX() = minOf(x1, x2) + fun maxX() = maxOf(x1, x2) + fun minY() = minOf(y1, y2) + fun maxY() = maxOf(y1, y2) + fun minZ() = minOf(z1, z2) + fun maxZ() = maxOf(z1, z2) + + fun contains(x: Double, y: Double, z: Double): Boolean { + return x >= minX() && x <= maxX() && + y >= minY() && y <= maxY() && + z >= minZ() && z <= maxZ() + } + } + + @Serializable + @SerialName("cylinder") + data class Cylinder( + val x: Double, val y: Double, val z: Double, + val radius: Double, + val height: Double // Assuming vertical cylinder + ) : Shape() { + fun contains(tx: Double, ty: Double, tz: Double): Boolean { + if (ty < y || ty > y + height) return false + val dx = tx - x + val dz = tz - z + return (dx * dx + dz * dz) <= (radius * radius) + } + } +} diff --git a/src/main/kotlin/net/hareworks/hcu/lands/service/LandService.kt b/src/main/kotlin/net/hareworks/hcu/lands/service/LandService.kt new file mode 100644 index 0000000..4449420 --- /dev/null +++ b/src/main/kotlin/net/hareworks/hcu/lands/service/LandService.kt @@ -0,0 +1,84 @@ +package net.hareworks.hcu.lands.service + +import net.hareworks.hcu.lands.database.LandsTable +import net.hareworks.hcu.lands.model.Land +import net.hareworks.hcu.lands.model.LandData +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.jdbc.Database +import org.jetbrains.exposed.v1.jdbc.SchemaUtils +import org.jetbrains.exposed.v1.jdbc.insert +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.jetbrains.exposed.v1.jdbc.update +import org.jetbrains.exposed.v1.jdbc.deleteWhere +import org.jetbrains.exposed.v1.jdbc.transactions.transaction +import java.util.concurrent.ConcurrentHashMap +import org.bukkit.Bukkit + +class LandService(private val database: Database) { + private val cache = ConcurrentHashMap() + + fun init() { + transaction(database) { + SchemaUtils.create(LandsTable) + refreshCache() + } + } + + private fun refreshCache() { + cache.clear() + LandsTable.selectAll().forEach { row -> + val land = Land( + name = row[LandsTable.name], + actorId = row[LandsTable.actorId], + world = row[LandsTable.world], + data = row[LandsTable.data] + ) + cache[land.name] = land + } + } + + fun createLand(name: String, actorId: Int, world: String): Boolean { + if (cache.containsKey(name)) return false + + transaction(database) { + LandsTable.insert { + it[LandsTable.name] = name + it[LandsTable.actorId] = actorId + it[LandsTable.world] = world + it[LandsTable.data] = LandData() + } + } + // Update cache efficiently + cache[name] = Land(name, actorId, world, LandData()) + return true + } + + fun modifyLand(name: String, modifier: (LandData) -> Unit): Boolean { + val land = cache[name] ?: return false + val newParts = ArrayList(land.data.parts) + val newData = land.data.copy(parts = newParts) + + modifier(newData) + + transaction(database) { + LandsTable.update({ LandsTable.name eq name }) { + it[LandsTable.data] = newData + } + } + cache[name] = land.copy(data = newData) + return true + } + + fun deleteLand(name: String): Boolean { + if (!cache.containsKey(name)) return false + transaction(database) { + LandsTable.deleteWhere { LandsTable.name eq name } + } + cache.remove(name) + return true + } + + fun getLand(name: String): Land? = cache[name] + + fun getAllLands(): Collection = cache.values +} diff --git a/src/main/kotlin/net/hareworks/hcu/lands/task/VisualizerTask.kt b/src/main/kotlin/net/hareworks/hcu/lands/task/VisualizerTask.kt new file mode 100644 index 0000000..a05ee46 --- /dev/null +++ b/src/main/kotlin/net/hareworks/hcu/lands/task/VisualizerTask.kt @@ -0,0 +1,90 @@ +package net.hareworks.hcu.lands.task + +import net.hareworks.hcu.lands.model.Shape +import net.hareworks.hcu.lands.service.LandService +import org.bukkit.Bukkit +import org.bukkit.Color +import org.bukkit.Particle +import org.bukkit.entity.Player +import java.util.UUID +import kotlin.math.cos +import kotlin.math.sin + +object LandsVisualizer { + private val enabledPlayers = mutableSetOf() + + fun toggle(player: Player) { + if (enabledPlayers.contains(player.uniqueId)) { + enabledPlayers.remove(player.uniqueId) + player.sendMessage("Visualization disabled.") + } else { + enabledPlayers.add(player.uniqueId) + player.sendMessage("Visualization enabled.") + } + } + + fun isEnabled(player: Player) = enabledPlayers.contains(player.uniqueId) +} + +class VisualizerTask(private val landService: LandService) : Runnable { + override fun run() { + Bukkit.getOnlinePlayers().forEach { p -> + if (LandsVisualizer.isEnabled(p)) { + landService.getAllLands().forEach { land -> + if (land.world == p.world.name) { + // Optimization: Check distance to Land center/bounds? + // For now basic iteration + land.data.parts.forEach { shape -> + drawShape(p, shape) + } + } + } + } + } + } + + private fun drawShape(player: Player, shape: Shape) { + when (shape) { + is Shape.Cuboid -> drawCuboid(player, shape) + is Shape.Cylinder -> drawCylinder(player, shape) + } + } + + private fun drawCuboid(player: Player, cuboid: Shape.Cuboid) { + // Draw edges + val minX = cuboid.minX() + val maxX = cuboid.maxX() + val minY = cuboid.minY() + val maxY = cuboid.maxY() + val minZ = cuboid.minZ() + val maxZ = cuboid.maxZ() + + // Just corners for now or simple lines + // A simple way to visualize is to spawn particles at corners and periodically along edges + // Doing full wireframe every tick is heavy. + // Let's do corners. + val corners = listOf( + Triple(minX, minY, minZ), Triple(maxX, minY, minZ), + Triple(minX, maxY, minZ), Triple(maxX, maxY, minZ), + Triple(minX, minY, maxZ), Triple(maxX, minY, maxZ), + Triple(minX, maxY, maxZ), Triple(maxX, maxY, maxZ) + ) + corners.forEach { (x, y, z) -> + player.spawnParticle(Particle.DUST, x, y, z, 1, 0.0, 0.0, 0.0, Particle.DustOptions(Color.LIME, 1.0f)) + } + } + + private fun drawCylinder(player: Player, cylinder: Shape.Cylinder) { + val segments = 20 + val step = (Math.PI * 2) / segments + // Top and Bottom circles + for (i in 0 until segments) { + val angle = i * step + val dx = cos(angle) * cylinder.radius + val dz = sin(angle) * cylinder.radius + + player.spawnParticle(Particle.DUST, cylinder.x + dx, cylinder.y, cylinder.z + dz, 1, 0.0, 0.0, 0.0, Particle.DustOptions(Color.AQUA, 1.0f)) + player.spawnParticle(Particle.DUST, cylinder.x + dx, cylinder.y + cylinder.height, cylinder.z + dz, 1, 0.0, 0.0, 0.0, Particle.DustOptions(Color.AQUA, 1.0f)) + } + } +}