diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..5adf394 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,41 @@ +# Automatically build the project and run any configured tests for every push +# and submitted pull request. This can help catch issues that only occur on +# certain platforms or Java versions, and provides a first line of defence +# against bad commits. + +name: build +on: [pull_request, push] + +jobs: + build: + strategy: + matrix: + # Use these Java versions + java: [ + 17, # Current Java LTS & minimum supported by Minecraft + 21, # Current Java LTS + ] + # and run on both Linux and Windows + os: [ubuntu-22.04, windows-2022] + runs-on: ${{ matrix.os }} + steps: + - name: checkout repository + uses: actions/checkout@v4 + - name: validate gradle wrapper + uses: gradle/wrapper-validation-action@v1 + - name: setup jdk ${{ matrix.java }} + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java }} + distribution: 'microsoft' + - name: make gradle wrapper executable + if: ${{ runner.os != 'Windows' }} + run: chmod +x ./gradlew + - name: build + run: ./gradlew build + - name: capture build artifacts + if: ${{ runner.os == 'Linux' && matrix.java == '21' }} # Only upload artifacts built from latest java on one OS + uses: actions/upload-artifact@v3 + with: + name: Artifacts + path: build/libs/ \ No newline at end of file diff --git a/.gitignore b/.gitignore index 524f096..c476faf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,40 @@ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -replay_pid* +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ + +# java + +hs_err_*.log +replay_*.log +*.hprof +*.jfr diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1625c17 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..5e5c6f9 --- /dev/null +++ b/build.gradle @@ -0,0 +1,110 @@ +plugins { + id 'fabric-loom' version '1.5-SNAPSHOT' + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. + + exclusiveContent { + forRepository { + maven { + name = "Modrinth" + url = "https://api.modrinth.com/maven" + } + } + filter { + includeGroup("maven.modrinth") + } + } +} + +loom { + splitEnvironmentSourceSets() + + mods { + "thework" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } + +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API. This is technically optional, but you probably want it anyway. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + //development runtime only mods (make it go nice and brrr) + modRuntimeOnly "maven.modrinth:rrls:3.3.0+mc1.20.4-fabric" + modRuntimeOnly "maven.modrinth:cloth-config:13.0.121+fabric" + modRuntimeOnly "maven.modrinth:modmenu:9.0.0" + modRuntimeOnly "maven.modrinth:sodium:mc1.20.4-0.5.8" + modRuntimeOnly "maven.modrinth:iris:1.6.15+1.20.4" + + // Uncomment the following line to enable the deprecated Fabric API modules. + // These are included in the Fabric API production distribution and allow you to update your mod to the latest modules at a later more convenient time. + + // modImplementation "net.fabricmc.fabric-api:fabric-api-deprecated:${project.fabric_version}" +} + +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 17 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +jar { + from("LICENSE") { + rename { "${it}_${project.base.archivesName.get()}"} + } +} + +// configure the maven publication +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2e4e54e --- /dev/null +++ b/gradle.properties @@ -0,0 +1,17 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +org.gradle.parallel=true + +# Fabric Properties +# check these on https://fabricmc.net/develop +minecraft_version=1.20.4 +yarn_mappings=1.20.4+build.3 +loader_version=0.15.6 + +# Mod Properties +mod_version=1.0.0 +maven_group=cassunshine.thework +archives_base_name=thework + +# Dependencies +fabric_version=0.95.4+1.20.4 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 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..1af9e09 --- /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.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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. +# + +############################################################################## +# +# 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/subprojects/plugins/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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# 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, 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" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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 + +@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. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +: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 b/settings.gradle new file mode 100644 index 0000000..75c4d72 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() + } +} \ No newline at end of file diff --git a/src/client/java/cassunshine/thework/TheWorkClient.java b/src/client/java/cassunshine/thework/TheWorkClient.java new file mode 100644 index 0000000..2fbade6 --- /dev/null +++ b/src/client/java/cassunshine/thework/TheWorkClient.java @@ -0,0 +1,17 @@ +package cassunshine.thework; + +import cassunshine.thework.rendering.blockentities.TheWorkBlockEntityRenderers; +import cassunshine.thework.rendering.blockentities.alchemy_block.nodes.NodeTypeRenderers; +import net.fabricmc.api.ClientModInitializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TheWorkClient implements ClientModInitializer { + public static final Logger CLIENT_LOGGER = LoggerFactory.getLogger(TheWorkClient.class); + + @Override + public void onInitializeClient() { + TheWorkBlockEntityRenderers.initialize(); + NodeTypeRenderers.initialize(); + } +} \ No newline at end of file diff --git a/src/client/java/cassunshine/thework/mixin/client/ExampleClientMixin.java b/src/client/java/cassunshine/thework/mixin/client/ExampleClientMixin.java new file mode 100644 index 0000000..05ed021 --- /dev/null +++ b/src/client/java/cassunshine/thework/mixin/client/ExampleClientMixin.java @@ -0,0 +1,15 @@ +package cassunshine.thework.mixin.client; + +import net.minecraft.client.MinecraftClient; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(MinecraftClient.class) +public class ExampleClientMixin { + @Inject(at = @At("HEAD"), method = "run") + private void run(CallbackInfo info) { + // This code is injected into the start of MinecraftClient.run()V + } +} \ No newline at end of file diff --git a/src/client/java/cassunshine/thework/rendering/blockentities/TheWorkBlockEntityRenderers.java b/src/client/java/cassunshine/thework/rendering/blockentities/TheWorkBlockEntityRenderers.java new file mode 100644 index 0000000..e80c9ea --- /dev/null +++ b/src/client/java/cassunshine/thework/rendering/blockentities/TheWorkBlockEntityRenderers.java @@ -0,0 +1,12 @@ +package cassunshine.thework.rendering.blockentities; + +import cassunshine.thework.blockentities.TheWorkBlockEntities; +import cassunshine.thework.rendering.blockentities.alchemy_block.AlchemyCircleBlockEntityRenderer; +import net.minecraft.client.render.block.entity.BlockEntityRendererFactories; + +public class TheWorkBlockEntityRenderers { + + public static void initialize() { + BlockEntityRendererFactories.register(TheWorkBlockEntities.ALCHEMY_CIRCLE_TYPE, AlchemyCircleBlockEntityRenderer::new); + } +} diff --git a/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/AlchemyCircleBlockEntityRenderer.java b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/AlchemyCircleBlockEntityRenderer.java new file mode 100644 index 0000000..02d78ff --- /dev/null +++ b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/AlchemyCircleBlockEntityRenderer.java @@ -0,0 +1,179 @@ +package cassunshine.thework.rendering.blockentities.alchemy_block; + +import cassunshine.thework.TheWorkMod; +import cassunshine.thework.blockentities.alchemy_circle.AlchemyCircleBlockEntity; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeType; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeTypes; +import cassunshine.thework.rendering.blockentities.alchemy_block.nodes.NodeTypeRenderers; +import cassunshine.thework.rendering.util.RenderingUtilities; +import net.minecraft.client.render.RenderLayer; +import net.minecraft.client.render.VertexConsumerProvider; +import net.minecraft.client.render.block.entity.BlockEntityRenderer; +import net.minecraft.client.render.block.entity.BlockEntityRendererFactory; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.MathHelper; + +public class AlchemyCircleBlockEntityRenderer implements BlockEntityRenderer { + + private static final Identifier ALCHEMY_CIRCLE_TEXTURE = new Identifier(TheWorkMod.ModID, "textures/other/alchemy_circle.png"); + + public AlchemyCircleBlockEntityRenderer(BlockEntityRendererFactory.Context context) { + + } + + @Override + public void render(AlchemyCircleBlockEntity entity, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay) { + RenderingUtilities.setupStack(matrices); + RenderingUtilities.setupLightOverlay(light, overlay); + + RenderingUtilities.pushMat(); + RenderingUtilities.setupConsumers(vertexConsumers); + RenderingUtilities.setupRenderLayer(getLayer()); + + try { + matrices.translate(0.5f, 1 / 32.0f, 0.5f); + + for (int i = 0; i < entity.mainCircles.size(); i++) { + AlchemyCircleBlockEntity.MainCircle circle = entity.mainCircles.get(i); + AlchemyCircleBlockEntity.MainCircle nextCircle = i + 1 >= entity.mainCircles.size() ? null : entity.mainCircles.get(i + 1); + + drawMainCircle(circle, nextCircle == null ? -1 : nextCircle.radius); + } + + } catch (Exception e) { + //Do nothing. + } finally { + RenderingUtilities.popMat(); + } + } + + @Override + public int getRenderDistance() { + return 999; + } + + public RenderLayer getLayer() { + return RenderLayer.getEntityCutoutNoCull(ALCHEMY_CIRCLE_TEXTURE); + } + + @Override + public boolean rendersOutsideBoundingBox(AlchemyCircleBlockEntity blockEntity) { + return true; + } + + private void drawMainCircle(AlchemyCircleBlockEntity.MainCircle circle, float nextRadius) { + float anglePerNode = MathHelper.TAU / circle.nodes.length; + float lastAngle = 0; + + float smallCircleCover = ((0.5f / circle.circumference) * MathHelper.TAU); + + for (int i = 0; i < circle.nodes.length; i++) { + NodeType node = circle.nodes[i]; + NodeType nextNode = circle.nodes[(i + 1) % circle.nodes.length]; + + float thisAngle = node == NodeTypes.NONE ? lastAngle : lastAngle + smallCircleCover; + float nextAngle = nextNode == NodeTypes.NONE ? lastAngle + anglePerNode : lastAngle + anglePerNode - smallCircleCover; + + float pipHeight = 0.1f; + float pipOffset = 0; + + //Draw sub-circle + if (node != NodeTypes.NONE) { + RenderingUtilities.pushMat(); + float drawX = MathHelper.sin(thisAngle - smallCircleCover) * circle.radius; + float drawZ = MathHelper.cos(thisAngle - smallCircleCover) * circle.radius; + + RenderingUtilities.translateMatrix(drawX, 0, drawZ); + + drawCircleSegment(0.5f, 0, MathHelper.TAU); + + RenderingUtilities.rotateMatrix(0, -lastAngle, 0); + RenderingUtilities.translateMatrix(-0.5f, 0, -0.5f); + + //Special node renderer, if any. + var renderer = NodeTypeRenderers.get(node.getClass()); + if (renderer != null) { + renderer.render(node); + RenderingUtilities.setupRenderLayer(getLayer()); + } + + + RenderingUtilities.popMat(); + + if (nextRadius > 0) { + pipOffset = 0.5f; + pipHeight = (nextRadius - circle.radius) - pipOffset; + } else { + pipOffset = 0.5f; + } + } + + + if (pipHeight > 0.001f) + drawPip(circle.radius + pipOffset, lastAngle, 1 / 32.0f, pipHeight); + + //Draw line to next sub-circle. + drawCircleSegment(circle.radius, thisAngle, nextAngle); + lastAngle += anglePerNode; + } + + if (circle.nodes.length == 0) + drawCircleSegment(circle.radius, 0, MathHelper.TAU); + } + + private void drawCircleSegment(float radius, float startAngle, float endAngle) { + + float circleHalfThickness = 1 / 32.0f; + float circleMin = radius - circleHalfThickness; + float circleMax = radius + circleHalfThickness; + + //Total circumference of the circle. + float totalCircumference = 2 * MathHelper.PI * radius; + //The length of the segment we're drawing. + float deltaCircumference = totalCircumference * (MathHelper.abs(startAngle - endAngle) / MathHelper.TAU); + + //Draw 1 segment per block length, rounding up, times 2 so it's always even(?) + int drawSegments = MathHelper.ceil(deltaCircumference); + + if (radius < 1) + drawSegments *= 4; + + float startCircumference = totalCircumference * (startAngle / MathHelper.TAU); + + for (int i = 0; i < drawSegments; i++) { + float angleThis = MathHelper.lerp(i / (float) drawSegments, startAngle, endAngle); + float angleNext = MathHelper.lerp((i + 1) / (float) drawSegments, startAngle, endAngle); + + float startSin = MathHelper.sin(angleThis); + float startCos = MathHelper.cos(angleThis); + + float nextSin = MathHelper.sin(angleNext); + float nextCos = MathHelper.cos(angleNext); + + RenderingUtilities.saneVertex(startSin * circleMin, 0, startCos * circleMin, 255, 255, 255, startCircumference, 0, 0, 1, 0); + RenderingUtilities.saneVertex(startSin * circleMax, 0, startCos * circleMax, 255, 255, 255, startCircumference, 0.125f, 0, 1, 0); + + startCircumference += 1; + + RenderingUtilities.saneVertex(nextSin * circleMax, 0, nextCos * circleMax, 255, 255, 255, startCircumference, 0.125f, 0, 1, 0); + RenderingUtilities.saneVertex(nextSin * circleMin, 0, nextCos * circleMin, 255, 255, 255, startCircumference, 0, 0, 1, 0); + } + } + + private void drawPip(float radius, float angle, float pipWidth, float pipHeight) { + float circumference = 2 * MathHelper.PI * radius; + float angleWidth = (pipWidth / circumference) * MathHelper.TAU; + + float topCircumference = 2 * MathHelper.PI * (radius + pipHeight); + float topAngleWidth = (pipWidth / topCircumference) * MathHelper.TAU; + + float minRadius = radius; + float maxRadius = radius + pipHeight; + + RenderingUtilities.saneVertex(MathHelper.sin(angle - angleWidth) * minRadius, 0, MathHelper.cos(angle - angleWidth) * minRadius, 255, 255, 255, 0, 0, 0, 1, 0); + RenderingUtilities.saneVertex(MathHelper.sin(angle - topAngleWidth) * maxRadius, 0, MathHelper.cos(angle - topAngleWidth) * maxRadius, 255, 255, 255, 0, 0, 0, 1, 0); + RenderingUtilities.saneVertex(MathHelper.sin(angle + topAngleWidth) * maxRadius, 0, MathHelper.cos(angle + topAngleWidth) * maxRadius, 255, 255, 255, 0, 0, 0, 1, 0); + RenderingUtilities.saneVertex(MathHelper.sin(angle + angleWidth) * minRadius, 0, MathHelper.cos(angle + angleWidth) * minRadius, 255, 255, 255, 0, 0, 0, 1, 0); + } +} diff --git a/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/ElementNodeRenderer.java b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/ElementNodeRenderer.java new file mode 100644 index 0000000..195ffa7 --- /dev/null +++ b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/ElementNodeRenderer.java @@ -0,0 +1,24 @@ +package cassunshine.thework.rendering.blockentities.alchemy_block.nodes; + +import cassunshine.thework.blockentities.alchemy_circle.nodes.ElementNodeType; +import cassunshine.thework.rendering.util.RenderingUtilities; +import net.minecraft.client.render.RenderLayer; +import net.minecraft.util.Identifier; + +public class ElementNodeRenderer extends NodeTypeRenderer { + + + @Override + public void render(ElementNodeType node) { + var element = node.element; + if (element == null) + return; + + RenderingUtilities.setupRenderLayer(RenderLayer.getEntityCutoutNoCull(new Identifier(element.id.getNamespace(), "textures/item/" + element.id.getPath() + ".png"))); + + RenderingUtilities.saneVertex(0, 0, 0, 255, 255, 255, 0, 0, 0, 1, 0); + RenderingUtilities.saneVertex(0, 0, 1, 255, 255, 255, 0, 1, 0, 1, 0); + RenderingUtilities.saneVertex(1, 0, 1, 255, 255, 255, 1, 1, 0, 1, 0); + RenderingUtilities.saneVertex(1, 0, 0, 255, 255, 255, 1, 0, 0, 1, 0); + } +} diff --git a/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/NodeTypeRenderer.java b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/NodeTypeRenderer.java new file mode 100644 index 0000000..3615380 --- /dev/null +++ b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/NodeTypeRenderer.java @@ -0,0 +1,11 @@ +package cassunshine.thework.rendering.blockentities.alchemy_block.nodes; + +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeType; + +public class NodeTypeRenderer { + + public void render(T node) { + + } + +} diff --git a/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/NodeTypeRenderers.java b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/NodeTypeRenderers.java new file mode 100644 index 0000000..6878bcf --- /dev/null +++ b/src/client/java/cassunshine/thework/rendering/blockentities/alchemy_block/nodes/NodeTypeRenderers.java @@ -0,0 +1,26 @@ +package cassunshine.thework.rendering.blockentities.alchemy_block.nodes; + +import cassunshine.thework.blockentities.alchemy_circle.nodes.ElementNodeType; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeType; + +import java.util.HashMap; + +public class NodeTypeRenderers { + private static final HashMap, NodeTypeRenderer> renderers = new HashMap<>(); + + public static void initialize() { + + } + + private static void register(Class type, NodeTypeRenderer renderer) { + renderers.put(type, renderer); + } + + public static NodeTypeRenderer get(Class type) { + return (NodeTypeRenderer) renderers.get(type); //yea yea + } + + static { + register(ElementNodeType.class, new ElementNodeRenderer()); + } +} diff --git a/src/client/java/cassunshine/thework/rendering/util/RenderingUtilities.java b/src/client/java/cassunshine/thework/rendering/util/RenderingUtilities.java new file mode 100644 index 0000000..d512462 --- /dev/null +++ b/src/client/java/cassunshine/thework/rendering/util/RenderingUtilities.java @@ -0,0 +1,59 @@ +package cassunshine.thework.rendering.util; + +import net.minecraft.client.render.RenderLayer; +import net.minecraft.client.render.VertexConsumer; +import net.minecraft.client.render.VertexConsumerProvider; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.util.math.MatrixUtil; +import org.joml.Quaternionf; + +public class RenderingUtilities { + private static MatrixStack stack; + private static VertexConsumerProvider consumers; + private static VertexConsumer consumer; + + private static int light; + private static int overlay; + + public static void setupStack(MatrixStack stack) { + RenderingUtilities.stack = stack; + } + + public static void setupConsumers(VertexConsumerProvider vertexConsumers) { + RenderingUtilities.consumers = vertexConsumers; + } + + public static void setupRenderLayer(RenderLayer layer) { + RenderingUtilities.consumer = consumers.getBuffer(layer); + } + + + public static void setupLightOverlay(int light, int overlay) { + RenderingUtilities.light = light; + RenderingUtilities.overlay = overlay; + } + + public static void saneVertex(float x, float y, float z, int red, int green, int blue, float u, float v, float normalX, float normalY, float normalZ) { + consumer.vertex(stack.peek().getPositionMatrix(), x, y, z).color(red, green, blue, 255).texture(u, v).overlay(overlay).light(light).normal(stack.peek().getNormalMatrix(), normalX, normalY, normalZ).next(); + } + + public static void pushMat() { + stack.push(); + } + + public static void popMat() { + stack.pop(); + + } + + public static void translateMatrix(float x, float y, float z) { + stack.translate(x, y, z); + } + + public static void rotateMatrix(float x, float y, float z) { + stack.multiply(new Quaternionf().rotationX(x)); + stack.multiply(new Quaternionf().rotationY(y)); + stack.multiply(new Quaternionf().rotationZ(z)); + } + +} diff --git a/src/client/resources/assets/thework/lang/en_us.json b/src/client/resources/assets/thework/lang/en_us.json new file mode 100644 index 0000000..bb85653 --- /dev/null +++ b/src/client/resources/assets/thework/lang/en_us.json @@ -0,0 +1,10 @@ +{ + "item.thework.chalk" : "Chalk", + + "element.thework.ignis" : "Ignis", + "element.thework.terra" : "Terra", + "element.thework.aqua" : "Aqua", + "element.thework.ventus" : "Ventus", + + "element.thework.vita" : "Vita" +} \ No newline at end of file diff --git a/src/client/resources/assets/thework/models/item/chalk.json b/src/client/resources/assets/thework/models/item/chalk.json new file mode 100644 index 0000000..0bbf4e4 --- /dev/null +++ b/src/client/resources/assets/thework/models/item/chalk.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0" : "thework:item/chalk" + } +} \ No newline at end of file diff --git a/src/client/resources/assets/thework/textures/item/aqua.png b/src/client/resources/assets/thework/textures/item/aqua.png new file mode 100644 index 0000000..196fc9b Binary files /dev/null and b/src/client/resources/assets/thework/textures/item/aqua.png differ diff --git a/src/client/resources/assets/thework/textures/item/chalk.png b/src/client/resources/assets/thework/textures/item/chalk.png new file mode 100644 index 0000000..0ace129 Binary files /dev/null and b/src/client/resources/assets/thework/textures/item/chalk.png differ diff --git a/src/client/resources/assets/thework/textures/item/ignis.png b/src/client/resources/assets/thework/textures/item/ignis.png new file mode 100644 index 0000000..a20e30c Binary files /dev/null and b/src/client/resources/assets/thework/textures/item/ignis.png differ diff --git a/src/client/resources/assets/thework/textures/item/terra.png b/src/client/resources/assets/thework/textures/item/terra.png new file mode 100644 index 0000000..97e7851 Binary files /dev/null and b/src/client/resources/assets/thework/textures/item/terra.png differ diff --git a/src/client/resources/assets/thework/textures/item/ventus.png b/src/client/resources/assets/thework/textures/item/ventus.png new file mode 100644 index 0000000..8080ded Binary files /dev/null and b/src/client/resources/assets/thework/textures/item/ventus.png differ diff --git a/src/client/resources/assets/thework/textures/other/alchemy_circle.png b/src/client/resources/assets/thework/textures/other/alchemy_circle.png new file mode 100644 index 0000000..af72fa8 Binary files /dev/null and b/src/client/resources/assets/thework/textures/other/alchemy_circle.png differ diff --git a/src/client/resources/thework.client.mixins.json b/src/client/resources/thework.client.mixins.json new file mode 100644 index 0000000..055bc0d --- /dev/null +++ b/src/client/resources/thework.client.mixins.json @@ -0,0 +1,11 @@ +{ + "required": true, + "package": "cassunshine.thework.mixin.client", + "compatibilityLevel": "JAVA_17", + "client": [ + "ExampleClientMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/src/main/java/cassunshine/thework/TheWorkMod.java b/src/main/java/cassunshine/thework/TheWorkMod.java new file mode 100644 index 0000000..0b1beae --- /dev/null +++ b/src/main/java/cassunshine/thework/TheWorkMod.java @@ -0,0 +1,27 @@ +package cassunshine.thework; + +import cassunshine.thework.blockentities.TheWorkBlockEntities; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeTypes; +import cassunshine.thework.blocks.TheWorkBlocks; +import cassunshine.thework.elements.TheWorkElements; +import cassunshine.thework.items.TheWorkItems; +import net.fabricmc.api.ModInitializer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TheWorkMod implements ModInitializer { + public static final String ModID = "thework"; + + public static final Logger LOGGER = LoggerFactory.getLogger(TheWorkMod.class); + + @Override + public void onInitialize() { + TheWorkElements.initialize(); + NodeTypes.initialize(); + + TheWorkItems.initialize(); + TheWorkBlocks.initialize(); + TheWorkBlockEntities.initialize(); + } +} \ No newline at end of file diff --git a/src/main/java/cassunshine/thework/blockentities/TheWorkBlockEntities.java b/src/main/java/cassunshine/thework/blockentities/TheWorkBlockEntities.java new file mode 100644 index 0000000..1098b2e --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/TheWorkBlockEntities.java @@ -0,0 +1,29 @@ +package cassunshine.thework.blockentities; + +import cassunshine.thework.TheWorkMod; +import cassunshine.thework.blockentities.alchemy_circle.AlchemyCircleBlockEntity; +import cassunshine.thework.blocks.TheWorkBlocks; +import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder; +import net.minecraft.block.entity.BlockEntityType; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +public class TheWorkBlockEntities { + + public static final BlockEntityType ALCHEMY_CIRCLE_TYPE; + + static { + ALCHEMY_CIRCLE_TYPE = FabricBlockEntityTypeBuilder.create(AlchemyCircleBlockEntity::new, TheWorkBlocks.ALCHEMY_CIRCLE_BLOCK).build(); + } + + public static void initialize() { + registerBlockEntity(ALCHEMY_CIRCLE_TYPE, "alchemy_circle"); + } + + + public static void registerBlockEntity(BlockEntityType type, String name) { + Registry.register(Registries.BLOCK_ENTITY_TYPE, new Identifier(TheWorkMod.ModID, name), type); + } + +} diff --git a/src/main/java/cassunshine/thework/blockentities/alchemy_circle/AlchemyCircleBlockEntity.java b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/AlchemyCircleBlockEntity.java new file mode 100644 index 0000000..8c0c4b9 --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/AlchemyCircleBlockEntity.java @@ -0,0 +1,236 @@ +package cassunshine.thework.blockentities.alchemy_circle; + +import cassunshine.thework.TheWorkMod; +import cassunshine.thework.blockentities.TheWorkBlockEntities; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeType; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeTypes; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.block.entity.BlockEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemUsageContext; +import net.minecraft.item.Items; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtElement; +import net.minecraft.util.Hand; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Direction; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.Vec3d; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; + +public class AlchemyCircleBlockEntity extends BlockEntity { + + public final ArrayList mainCircles = new ArrayList<>(); + + public AlchemyCircleBlockEntity(BlockPos pos, BlockState state) { + super(TheWorkBlockEntities.ALCHEMY_CIRCLE_TYPE, pos, state); + } + + + @Override + protected void writeNbt(NbtCompound nbt) { + super.writeNbt(nbt); + + { + NbtCompound circles = new NbtCompound(); + nbt.put("circles", circles); + + circles.putInt("count", mainCircles.size()); + + for (int i = 0; i < mainCircles.size(); i++) { + MainCircle circle = mainCircles.get(i); + NbtCompound circleCompound = new NbtCompound(); + circle.writeNbt(circleCompound); + circles.put(Integer.toString(i), circleCompound); + } + } + } + + @Override + public void readNbt(NbtCompound nbt) { + super.readNbt(nbt); + + { + mainCircles.clear(); + + NbtCompound circles = nbt.getCompound("circles"); + int count = circles.getInt("count"); + + for (int i = 0; i < count; i++) { + MainCircle circle = new MainCircle(); + NbtCompound circleCompound = circles.getCompound(Integer.toString(i)); + + circle.readNbt(circleCompound); + + mainCircles.add(circle); + } + } + } + + @Override + public NbtCompound toInitialChunkDataNbt() { + return createNbt(); + } + + public Vec3d getCenter() { + return new Vec3d(getPos().getX() + 0.5f, getPos().getY() - 0.5f, getPos().getZ() + 0.5f); + } + + public void addCircle(float radius) { + + for (int i = 0; i < mainCircles.size(); i++) { + MainCircle circle = mainCircles.get(i); + + var dist = Math.abs(circle.radius - radius); + + if (dist < 1) { + mainCircles.remove(i); + + if (mainCircles.isEmpty()) { + markRemoved(); + world.setBlockState(getPos(), Blocks.AIR.getDefaultState()); + } + + return; + } + + } + + MainCircle circle = new MainCircle(); + circle.setRadius(radius); + + mainCircles.add(circle); + mainCircles.sort(Comparator.comparingDouble(a -> a.radius)); + + markDirty(); + } + + + public boolean onChalkUsed(ItemUsageContext context) { + var center = getCenter().withAxis(Direction.Axis.Y, 0); + var hitPos = context.getHitPos().withAxis(Direction.Axis.Y, 0); + + var delta = hitPos.subtract(center).normalize(); + var dist = (float) center.distanceTo(hitPos); + + float angle = (float) Math.atan2(-delta.z, delta.x); + + //Check if we clicked on one of the main lines. + for (int i = 0; i < mainCircles.size(); i++) { + AlchemyCircleBlockEntity.MainCircle circle = mainCircles.get(i); + + if (circle.onChalkUsed(context, dist, angle)) + return true; + } + return false; + } + + public class MainCircle { + public float radius; + public float circumference; + + public NodeType[] nodes; + + protected void writeNbt(NbtCompound nbt) { + nbt.putFloat("radius", radius); + + { + NbtCompound nodesNbt = new NbtCompound(); + nbt.put("nodes", nodesNbt); + + for (int i = 0; i < nodes.length; i++) { + NodeType node = nodes[i]; + nodesNbt.putString(Integer.toString(i), node.id.toString()); + } + } + } + + public void readNbt(NbtCompound nbt) { + setRadius(nbt.getFloat("radius")); + + { + NbtCompound nodesNbt = nbt.getCompound("nodes"); + for (int i = 0; i < nodes.length; i++) { + String val = nodesNbt.getString(Integer.toString(i)); + nodes[i] = NodeTypes.getType(new Identifier(val)); + } + } + } + + public void setRadius(float radius) { + this.radius = radius; + this.circumference = 2 * MathHelper.PI * radius; + + if (radius < 1) + nodes = new NodeType[0]; + else { + var nodeCount = MathHelper.ceil(radius / 2) * 4; + nodes = new NodeType[nodeCount]; + Arrays.fill(nodes, NodeTypes.NONE); + } + } + + public boolean onChalkUsed(ItemUsageContext context, float distFromCenter, float angleFromCenter) { + var distToCircle = Math.abs(distFromCenter - radius); + + //If the location clicked is >0.5 blocks away, we definitely didn't click this circle. + if (distToCircle > 0.5f) + return false; + + float anglePercent = (angleFromCenter) / MathHelper.TAU; + anglePercent += 0.25f; + if (anglePercent < 0) + anglePercent += 1.0f; + int nearestIndex = (Math.round(anglePercent * nodes.length)) % nodes.length; + float nearestPercent = nearestIndex / (float) nodes.length; + + float distToPercent = Math.min( + Math.abs(anglePercent - nearestPercent), + Math.abs((1 - anglePercent) - nearestPercent) + ); + + float distanceReal = distToPercent * circumference; + + if (distanceReal < 0.6f) { + var newType = getTargetNodeType(context); + + if (nodes[nearestIndex] != newType) + nodes[nearestIndex] = newType; + else + nodes[nearestIndex] = NodeTypes.NONE; + + return true; + } + + + return true; + } + + private NodeType getTargetNodeType(ItemUsageContext context) { + Hand oppositeHand = context.getHand() == Hand.MAIN_HAND ? Hand.OFF_HAND : Hand.MAIN_HAND; + ItemStack oppositeHandStack = context.getPlayer().getStackInHand(oppositeHand); + + if (oppositeHandStack.getItem() != Items.WRITABLE_BOOK || !oppositeHandStack.hasNbt()) + return NodeTypes.NONE; + var list = oppositeHandStack.getNbt().getList("pages", NbtElement.STRING_TYPE); + if (list.isEmpty()) + return NodeTypes.NONE; + + var firstPage = list.getString(0).trim(); + + try { + var id = new Identifier(TheWorkMod.ModID, firstPage); + return NodeTypes.getType(id); + } catch (Exception e) { + //Ignored. + } + + return NodeTypes.NONE; + } + } +} diff --git a/src/main/java/cassunshine/thework/blockentities/alchemy_circle/connections/ConnectionType.java b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/connections/ConnectionType.java new file mode 100644 index 0000000..ce134c8 --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/connections/ConnectionType.java @@ -0,0 +1,12 @@ +package cassunshine.thework.blockentities.alchemy_circle.connections; + +public enum ConnectionType { + /** + * Allows no essence to pass through this connection. + */ + STOP, + /** + * Allow all essence to pass through this connection. + */ + ALLOW +} diff --git a/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/AlchemyNode.java b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/AlchemyNode.java new file mode 100644 index 0000000..0bc6399 --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/AlchemyNode.java @@ -0,0 +1,67 @@ +package cassunshine.thework.blockentities.alchemy_circle.nodes; + + +import cassunshine.thework.blockentities.alchemy_circle.connections.ConnectionType; +import cassunshine.thework.elements.Element; +import net.minecraft.item.ItemUsageContext; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.util.math.Vec3d; + +/** + * Nodes are the main points of interaction with alchemic circles + * They act as the input, output, processing, and pools of circles. + */ +public class AlchemyNode { + + /** + * Position of the node in 3D space. + */ + public Vec3d position; + + /** + * Rotation angle of the node. + */ + public float rotation; + + /** + * The type of node. + */ + public NodeType type = NodeTypes.NONE; + + /** + * The connection type out to the next ring, if any. + */ + public ConnectionType outConnectionType = ConnectionType.ALLOW; + + /** + * The connection type to the next node, if any. + */ + public ConnectionType nextConnectionType = ConnectionType.ALLOW; + + public Element currentElement = null; + + public float elementAmount = 0; + + + public AlchemyNode(Vec3d pos, float rotation) { + position = pos; + } + + + public boolean handleInteraction(ItemUsageContext context, Vec3d interactPos) { + if (interactPos.distanceTo(position) > 0.5) + return false; + + + return true; + } + + + public void readNbt(NbtCompound nbt) { + + } + + public void writeNbt(NbtCompound nbt){ + + } +} diff --git a/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/ElementNodeType.java b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/ElementNodeType.java new file mode 100644 index 0000000..5ffdbea --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/ElementNodeType.java @@ -0,0 +1,13 @@ +package cassunshine.thework.blockentities.alchemy_circle.nodes; + +import cassunshine.thework.elements.Element; + +public class ElementNodeType extends NodeType{ + + public final Element element; + + public ElementNodeType(Element element){ + this.element = element; + } + +} diff --git a/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/NodeType.java b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/NodeType.java new file mode 100644 index 0000000..fe17d60 --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/NodeType.java @@ -0,0 +1,7 @@ +package cassunshine.thework.blockentities.alchemy_circle.nodes; + +import net.minecraft.util.Identifier; + +public class NodeType { + public Identifier id; +} diff --git a/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/NodeTypes.java b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/NodeTypes.java new file mode 100644 index 0000000..111c1de --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/nodes/NodeTypes.java @@ -0,0 +1,35 @@ +package cassunshine.thework.blockentities.alchemy_circle.nodes; + +import cassunshine.thework.TheWorkMod; +import cassunshine.thework.elements.TheWorkElements; +import net.minecraft.util.Identifier; + +import java.util.HashMap; + +public class NodeTypes { + + private static final HashMap types = new HashMap<>(); + + public static final NodeType NONE = registerType("none", new NodeType()); + public static final NodeType TEST = registerType("test", new NodeType()); + + + public static void initialize() { + for (var kvp : TheWorkElements.ELEMENT_HASH_MAP.entrySet()) { + registerType(kvp.getKey().getPath(), new ElementNodeType(kvp.getValue())); + } + } + + private static T registerType(String name, T type) { + var id = new Identifier(TheWorkMod.ModID, name); + type.id = id; + types.put(id, type); + return type; + } + + public static NodeType getType(Identifier id) { + var t = types.get(id); + + return t == null ? NONE : t; + } +} diff --git a/src/main/java/cassunshine/thework/blockentities/alchemy_circle/rings/AlchemyRing.java b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/rings/AlchemyRing.java new file mode 100644 index 0000000..475cb8a --- /dev/null +++ b/src/main/java/cassunshine/thework/blockentities/alchemy_circle/rings/AlchemyRing.java @@ -0,0 +1,148 @@ +package cassunshine.thework.blockentities.alchemy_circle.rings; + + +import cassunshine.thework.blockentities.alchemy_circle.nodes.AlchemyNode; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeType; +import cassunshine.thework.blockentities.alchemy_circle.nodes.NodeTypes; +import net.minecraft.item.ItemUsageContext; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.util.math.Direction; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.Vec3d; + +import java.util.Arrays; + +/** + * Alchemy rings are the pieces of an alchemic circle that hold nodes, and transfer essence from one node to another. + */ +public class AlchemyRing { + + /** + * Radius of the ring. + */ + public float radius = 1; + + /** + * The circumference of the ring. + */ + public float circumference; + + /** + * True if the ring should send essence clockwise, false for counterclockwise. + */ + public boolean isClockwise = true; + + /** + * Position of the ring's center in world-space. + */ + public Vec3d position; + + /** + * An array of all the nodes in this alchemy ring. + */ + public AlchemyNode[] nodes; + + + public void setRadius(float radius) { + this.radius = radius; + this.circumference = MathHelper.TAU * radius; + + if (radius < 1) nodes = new AlchemyNode[0]; + else { + var nodeCount = MathHelper.ceil(radius / 2) * 4; + nodes = new AlchemyNode[nodeCount]; + + for (int i = 0; i < nodes.length; i++) { + float angle = (i / (float) nodes.length) * MathHelper.TAU; + nodes[i] = new AlchemyNode(position.add(MathHelper.sin(angle), 0, MathHelper.cos(angle)), angle); + } + } + } + + /** + * Tries to handle an interaction with this ring. + * + * @param interactPos Position of interaction. Y value will be ignored. + * @return True if the interaction was handled, false otherwise. + */ + public boolean handleInteraction(ItemUsageContext context, Vec3d interactPos) { + interactPos = interactPos.withAxis(Direction.Axis.Y, position.y); + + //Interaction relative to this ring. + Vec3d delta = interactPos.subtract(position); + + //Distance that interaction is from the ring itself. + float difference = (float) delta.length() - radius; + float interactDist = MathHelper.abs(difference); + + //Interactions further than 0.5 blocks away will fail. + if (interactDist > 0.5f) return false; + + //Angle on the circle that interaction took place. + //Need to do some math to make it not negative and nicer to use. + float angle = (float) Math.atan2(-delta.z, delta.x); + angle += MathHelper.PI * 0.5f; + if (angle < 0) angle += MathHelper.TAU; + + int nearestIndex = getNearestNodeIndex(angle); + AlchemyNode node = nodes[nearestIndex]; + + if (node.handleInteraction(context, interactPos)) return true; + + if (difference > 0) { + isClockwise = true; + } else { + isClockwise = false; + } + + return true; + } + + + /** + * Gets the real distance between a node at some index and some angle. + */ + public float getNodeDistance(int index, float angle) { + float nodePercent = index / (float) nodes.length; + + float nodeAngle = MathHelper.TAU * nodePercent; + float anglePercent = angle / MathHelper.TAU; + + float distPercent = Math.min(Math.abs(anglePercent - nodeAngle), Math.abs((1 - anglePercent) - nodeAngle)); + + return circumference * distPercent; + } + + /** + * Takes some angle and returns the node nearest to that angle. + */ + public int getNearestNodeIndex(float angle) { + float anglePercent = angle / MathHelper.TAU; + return Math.round(anglePercent * nodes.length) % nodes.length; + } + + /** + * Takes some angle and returns the node that comes after it on the circle. + */ + public int getNextNodeIndex(float angle) { + float anglePercent = angle / MathHelper.TAU; + return MathHelper.ceil(anglePercent * nodes.length) % nodes.length; + } + + /** + * Takes some angle and returns the node that comes before it on the circle. + */ + public int getLastNodeIndex(float angle) { + float anglePercent = angle / MathHelper.TAU; + return MathHelper.floor(anglePercent * nodes.length) % nodes.length; + } + + + public void readNBT(NbtCompound nbt) { + + } + + public void writeNbt(NbtCompound nbt){ + + } +} diff --git a/src/main/java/cassunshine/thework/blocks/AlchemyCircleBlock.java b/src/main/java/cassunshine/thework/blocks/AlchemyCircleBlock.java new file mode 100644 index 0000000..4c2b0b7 --- /dev/null +++ b/src/main/java/cassunshine/thework/blocks/AlchemyCircleBlock.java @@ -0,0 +1,90 @@ +package cassunshine.thework.blocks; + +import cassunshine.thework.blockentities.alchemy_circle.AlchemyCircleBlockEntity; +import cassunshine.thework.blockentities.TheWorkBlockEntities; +import com.mojang.serialization.MapCodec; +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.minecraft.block.*; +import net.minecraft.block.entity.BlockEntity; +import net.minecraft.block.piston.PistonBehavior; +import net.minecraft.sound.BlockSoundGroup; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.shape.VoxelShape; +import net.minecraft.util.shape.VoxelShapes; +import net.minecraft.world.BlockView; +import org.jetbrains.annotations.Nullable; + +public class AlchemyCircleBlock extends BlockWithEntity { + private static final MapCodec CODEC = createCodec(AlchemyCircleBlock::new); + + private final VoxelShape alchemyCircleCenterShape; + + protected AlchemyCircleBlock(Settings settings) { + this(); + } + + protected AlchemyCircleBlock() { + super( + FabricBlockSettings.create() + .breakInstantly() + .dropsNothing() + .noCollision() + .nonOpaque() + .notSolid() + .noCollision() + .pistonBehavior(PistonBehavior.DESTROY) + .allowsSpawning(Blocks::never) + .solidBlock(Blocks::never) + .blockVision(Blocks::never) + .sounds(BlockSoundGroup.STONE) + ); + + alchemyCircleCenterShape = VoxelShapes.cuboid(0, 0, 0, 1, 1.0f / 16.0f, 1); + } + + @Override + protected MapCodec getCodec() { + return CODEC; + } + + @Nullable + @Override + public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { + return new AlchemyCircleBlockEntity(pos, state); + } + + @Override + public BlockRenderType getRenderType(BlockState state) { + return BlockRenderType.ENTITYBLOCK_ANIMATED; + } + + @Override + public VoxelShape getCameraCollisionShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { + return VoxelShapes.empty(); + } + + @Override + public boolean isTransparent(BlockState state, BlockView world, BlockPos pos) { + return true; + } + + @Override + public float getAmbientOcclusionLightLevel(BlockState state, BlockView world, BlockPos pos) { + return 1; + } + + @Override + public VoxelShape getCollisionShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { + return VoxelShapes.empty(); + } + + @Override + public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { + var blockEntity = world.getBlockEntity(pos, TheWorkBlockEntities.ALCHEMY_CIRCLE_TYPE); + + if (blockEntity.isEmpty()) + return alchemyCircleCenterShape; + + return alchemyCircleCenterShape; + } +} diff --git a/src/main/java/cassunshine/thework/blocks/TheWorkBlocks.java b/src/main/java/cassunshine/thework/blocks/TheWorkBlocks.java new file mode 100644 index 0000000..96b41c2 --- /dev/null +++ b/src/main/java/cassunshine/thework/blocks/TheWorkBlocks.java @@ -0,0 +1,34 @@ +package cassunshine.thework.blocks; + +import cassunshine.thework.TheWorkMod; +import cassunshine.thework.items.TheWorkItems; +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.minecraft.block.Block; +import net.minecraft.item.BlockItem; +import net.minecraft.item.Item; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +public class TheWorkBlocks { + + public static final Block ALCHEMY_CIRCLE_BLOCK = new AlchemyCircleBlock(); + + + public static void initialize() { + registerBlock(ALCHEMY_CIRCLE_BLOCK, "alchemy_circle"); + } + + private static void registerBlock(Block b, String name) { + Registry.register(Registries.BLOCK, new Identifier(TheWorkMod.ModID, name), b); + } + + private static void registerBlockWithItem(Block b, String name) { + registerBlockWithItem(b, name, new FabricItemSettings()); + } + + private static void registerBlockWithItem(Block b, String name, Item.Settings itemSettings) { + registerBlock(b, name); + TheWorkItems.registerItem(new BlockItem(b, itemSettings), name); + } +} diff --git a/src/main/java/cassunshine/thework/elements/Element.java b/src/main/java/cassunshine/thework/elements/Element.java new file mode 100644 index 0000000..c73a841 --- /dev/null +++ b/src/main/java/cassunshine/thework/elements/Element.java @@ -0,0 +1,15 @@ +package cassunshine.thework.elements; + +import cassunshine.thework.TheWorkMod; +import net.minecraft.util.Identifier; + +public class Element { + public Identifier id; + public int color; + + public Element(String name, int color) { + id = new Identifier(TheWorkMod.ModID, name); + + TheWorkElements.ELEMENT_HASH_MAP.put(id, this); + } +} diff --git a/src/main/java/cassunshine/thework/elements/TheWorkElements.java b/src/main/java/cassunshine/thework/elements/TheWorkElements.java new file mode 100644 index 0000000..1f49296 --- /dev/null +++ b/src/main/java/cassunshine/thework/elements/TheWorkElements.java @@ -0,0 +1,20 @@ +package cassunshine.thework.elements; + +import net.minecraft.util.Identifier; +import net.minecraft.util.math.ColorHelper; + +import java.util.HashMap; + +public class TheWorkElements { + + public static final HashMap ELEMENT_HASH_MAP = new HashMap<>(); + + public static Element IGNIS = new Element("ignis", ColorHelper.Argb.getArgb(255, 255, 255, 255)); + public static Element TERRA = new Element("terra", ColorHelper.Argb.getArgb(255, 255, 255, 255)); + public static Element AQUA = new Element("aqua", ColorHelper.Argb.getArgb(255, 255, 255, 255)); + public static Element VENTUS = new Element("ventus", ColorHelper.Argb.getArgb(255, 255, 255, 255)); + + public static void initialize() { + + } +} diff --git a/src/main/java/cassunshine/thework/items/ChalkItem.java b/src/main/java/cassunshine/thework/items/ChalkItem.java new file mode 100644 index 0000000..32dbb65 --- /dev/null +++ b/src/main/java/cassunshine/thework/items/ChalkItem.java @@ -0,0 +1,136 @@ +package cassunshine.thework.items; + +import cassunshine.thework.blockentities.alchemy_circle.AlchemyCircleBlockEntity; +import cassunshine.thework.blockentities.TheWorkBlockEntities; +import cassunshine.thework.blocks.TheWorkBlocks; +import cassunshine.thework.util.AlchemyCircleUtils; +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemUsageContext; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtElement; +import net.minecraft.util.ActionResult; +import net.minecraft.util.Hand; +import net.minecraft.util.TypedActionResult; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.MathHelper; +import net.minecraft.world.World; +import org.joml.Vector3f; + +import java.util.ArrayList; +import java.util.Comparator; + +public class ChalkItem extends Item { + public ChalkItem() { + super( + new FabricItemSettings() + ); + } + + @Override + public ActionResult useOnBlock(ItemUsageContext context) { + NbtCompound stackNbt = context.getStack().getOrCreateNbt(); + + if (stackNbt.contains("start_pos", NbtElement.INT_ARRAY_TYPE)) { + var pos = stackNbt.getIntArray("start_pos"); + stackNbt.remove("start_pos"); + + int x = pos[0]; + int y = pos[1]; + int z = pos[2]; + + float dist = Vector3f.distance(x, y, z, context.getBlockPos().getX(), context.getBlockPos().getY(), context.getBlockPos().getZ()); + dist = Math.max(dist, 0.5f); + + if (dist > 64.0f) + return ActionResult.SUCCESS; + + var usedBlock = context.getWorld().getBlockState(new BlockPos(x, y, z)).getBlock(); + attemptDrawCircle(x, usedBlock == TheWorkBlocks.ALCHEMY_CIRCLE_BLOCK ? y : y + 1, z, dist, context.getWorld()); + } else { + + var maybeCircle = AlchemyCircleUtils.alchemyCircleSearch(context.getBlockPos().add(0, 1, 0), context.getWorld()); + + if (maybeCircle.isPresent()) { + AlchemyCircleBlockEntity alchemyCircle = maybeCircle.get(); + + if(alchemyCircle.onChalkUsed(context)){ + return ActionResult.SUCCESS; + } + } + + int[] pos = new int[]{ + context.getBlockPos().getX(), + context.getBlockPos().getY(), + context.getBlockPos().getZ(), + }; + + stackNbt.putIntArray("start_pos", pos); + } + + return ActionResult.SUCCESS; + } + + + private void attemptDrawCircle(int x, int y, int z, float radius, World world) { + float biasedRadius = radius < 1 ? radius : radius + 1; + int intRadius = MathHelper.ceil(biasedRadius); + + ArrayList blocksToRemove = new ArrayList<>(); + + for (int ix = -intRadius; ix <= intRadius; ix++) { + for (int iz = -intRadius; iz <= intRadius; iz++) { + BlockPos actualPos = new BlockPos(x + ix, y, z + iz); + float squareDistance = (float) actualPos.add(0, -actualPos.getY(), 0).getSquaredDistance(x, 0, z); + + if (squareDistance < (biasedRadius * biasedRadius) && !checkValidCirclePos(blocksToRemove, actualPos, world, squareDistance)) + return; + } + } + + blocksToRemove.sort(Comparator.comparingDouble(a -> a.getSquaredDistance(x, y, z))); + + for (BlockPos pos : blocksToRemove) + world.setBlockState(pos, Blocks.AIR.getDefaultState()); + + BlockPos targetPos = new BlockPos(x, y, z); + + if (world.getBlockState(targetPos).getBlock() != TheWorkBlocks.ALCHEMY_CIRCLE_BLOCK) + world.setBlockState(targetPos, TheWorkBlocks.ALCHEMY_CIRCLE_BLOCK.getDefaultState()); + + var maybeBlockEntity = world.getBlockEntity(targetPos, TheWorkBlockEntities.ALCHEMY_CIRCLE_TYPE); + if (maybeBlockEntity.isEmpty()) + return; + + AlchemyCircleBlockEntity blockEntity = maybeBlockEntity.get(); + + blockEntity.addCircle(radius); + } + + + private boolean checkValidCirclePos(ArrayList toRemove, BlockPos pos, World world, float dist) { + BlockPos basePos = pos.add(0, -1, 0); + + BlockState circleState = world.getBlockState(pos); + BlockState baseState = world.getBlockState(basePos); + + if (!baseState.isFullCube(world, basePos)) + return false; + + if (circleState.getBlock() == Blocks.AIR || (dist < 0.01f && circleState.getBlock() == TheWorkBlocks.ALCHEMY_CIRCLE_BLOCK)) { + //toRemove.add(pos); + return true; + } + + if (circleState.isReplaceable()) { + toRemove.add(pos); + return true; + } + + return false; + } +} diff --git a/src/main/java/cassunshine/thework/items/TheWorkItems.java b/src/main/java/cassunshine/thework/items/TheWorkItems.java new file mode 100644 index 0000000..6b23034 --- /dev/null +++ b/src/main/java/cassunshine/thework/items/TheWorkItems.java @@ -0,0 +1,21 @@ +package cassunshine.thework.items; + +import cassunshine.thework.TheWorkMod; +import net.minecraft.item.Item; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +public class TheWorkItems { + + public static final ChalkItem CHALK_ITEM = new ChalkItem(); + + public static void initialize() { + registerItem(CHALK_ITEM, "chalk"); + } + + + public static void registerItem(Item item, String name) { + Registry.register(Registries.ITEM, new Identifier(TheWorkMod.ModID, name), item); + } +} diff --git a/src/main/java/cassunshine/thework/mixin/ExampleMixin.java b/src/main/java/cassunshine/thework/mixin/ExampleMixin.java new file mode 100644 index 0000000..86d9f56 --- /dev/null +++ b/src/main/java/cassunshine/thework/mixin/ExampleMixin.java @@ -0,0 +1,15 @@ +package cassunshine.thework.mixin; + +import net.minecraft.server.MinecraftServer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(MinecraftServer.class) +public class ExampleMixin { + @Inject(at = @At("HEAD"), method = "loadWorld") + private void init(CallbackInfo info) { + // This code is injected into the start of MinecraftServer.loadWorld()V + } +} \ No newline at end of file diff --git a/src/main/java/cassunshine/thework/util/AlchemyCircleUtils.java b/src/main/java/cassunshine/thework/util/AlchemyCircleUtils.java new file mode 100644 index 0000000..0caa0ad --- /dev/null +++ b/src/main/java/cassunshine/thework/util/AlchemyCircleUtils.java @@ -0,0 +1,66 @@ +package cassunshine.thework.util; + +import cassunshine.thework.blockentities.alchemy_circle.AlchemyCircleBlockEntity; +import cassunshine.thework.blockentities.TheWorkBlockEntities; +import net.minecraft.util.collection.ArrayListDeque; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import java.util.HashSet; +import java.util.Optional; + +public class AlchemyCircleUtils { + + public static Optional alchemyCircleSearch(BlockPos pos, World world) { + return alchemyCircleSearch(pos, world, 64); + } + + private static final BlockPos[] nPos = new BlockPos[]{ + new BlockPos(-1, 0, 0), + new BlockPos(1, 0, 0), + new BlockPos(0, 0, 1), + new BlockPos(0, 0, -1), + }; + + public static Optional alchemyCircleSearch(BlockPos pos, World world, int maxRadius) { + ArrayListDeque blockPosQueue = new ArrayListDeque<>(); + HashSet searchedPositions = new HashSet<>(); + + blockPosQueue.add(pos); + searchedPositions.add(pos); + + while (!blockPosQueue.isEmpty()) { + + if(blockPosQueue.size() > 4096) + return Optional.empty(); + + BlockPos next = blockPosQueue.removeFirst(); + BlockPos belowPos = next.add(0, -1, 0); + + var belowState = world.getBlockState(belowPos); + + if(!belowState.isFullCube(world, belowPos)) + continue; + + var mbe = world.getBlockEntity(next, TheWorkBlockEntities.ALCHEMY_CIRCLE_TYPE); + + if (mbe.isPresent()) + return mbe; + + for (BlockPos np : nPos) { + BlockPos total = np.add(next); + + if(total.getSquaredDistance(pos) > maxRadius * maxRadius) + continue; + + if (!searchedPositions.contains(total)) { + searchedPositions.add(total); + blockPosQueue.add(total); + } + } + } + + return Optional.empty(); + } + +} diff --git a/src/main/resources/assets/thework/icon.png b/src/main/resources/assets/thework/icon.png new file mode 100644 index 0000000..047b91f Binary files /dev/null and b/src/main/resources/assets/thework/icon.png differ diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..87c9c77 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,41 @@ +{ + "schemaVersion": 1, + "id": "thework", + "version": "${version}", + "name": "thework", + "description": "This is an example description! Tell everyone what your mod is about!", + "authors": [ + "Me!" + ], + "contact": { + "homepage": "https://fabricmc.net/", + "sources": "https://github.com/FabricMC/fabric-example-mod" + }, + "license": "CC0-1.0", + "icon": "assets/thework/icon.png", + "environment": "*", + "entrypoints": { + "main": [ + "cassunshine.thework.TheWorkMod" + ], + "client": [ + "cassunshine.thework.TheWorkClient" + ] + }, + "mixins": [ + "thework.mixins.json", + { + "config": "thework.client.mixins.json", + "environment": "client" + } + ], + "depends": { + "fabricloader": ">=0.15.6", + "minecraft": "~1.20.4", + "java": ">=17", + "fabric-api": "*" + }, + "suggests": { + "another-mod": "*" + } +} \ No newline at end of file diff --git a/src/main/resources/thework.mixins.json b/src/main/resources/thework.mixins.json new file mode 100644 index 0000000..eb2d29a --- /dev/null +++ b/src/main/resources/thework.mixins.json @@ -0,0 +1,11 @@ +{ + "required": true, + "package": "cassunshine.thework.mixin", + "compatibilityLevel": "JAVA_17", + "mixins": [ + "ExampleMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file