commit aa8fa05506ad64bd0c173334488c1e25d5877777 Author: Aran Roig Date: Sun Jul 12 17:00:44 2026 +0200 First commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# 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 + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..524fb1b --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,30 @@ +# 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: + runs-on: ubuntu-24.04 + steps: + - name: checkout repository + uses: actions/checkout@v6 + - name: validate gradle wrapper + uses: gradle/actions/wrapper-validation@v6 + - name: setup jdk + uses: actions/setup-java@v5 + with: + java-version: '25' + distribution: 'microsoft' + - name: make gradle wrapper executable + run: chmod +x ./gradlew + - name: build + run: ./gradlew build + - name: capture build artifacts + uses: actions/upload-artifact@v7 + with: + name: Artifacts + path: build/libs/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c476faf --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# 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/README.md b/README.md new file mode 100644 index 0000000..3ae2dc1 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# codecraft + +## Setup + +For setup instructions, please see the [Fabric Documentation page](https://docs.fabricmc.net/develop/getting-started/creating-a-project#setting-up) related to the IDE that you are using. + +## License + +This template is available under the CC0 license. Feel free to learn from it and incorporate it in your own projects. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..3995db1 --- /dev/null +++ b/build.gradle @@ -0,0 +1,97 @@ +plugins { + id 'net.fabricmc.fabric-loom' version "${loom_version}" + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +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. + mavenCentral() + maven { url = "https://maven.fabricmc.net" } + maven { url = "https://jitpack.io" } +} + +loom { + splitEnvironmentSourceSets() + + mods { + "codecraft" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } +} + +fabricApi { + configureDataGeneration { + client = true + } +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + + implementation 'party.iroiro.luajava:luajava:4.1.0' + implementation 'party.iroiro.luajava:luaj:4.1.0' + + implementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API. This is technically optional, but you probably want it anyway. + implementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}" +} + +processResources { + def version = project.version + inputs.property "version", version + + filesMatching("fabric.mod.json") { + expand "version": version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 25 +} + +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_25 + targetCompatibility = JavaVersion.VERSION_25 +} + +jar { + def projectName = project.name + inputs.property "projectName", projectName + + from("LICENSE") { + rename { "${it}_$projectName"} + } +} + +// configure the maven publication +publishing { + publications { + create("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. + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7ed5397 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,19 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +org.gradle.parallel=true + +# IntelliJ IDEA is not yet fully compatible with configuration cache, see: https://github.com/FabricMC/fabric-loom/issues/1349 +org.gradle.configuration-cache=false + +# Fabric Properties +# check these on https://fabricmc.net/develop +minecraft_version=26.2 +loader_version=0.19.3 +loom_version=1.17-SNAPSHOT + +# Mod Properties +mod_version=0.1 +maven_group=com.aranroig + +# Dependencies +fabric_api_version=0.153.0+26.2 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 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..df6a6ad --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..b9bb139 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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 + + + +# 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" ) + + 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" \ + -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..24c62d5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@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, and ensure extensions are enabled +setlocal EnableExtensions + +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 + +"%COMSPEC%" /c exit 1 + +: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 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..24625f4 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,14 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + maven { url = uri("https://jitpack.io") } + gradlePluginPortal() + } +} + +// Should match your modid +rootProject.name = 'codecraft' diff --git a/src/client/java/com/aranroig/client/CodecraftClient.java b/src/client/java/com/aranroig/client/CodecraftClient.java new file mode 100644 index 0000000..6c55e7b --- /dev/null +++ b/src/client/java/com/aranroig/client/CodecraftClient.java @@ -0,0 +1,46 @@ +package com.aranroig.client; + +import com.aranroig.Codecraft; +import com.aranroig.client.editor.EditorManager; +import com.mojang.blaze3d.platform.InputConstants; +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.minecraft.client.KeyMapping; +import net.minecraft.resources.Identifier; +import org.lwjgl.glfw.GLFW; +import net.fabricmc.fabric.api.client.keymapping.v1.KeyMappingHelper; + + +import javax.swing.text.JTextComponent; + +public class CodecraftClient implements ClientModInitializer { + + public static JTextComponent.KeyBinding OPEN_EDITOR; + + @Override + public void onInitializeClient() { + KeyMapping.Category CATEGORY = KeyMapping.Category.register( + Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "codecraft") + ); + + + KeyMapping openEditor = KeyMappingHelper.registerKeyMapping( + new KeyMapping( + "key.codecraft.open_editor", // The translation key for the key mapping. + InputConstants.Type.KEYSYM, // The type of the keybinding; KEYSYM for keyboard, MOUSE for mouse. + GLFW.GLFW_KEY_J, // The GLFW keycode of the key. + CATEGORY // The category of the mapping. + ) + ); + + EditorManager editorOverlay = new EditorManager(); + + ClientTickEvents.END_CLIENT_TICK.register(client -> { + while(openEditor.consumeClick()){ + if(client.player != null) { + editorOverlay.toggleVisible(); + } + } + }); + } +} \ No newline at end of file diff --git a/src/client/java/com/aranroig/client/CodecraftDataGenerator.java b/src/client/java/com/aranroig/client/CodecraftDataGenerator.java new file mode 100644 index 0000000..42623e0 --- /dev/null +++ b/src/client/java/com/aranroig/client/CodecraftDataGenerator.java @@ -0,0 +1,14 @@ +package com.aranroig.client; + +import com.aranroig.client.translations.CodecraftEnglishLangProvider; +import net.fabricmc.fabric.api.datagen.v1.DataGeneratorEntrypoint; +import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator; + +public class CodecraftDataGenerator implements DataGeneratorEntrypoint { + @Override + public void onInitializeDataGenerator(FabricDataGenerator fabricDataGenerator) { + FabricDataGenerator.Pack pack = fabricDataGenerator.createPack(); + + pack.addProvider(CodecraftEnglishLangProvider::new); + } +} diff --git a/src/client/java/com/aranroig/client/editor/EditorFileTree.java b/src/client/java/com/aranroig/client/editor/EditorFileTree.java new file mode 100644 index 0000000..76d5285 --- /dev/null +++ b/src/client/java/com/aranroig/client/editor/EditorFileTree.java @@ -0,0 +1,77 @@ +package com.aranroig.client.editor; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import org.jspecify.annotations.NonNull; + +import java.util.List; + +public class EditorFileTree extends Widget { + + private static final int COLOR_TEXT = 0xFFFFFFFF; + private static final int COLOR_BACKGROUND = 0xFF202020; + + public EditorFileTree(EditorManager editorManager) { + super(editorManager); + } + + public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) { + graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND); + + // Line numbers + text + /* + for (int i = firstLine; i <= lastLine; i++) { + int screenY = start_y + i * lineH - scrollY; + + // Line number — right-aligned, not scrolled horizontally + String lineNum = String.valueOf(i + 1); + int numW = font.width(lineNum); + graphics.text(font, lineNum, + gutterDivX() - 4 - numW, + screenY, COLOR_GUTTER_TEXT, false); + + // Code text — offset by scrollX + graphics.text(font, lines[i], textAreaX() - scrollX, screenY, COLOR_TEXT, true); + } + */ + Font font = editorScreen.getFont(); + int lineH = font.lineHeight; + List files = editorManager.getFiles(); + for(int i = 0; i < files.size(); i++) { + graphics.text(font, files.get(i).getName(), getStartX(), getStartY() + i * lineH, COLOR_TEXT, true); + } + } + + @Override + public boolean handleKeyPressed(KeyEvent event) { + return false; + } + + @Override + public boolean handleCharTyped(CharacterEvent event) { + return false; + } + + @Override + public boolean handleMouseClicked(MouseButtonEvent event) { + return false; + } + + @Override + public boolean handleMouseDragged(MouseButtonEvent event) { + return false; + } + + @Override + public boolean handleMouseReleased(MouseButtonEvent event) { + return false; + } + + @Override + public boolean handleMouseScrolled(double scrollY) { + return false; + } +} diff --git a/src/client/java/com/aranroig/client/editor/EditorFileView.java b/src/client/java/com/aranroig/client/editor/EditorFileView.java new file mode 100644 index 0000000..6325314 --- /dev/null +++ b/src/client/java/com/aranroig/client/editor/EditorFileView.java @@ -0,0 +1,478 @@ +package com.aranroig.client.editor; + +import com.aranroig.editor.EditorFile; +import com.aranroig.payloads.ServerboundSaveCodePayload; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import org.jspecify.annotations.NonNull; + +public class EditorFileView extends Widget { + + private StringBuilder text = new StringBuilder(); + + private EditorFile currentEditorFile; + + private int selectionAnchor = -1; + private int cursorPos = 0; + + private Font font; + + public EditorFileView(EditorManager editorManager) { + super(editorManager); + } + + // ── Scroll state ────────────────────────────────────────────────────── + private int scrollX = 0; // horizontal scroll in pixels + private int scrollY = 0; // vertical scroll in pixels + + /** How many pixels to scroll per mouse-wheel notch (vertically). */ + private static final int SCROLL_SPEED = 3; // lines per notch + + /** Width reserved for line numbers + a small right-padding. */ + private static final int GUTTER_WIDTH = 30; + private static final int GUTTER_MARGIN = 5; + + /** Where actual text content starts (after the gutter). */ + private int gutterDivX() { return getStartX() + GUTTER_WIDTH; } + private int textAreaX() { return getStartX() + GUTTER_WIDTH + GUTTER_MARGIN; } + + /** Visible width available for text (excludes gutter). */ + private int textAreaWidth() { return getEndX() - textAreaX(); } + /** Visible height available for text. */ + private int textAreaHeight() { return getEndY() - getStartY(); } + + // ── Colors ──────────────────────────────────────────────────────────── + private static final int COLOR_TEXT = 0xFFFFFFFF; + private static final int COLOR_CURSOR = 0xFFFFFFFF; + private static final int COLOR_SELECTION = 0x664466FF; + private static final int COLOR_GUTTER_BG = 0xFF252525; + private static final int COLOR_GUTTER_TEXT = 0xFF888888; + private static final int COLOR_GUTTER_DIV = 0xFF444444; + + // ───────────────────────────────────────────────────────────────────── + + private String[] getLines() { + return text.toString().split("\n", -1); + } + + private boolean hasSelection() { + return selectionAnchor >= 0 && selectionAnchor != cursorPos; + } + + /** Replaces \t with 4 spaces so font.width() measures correctly. */ + private String sanitize(String input) { + return input.replace("\t", " "); + } + + /** + * Returns the rendered pixel width of a prefix of a raw line up to + * character index {@code charCount}, expanding tabs properly. + */ + private int widthUpTo(String rawLine, int charCount) { + return font.width(sanitize(rawLine.substring(0, charCount))); + } + + // ── Scroll helpers ──────────────────────────────────────────────────── + + /** Maximum horizontal scroll so the widest line end is just visible. */ + private int maxScrollX() { + if (font == null) return 0; + int maxW = 0; + for (String line : getLines()) maxW = Math.max(maxW, font.width(sanitize(line))); + return Math.max(0, maxW - textAreaWidth()); + } + + /** Maximum vertical scroll so the last line is just visible. */ + private int maxScrollY() { + if (font == null) return 0; + int totalH = getLines().length * font.lineHeight; + return Math.max(0, totalH - textAreaHeight()); + } + + private void clampScroll() { + scrollX = Math.max(0, Math.min(scrollX, maxScrollX())); + scrollY = Math.max(0, Math.min(scrollY, maxScrollY())); + } + + /** + * Scrolls the view so the cursor is always visible. + * Call after any cursor movement. + */ + private void scrollToCursor() { + if (font == null) return; + int[] lc = offsetToLineCol(cursorPos); + String[] lines = getLines(); + String lineText = (lc[0] < lines.length) ? lines[lc[0]] : ""; + + // Vertical + int cursorTop = lc[0] * font.lineHeight; + int cursorBottom = cursorTop + font.lineHeight; + if (cursorTop < scrollY) + scrollY = cursorTop; + else if (cursorBottom > scrollY + textAreaHeight()) + scrollY = cursorBottom - textAreaHeight(); + + // Horizontal — measure sanitized prefix so tabs expand correctly + int cursorPx = widthUpTo(lineText, Math.min(lc[1], lineText.length())); + if (cursorPx < scrollX) + scrollX = cursorPx; + else if (cursorPx + 2 > scrollX + textAreaWidth()) + scrollX = cursorPx + 2 - textAreaWidth(); + + clampScroll(); + } + + // ── Coordinate mapping ──────────────────────────────────────────────── + + private int[] offsetToLineCol(int offset) { + String content = text.toString(); + int line = 0, col = 0; + for (int i = 0; i < offset && i < content.length(); i++) { + if (content.charAt(i) == '\n') { line++; col = 0; } + else { col++; } + } + return new int[]{line, col}; + } + + private int lineColToOffset(int targetLine, int targetCol) { + String[] lines = getLines(); + targetLine = Math.max(0, Math.min(targetLine, lines.length - 1)); + targetCol = Math.max(0, Math.min(targetCol, lines[targetLine].length())); + int offset = 0; + for (int i = 0; i < targetLine; i++) offset += lines[i].length() + 1; + return offset + targetCol; + } + + /** + * Maps a pixel coordinate to a text offset. + * Accounts for the gutter AND current scroll position. + * Uses sanitized widths so tab expansion is reflected in click targets. + */ + private int pixelToOffset(double mouseX, double mouseY) { + String[] lines = getLines(); + int lineH = font.lineHeight; + + // Apply scroll to convert screen coords → content coords + double contentY = mouseY - getStartY() + scrollY; + double contentX = mouseX - textAreaX() + scrollX; + + int clickedLine = (int) Math.floor(contentY / lineH); + clickedLine = Math.max(0, Math.min(clickedLine, lines.length - 1)); + + String lineText = lines[clickedLine]; + String sanitized = sanitize(lineText); + int col = 0; + for (int i = 0; i < lineText.length(); i++) { + // Measure using sanitized prefix widths so tabs count as 4 spaces + float charW = font.width(sanitized.substring(i, i + 1)); + float midPoint = font.width(sanitized.substring(0, i)) + charW / 2f; + if (contentX < midPoint) { col = i; break; } + col = i + 1; + } + return lineColToOffset(clickedLine, col); + } + + private void deleteSelection() { + if (selectionAnchor < 0) return; + int lo = Math.min(selectionAnchor, cursorPos); + int hi = Math.max(selectionAnchor, cursorPos); + text.delete(lo, hi); + cursorPos = lo; + selectionAnchor = -1; + } + + // ── Draw ────────────────────────────────────────────────────────────── + + public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) { + String[] lines = getLines(); + font = editorScreen.getFont(); + + int lineH = font.lineHeight; + + int start_x = getStartX(); + int start_y = getStartY(); + int end_x = getEndX(); + int end_y = getEndY(); + + graphics.enableScissor(start_x, start_y, end_x, end_y); + + // Background + graphics.fill(start_x, start_y, end_x, end_y, 0xFF303030); + + // Gutter background + divider (not scrolled — always fixed on left) + graphics.fill(start_x, start_y, gutterDivX() - 1, end_y, COLOR_GUTTER_BG); + graphics.fill(gutterDivX() - 1, start_y, gutterDivX(), end_y, COLOR_GUTTER_DIV); + + // Only render lines that are at least partially visible + int firstLine = Math.max(0, scrollY / lineH); + int lastLine = Math.min(lines.length - 1, (scrollY + textAreaHeight()) / lineH + 1); + + // Selection highlight + if (hasSelection()) { + int lo = Math.min(selectionAnchor, cursorPos); + int hi = Math.max(selectionAnchor, cursorPos); + + int[] loLC = offsetToLineCol(lo); + int[] hiLC = offsetToLineCol(hi); + + for (int ln = Math.max(loLC[0], firstLine); ln <= Math.min(hiLC[0], lastLine); ln++) { + String lineText = lines[ln]; + int colStart = (ln == loLC[0]) ? loLC[1] : 0; + int colEnd = (ln == hiLC[0]) ? hiLC[1] : lineText.length(); + + // Use sanitized widths so tabs expand correctly in the highlight + int x0 = textAreaX() + widthUpTo(lineText, colStart) - scrollX; + int x1 = textAreaX() + widthUpTo(lineText, colEnd) - scrollX; + if (x1 == x0) x1 = x0 + 2; + + // Clamp to text area so highlight doesn't bleed into the gutter + x0 = Math.max(x0, textAreaX()); + x1 = Math.min(x1, end_x); + + int screenY = start_y + ln * lineH - scrollY; + graphics.fill(x0, screenY, x1, screenY + lineH, COLOR_SELECTION); + } + } + + // Line numbers + text + for (int i = firstLine; i <= lastLine; i++) { + int screenY = start_y + i * lineH - scrollY; + + // Line number — right-aligned, not scrolled horizontally + String lineNum = String.valueOf(i + 1); + int numW = font.width(lineNum); + graphics.text(font, lineNum, + gutterDivX() - 4 - numW, + screenY, COLOR_GUTTER_TEXT, false); + + // Code text — sanitized so \t renders as 4 spaces, offset by scrollX + graphics.text(font, sanitize(lines[i]), textAreaX() - scrollX, screenY, COLOR_TEXT, true); + } + + // Blinking cursor + boolean showCursor = (System.currentTimeMillis() / 500) % 2 == 0; + if (showCursor) { + int[] lc = offsetToLineCol(cursorPos); + int ln = lc[0]; + int col = lc[1]; + + // Sanitize before measuring so the tab expansion is accounted for + int cursorX = textAreaX() + widthUpTo( + (ln < lines.length) ? lines[ln] : "", + (ln < lines.length) ? Math.min(col, lines[ln].length()) : 0 + ) - scrollX; + int cursorY = start_y + ln * lineH - scrollY; + + // Only draw cursor if it's within the visible text area + if (cursorX >= textAreaX() && cursorX <= end_x) { + graphics.fill(cursorX, cursorY, cursorX + 1, cursorY + lineH, COLOR_CURSOR); + } + } + + graphics.disableScissor(); + } + + // ── Input handlers ──────────────────────────────────────────────────── + + public boolean handleMouseClicked(MouseButtonEvent event) { + int clicked = pixelToOffset(event.x(), event.y()); + cursorPos = clicked; + selectionAnchor = clicked; + return true; + } + + public boolean handleMouseDragged(MouseButtonEvent event) { + cursorPos = pixelToOffset(event.x(), event.y()); + + // Auto-scroll when dragging outside the editor bounds + if (font != null) { + int lineH = font.lineHeight; + double my = event.y(); + double mx = event.x(); + + if (my < getStartY()) scrollY = Math.max(0, scrollY - lineH); + else if (my > getEndY()) scrollY = Math.min(maxScrollY(), scrollY + lineH); + + if (mx < textAreaX()) scrollX = Math.max(0, scrollX - 10); + else if (mx > getEndX()) scrollX = Math.min(maxScrollX(), scrollX + 10); + } + + return true; + } + + public boolean handleMouseReleased(MouseButtonEvent event) { + if (cursorPos == selectionAnchor) selectionAnchor = -1; + return true; + } + + /** + * Call this from your Screen's mouseScrolled override whenever inside() is true. + * + * @param delta positive = scroll up (content moves down), negative = scroll down + */ + public boolean handleMouseScrolled(double delta) { + if (font == null) return true; + int amount = (int) (delta * SCROLL_SPEED * font.lineHeight); + + scrollY = Math.max(0, Math.min(scrollY - amount, maxScrollY())); + + return true; + } + + public boolean handleCharTyped(CharacterEvent event) { + int codePoint = event.codepoint(); + if (codePoint >= 32 && codePoint != 127) { + if (hasSelection()) deleteSelection(); + text.insert(cursorPos, Character.toString(codePoint)); + cursorPos += Character.charCount(codePoint); + selectionAnchor = -1; + scrollToCursor(); + } + return true; + } + + public boolean handleKeyPressed(KeyEvent event) { + int key = event.key(); + boolean shift = event.hasShiftDown(); + boolean ctrl = event.hasControlDown(); + + Minecraft minecraft = Minecraft.getInstance(); + + switch (key) { + case 257 -> { // Enter + if (hasSelection()) deleteSelection(); + text.insert(cursorPos, '\n'); + cursorPos++; + selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 258 -> { // Tab + if (hasSelection()) deleteSelection(); + text.insert(cursorPos, '\t'); + cursorPos++; + selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 259 -> { // Backspace + if (hasSelection()) { deleteSelection(); } + else if (cursorPos > 0) { text.deleteCharAt(--cursorPos); } + selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 261 -> { // Delete + if (hasSelection()) { deleteSelection(); } + else if (cursorPos < text.length()) { text.deleteCharAt(cursorPos); } + selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 263 -> { // Left + if (shift) { + if (selectionAnchor < 0) selectionAnchor = cursorPos; + if (cursorPos > 0) cursorPos--; + } else { + if (hasSelection()) cursorPos = Math.min(selectionAnchor, cursorPos); + else if (cursorPos > 0) cursorPos--; + selectionAnchor = -1; + } + scrollToCursor(); + return true; + } + case 262 -> { // Right + if (shift) { + if (selectionAnchor < 0) selectionAnchor = cursorPos; + if (cursorPos < text.length()) cursorPos++; + } else { + if (hasSelection()) cursorPos = Math.max(selectionAnchor, cursorPos); + else if (cursorPos < text.length()) cursorPos++; + selectionAnchor = -1; + } + scrollToCursor(); + return true; + } + case 265 -> { // Up + if (shift && selectionAnchor < 0) selectionAnchor = cursorPos; + int[] lc = offsetToLineCol(cursorPos); + cursorPos = (lc[0] - 1 >= 0) ? lineColToOffset(lc[0] - 1, lc[1]) : 0; + if (!shift) selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 264 -> { // Down + if (shift && selectionAnchor < 0) selectionAnchor = cursorPos; + int[] lc2 = offsetToLineCol(cursorPos); + String[] lines = getLines(); + cursorPos = (lc2[0] + 1 < lines.length) + ? lineColToOffset(lc2[0] + 1, lc2[1]) + : text.length(); + if (!shift) selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 268 -> { // Home + if (shift && selectionAnchor < 0) selectionAnchor = cursorPos; + cursorPos = lineColToOffset(offsetToLineCol(cursorPos)[0], 0); + if (!shift) selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 269 -> { // End + if (shift && selectionAnchor < 0) selectionAnchor = cursorPos; + int[] lc4 = offsetToLineCol(cursorPos); + cursorPos = lineColToOffset(lc4[0], getLines()[lc4[0]].length()); + if (!shift) selectionAnchor = -1; + scrollToCursor(); + return true; + } + case 65 -> { // Ctrl+A + if (ctrl) { selectionAnchor = 0; cursorPos = text.length(); scrollToCursor(); return true; } + } + case 67, 88 -> { // Ctrl+C / Ctrl+X + if (ctrl && hasSelection()) { + int lo = Math.min(selectionAnchor, cursorPos); + int hi = Math.max(selectionAnchor, cursorPos); + minecraft.keyboardHandler.setClipboard(text.substring(lo, hi)); + if (key == 88) { deleteSelection(); scrollToCursor(); } + return true; + } + } + case 86 -> { // Ctrl+V + if (ctrl) { + if (hasSelection()) deleteSelection(); + String clip = minecraft.keyboardHandler.getClipboard(); + text.insert(cursorPos, clip); + cursorPos += clip.length(); + selectionAnchor = -1; + scrollToCursor(); + return true; + } + } + case 83 -> { // Ctrl+S + saveEditorFile(); + } + } + return false; + } + + public void setEditorFile(EditorFile currentEditorFile) { + this.currentEditorFile = currentEditorFile; + text = new StringBuilder(currentEditorFile.getText()); + } + + public void saveEditorFile() { + if(this.currentEditorFile == null) return; + this.currentEditorFile.setText(text.toString()); + + // Send save + ServerboundSaveCodePayload payload = new ServerboundSaveCodePayload(this.currentEditorFile); + ClientPlayNetworking.send(payload); + } +} \ No newline at end of file diff --git a/src/client/java/com/aranroig/client/editor/EditorManager.java b/src/client/java/com/aranroig/client/editor/EditorManager.java new file mode 100644 index 0000000..ea8dd2c --- /dev/null +++ b/src/client/java/com/aranroig/client/editor/EditorManager.java @@ -0,0 +1,83 @@ +package com.aranroig.client.editor; + +import com.aranroig.client.wrapper.Logger; +import net.minecraft.client.Minecraft; +import party.iroiro.luajava.Lua; +import party.iroiro.luajava.luaj.LuaJ; + +import java.util.ArrayList; +import java.util.List; + +public class EditorManager { + + Minecraft client; + + EditorFileTree editorFileTree; + EditorTopBar editorTopBar; + EditorFileView editorFileView; + + List files; + + public EditorManager() { + client = Minecraft.getInstance(); + + editorFileTree = new EditorFileTree(this); + editorTopBar = new EditorTopBar(this); + editorFileView = new EditorFileView(this); + + files = new ArrayList<>(); + + // Add example file + com.aranroig.editor.EditorFile editorFile = new com.aranroig.editor.EditorFile("test.lua", ""); + files.add(editorFile); + } + + public List getFiles() { + return files; + } + + private final int FILE_RENDER_WIDTH_SIZE = 150; + private final int TOP_BAR_HEIGHT = 12; + + public void toggleVisible() { + TextEditorScreen textEditorScreen = new TextEditorScreen(); + + // Populate screen with widgets + editorFileTree.setSize(0, TOP_BAR_HEIGHT, FILE_RENDER_WIDTH_SIZE, -1); + editorFileTree.addToEditorScreen(textEditorScreen); + + editorTopBar.setSize(0, 0, -1, TOP_BAR_HEIGHT); + editorTopBar.setZIndex(1); + editorTopBar.addToEditorScreen(textEditorScreen); + + editorFileView.setSize(FILE_RENDER_WIDTH_SIZE, TOP_BAR_HEIGHT, -1, -1); + editorFileView.setEditorFile(files.getFirst()); + editorFileView.addToEditorScreen(textEditorScreen); + + client.setScreenAndShow(textEditorScreen); + } + + public void newFile() { + } + + public void save() { + } + + public void undo() { + } + + public void run() { + String code = files.getFirst().getText(); + System.out.println(code); + + Lua l = new LuaJ(); + l.register("print", Logger.print()); + l.run(code); + } + + public void redo() { + } + + public void stop() { + } +} \ No newline at end of file diff --git a/src/client/java/com/aranroig/client/editor/EditorScreen.java b/src/client/java/com/aranroig/client/editor/EditorScreen.java new file mode 100644 index 0000000..3de9c3b --- /dev/null +++ b/src/client/java/com/aranroig/client/editor/EditorScreen.java @@ -0,0 +1,113 @@ +package com.aranroig.client.editor; + +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; + +import java.util.ArrayList; +import java.util.List; + +public abstract class EditorScreen extends Screen { + + private boolean isDragging = false; + + protected EditorScreen(Component title) { + super(title); + } + + protected List widgets = new ArrayList<>(); + + protected Widget selectedWidget; + + public void addWidget(Widget widget){ + widgets.add(widget); + } + + @Override + public boolean keyPressed(KeyEvent event) { + if(selectedWidget != null){ + if(selectedWidget.handleKeyPressed(event)) return true; + } + + return super.keyPressed(event); + } + + @Override + public boolean charTyped(CharacterEvent event) { + if(selectedWidget != null){ + if(selectedWidget.handleCharTyped(event)) + return true; + } + + return super.charTyped(event); + } + + @Override + public boolean keyReleased(KeyEvent event) { + return super.keyReleased(event); + } + + @Override + public boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick) { + selectedWidget = raycastWidget(event); + if(selectedWidget != null) + if (event.button() == 0) { // left button + isDragging = true; + if(selectedWidget.handleMouseClicked(event)) + return true; + } + return super.mouseClicked(event, doubleClick); + } + + @Override + public boolean mouseDragged(final MouseButtonEvent event, final double dx, final double dy) { + if(selectedWidget != null) + if (event.button() == 0 && isDragging) { + if(selectedWidget.handleMouseDragged(event)) + return true; + } + return super.mouseDragged(event, dx, dy); + } + + @Override + public boolean mouseReleased(final MouseButtonEvent event) { + if(selectedWidget != null) + if (event.button() == 0) { + isDragging = false; + if(selectedWidget.handleMouseReleased(event)) + return true; + } + return super.mouseReleased(event); + } + + @Override + public boolean mouseScrolled(final double x, final double y, final double scrollX, final double scrollY) { + if (selectedWidget != null){ + if (selectedWidget.inside(x, y)) { + // scrollY from GLFW: positive = up, which in our model = scroll content upward + if(selectedWidget.handleMouseScrolled(scrollY)) + return true; + } + } + + return super.mouseScrolled(x, y, scrollX, scrollY); + } + + private Widget raycastWidget(MouseButtonEvent event) { + Widget bestWidget = null; + for(Widget widget : widgets){ + if(widget.inside(event.x(), event.y())){ + if(bestWidget == null) bestWidget = widget; + else { + if(bestWidget.getZIndex() < widget.getZIndex()) { + bestWidget = widget; + } + } + } + } + return bestWidget; + } + +} diff --git a/src/client/java/com/aranroig/client/editor/EditorTopBar.java b/src/client/java/com/aranroig/client/editor/EditorTopBar.java new file mode 100644 index 0000000..9f871a2 --- /dev/null +++ b/src/client/java/com/aranroig/client/editor/EditorTopBar.java @@ -0,0 +1,314 @@ +package com.aranroig.client.editor; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import org.jspecify.annotations.NonNull; + +import java.util.List; + +public class EditorTopBar extends Widget { + public EditorTopBar(EditorManager editorManager) { + super(editorManager); + } + + private static final int BAR_HEIGHT = 12; + private static final int TAB_PADDING_X = 6; + private static final int TAB_PADDING_Y = 2; + + // ── Colors ──────────────────────────────────────────────────────────── + private static final int COLOR_TEXT = 0xFFFFFFFF; + private static final int COLOR_BACKGROUND = 0xFF1C1C1C; + private static final int COLOR_TAB_HOVER = 0xFF2D2D2D; + private static final int COLOR_TAB_OPEN = 0xFF3A3A3A; + private static final int COLOR_DROPDOWN_BG = 0xFF252525; + private static final int COLOR_ITEM_HOVER = 0xFF0055AA; + private static final int COLOR_SEPARATOR = 0xFF444444; + + + + // ── Menu definitions ────────────────────────────────────────────────── + private record MenuItem(String label, boolean isSeparator) { + static MenuItem item(String label) { return new MenuItem(label, false); } + static MenuItem separator() { return new MenuItem("", true); } + } + + private static final String[] TAB_LABELS = { "File", "Edit", "Run" }; + + private static final List> TAB_ITEMS = List.of( + // File + List.of( + MenuItem.item("New File"), + MenuItem.item("Open..."), + MenuItem.item("Save"), + MenuItem.item("Save As..."), + MenuItem.separator(), + MenuItem.item("Close") + ), + // Edit + List.of( + MenuItem.item("Undo"), + MenuItem.item("Redo"), + MenuItem.separator(), + MenuItem.item("Cut"), + MenuItem.item("Copy"), + MenuItem.item("Paste"), + MenuItem.separator(), + MenuItem.item("Find..."), + MenuItem.item("Replace...") + ), + // Run + List.of( + MenuItem.item("Run Script"), + MenuItem.item("Stop"), + MenuItem.separator(), + MenuItem.item("Build Project") + ) + ); + + // ── State ───────────────────────────────────────────────────────────── + /** Index of the currently open dropdown (-1 = none). */ + private int openTab = -1; + /** Mouse position, updated each frame from the screen. */ + private int mouseX, mouseY; + + // ── Drawing ─────────────────────────────────────────────────────────── + + public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) { + // Bar background + Font font = editorScreen.getFont(); + cachedFont = font; + graphics.fill(getStartX(), getStartY(), getEndX(), getStartY() + BAR_HEIGHT, COLOR_BACKGROUND); + this.mouseX = mouseX; + this.mouseY = mouseY; + + int tabX = getStartX(); + + for (int i = 0; i < TAB_LABELS.length; i++) { + String label = TAB_LABELS[i]; + int labelW = font.width(label); + int tabWidth = labelW + TAB_PADDING_X * 2; + int tabEndX = tabX + tabWidth; + int tabEndY = getStartY() + BAR_HEIGHT; + + boolean hovered = mouseX >= tabX && mouseX < tabEndX + && mouseY >= getStartY() && mouseY < tabEndY; + boolean isOpen = openTab == i; + + // Tab background + int bg = isOpen ? COLOR_TAB_OPEN : (hovered ? COLOR_TAB_HOVER : COLOR_BACKGROUND); + graphics.fill(tabX, getStartY(), tabEndX, tabEndY, bg); + + // Tab label + graphics.text(font, label, + tabX + TAB_PADDING_X, + getStartY() + TAB_PADDING_Y, + COLOR_TEXT, false); + + // Dropdown + if (isOpen) { + drawDropdown(graphics, font, i, tabX, tabEndY); + } + + tabX = tabEndX; + } + } + + @Override + public boolean handleKeyPressed(KeyEvent event) { + return false; + } + + @Override + public boolean handleCharTyped(CharacterEvent event) { + return false; + } + + @Override + public boolean handleMouseClicked(MouseButtonEvent event) { + int button = event.button(); + double mx = event.x(); + double my = event.y(); + + if (button != 0) return false; + + int imx = (int) mx; + int imy = (int) my; + + // Click on a tab label? + int tabX = getStartX(); + for (int i = 0; i < TAB_LABELS.length; i++) { + int tabW = font().width(TAB_LABELS[i]) + TAB_PADDING_X * 2; + int tabEndX = tabX + tabW; + + if (imx >= tabX && imx < tabEndX + && imy >= getStartY() && imy < getStartY() + BAR_HEIGHT) { + openTab = (openTab == i) ? -1 : i; + return true; + } + tabX = tabEndX; + } + + // Click on a dropdown item? + if (openTab >= 0) { + int result = getClickedItemIndex(imx, imy, openTab); + if (result >= 0) { + onItemClicked(openTab, result); + openTab = -1; + return true; + } + // Click outside → close + openTab = -1; + } + + return false; + } + + @Override + public boolean handleMouseDragged(MouseButtonEvent event) { + return false; + } + + @Override + public boolean handleMouseReleased(MouseButtonEvent event) { + return false; + } + + @Override + public boolean handleMouseScrolled(double scrollY) { + return false; + } + + private void drawDropdown(@NonNull GuiGraphicsExtractor graphics, Font font, + int tabIndex, int tabX, int topY) { + List items = TAB_ITEMS.get(tabIndex); + int dropW = dropdownWidth(font, tabIndex); + int dropX2 = tabX + dropW; + int itemH = font.lineHeight + TAB_PADDING_Y * 2; + + // Calculate total height + int totalH = 0; + for (MenuItem m : items) totalH += m.isSeparator() ? 5 : itemH; + + // Background + border + graphics.fill(tabX, topY, dropX2, topY + totalH, COLOR_DROPDOWN_BG); + graphics.fill(tabX, topY, dropX2, topY + 1, COLOR_SEPARATOR); // top + graphics.fill(tabX, topY, tabX + 1, topY + totalH, COLOR_SEPARATOR); // left + graphics.fill(dropX2-1, topY, dropX2, topY + totalH, COLOR_SEPARATOR); // right + graphics.fill(tabX, topY+totalH-1, dropX2, topY + totalH, COLOR_SEPARATOR); // bottom + + int curY = topY; + for (MenuItem item : items) { + if (item.isSeparator()) { + graphics.fill(tabX + 4, curY + 2, dropX2 - 4, curY + 3, COLOR_SEPARATOR); + curY += 5; + } else { + boolean hovered = mouseX >= tabX && mouseX < dropX2 + && mouseY >= curY && mouseY < curY + itemH; + + if (hovered) { + graphics.fill(tabX + 1, curY, dropX2 - 1, curY + itemH, COLOR_ITEM_HOVER); + } + + graphics.text(font, item.label(), + tabX + TAB_PADDING_X, + curY + TAB_PADDING_Y, + COLOR_TEXT, false); + + curY += itemH; + } + } + } + + // ── Item action dispatch ────────────────────────────────────────────── + + private void onItemClicked(int tabIndex, int itemIndex) { + MenuItem item = TAB_ITEMS.get(tabIndex).get(itemIndex); + if (item.isSeparator()) return; + + // TODO: wire these to your EditorManager + switch (item.label()) { + case "New File" -> editorManager.newFile(); + case "Save" -> editorManager.save(); + case "Undo" -> editorManager.undo(); + case "Redo" -> editorManager.redo(); + case "Run Script" -> editorManager.run(); + case "Stop" -> editorManager.stop(); + // Add remaining cases as needed + default -> System.out.println("[TopBar] Clicked: " + item.label()); + } + } + + // ── Helpers ─────────────────────────────────────────────────────────── + + private int dropdownWidth(Font font, int tabIndex) { + int maxW = 80; // minimum dropdown width + for (MenuItem item : TAB_ITEMS.get(tabIndex)) { + if (!item.isSeparator()) { + maxW = Math.max(maxW, font.width(item.label()) + TAB_PADDING_X * 2 + 8); + } + } + return maxW; + } + + private int getClickedItemIndex(int mx, int my, int tabIndex) { + int tabX = getStartX(); + for (int i = 0; i < tabIndex; i++) { + tabX += font().width(TAB_LABELS[i]) + TAB_PADDING_X * 2; + } + + int dropW = dropdownWidth(font(), tabIndex); + int topY = getStartY() + BAR_HEIGHT; + int itemH = font().lineHeight + TAB_PADDING_Y * 2; + int curY = topY; + + List items = TAB_ITEMS.get(tabIndex); + for (int i = 0; i < items.size(); i++) { + MenuItem item = items.get(i); + int h = item.isSeparator() ? 5 : itemH; + if (!item.isSeparator() + && mx >= tabX && mx < tabX + dropW + && my >= curY && my < curY + h) { + return i; + } + curY += h; + } + return -1; + } + + @Override + public boolean inside(double x, double y) { + if (getStartX() <= x && x <= getEndX() && getStartY() <= y && y <= getEndY()) { + return true; + } + + if (openTab >= 0 && cachedFont != null) { + // Find the X origin of the open tab + int tabX = getStartX(); + for (int i = 0; i < openTab; i++) { + tabX += cachedFont.width(TAB_LABELS[i]) + TAB_PADDING_X * 2; + } + + int dropW = dropdownWidth(cachedFont, openTab); + int topY = getStartY() + BAR_HEIGHT; + int itemH = cachedFont.lineHeight + TAB_PADDING_Y * 2; + + int totalH = 0; + for (MenuItem m : TAB_ITEMS.get(openTab)) { + totalH += m.isSeparator() ? 5 : itemH; + } + + if (tabX <= x && x <= tabX + dropW && topY <= y && y <= topY + totalH) { + return true; + } + } + + return false; + } + + /** Lazy accessor — store the font reference after the first draw() call if preferred. */ + private Font cachedFont; + private Font font() { return cachedFont; } +} \ No newline at end of file diff --git a/src/client/java/com/aranroig/client/editor/TextEditorScreen.java b/src/client/java/com/aranroig/client/editor/TextEditorScreen.java new file mode 100644 index 0000000..79670bc --- /dev/null +++ b/src/client/java/com/aranroig/client/editor/TextEditorScreen.java @@ -0,0 +1,35 @@ +package com.aranroig.client.editor; + +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.network.chat.Component; +import org.jspecify.annotations.NonNull; + +public class TextEditorScreen extends EditorScreen { + + /** True while the left mouse button is held down during a drag-select. */ + + public TextEditorScreen() { + super(Component.literal("Codecraft Editor")); + } + + + @Override + public void extractRenderState( + @NonNull GuiGraphicsExtractor graphics, + int mouseX, + int mouseY, + float delta + ) { + super.extractRenderState(graphics, mouseX, mouseY, delta); + + for (Widget widget : widgets) { + widget.draw( + graphics, + mouseX, + mouseY, + delta + ); + } + } + +} \ No newline at end of file diff --git a/src/client/java/com/aranroig/client/editor/Widget.java b/src/client/java/com/aranroig/client/editor/Widget.java new file mode 100644 index 0000000..ae01cfe --- /dev/null +++ b/src/client/java/com/aranroig/client/editor/Widget.java @@ -0,0 +1,84 @@ +package com.aranroig.client.editor; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import org.jspecify.annotations.NonNull; + +public abstract class Widget { + + private int start_x = 0; + private int start_y = 0; + private int end_x = 0; + private int end_y = 0; + + private int z_index = 0; + + private Screen s; + + // Maybe moure aixo per més genèric? + public EditorManager editorManager; + + public Widget(EditorManager editorManager) { + this.editorManager = editorManager; + } + + public boolean inside(double x, double y) { + return getStartX() <= x && x <= getEndX() && getStartY() <= y && y <= getEndY(); + } + + public void setSize(int start_x, int start_y, int end_x, int end_y) { + this.start_x = start_x; + this.start_y = start_y; + this.end_x = end_x; + this.end_y = end_y; + } + + public abstract void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta); + + public int getStartX() { + return normalize(start_x, editorScreen.width); + } + + public int getStartY() { + return normalize(start_y, editorScreen.height); + } + + public int getEndX() { + return normalize(end_x, editorScreen.width); + } + + public int getEndY() { + return normalize(end_y, editorScreen.height); + } + + private int normalize(int start, int total) { + if(start < 0) return total + start + 1; + return start; + } + + protected EditorScreen editorScreen; + + public void addToEditorScreen(EditorScreen editorScreen){ + this.editorScreen = editorScreen; + editorScreen.addWidget(this); + } + + public abstract boolean handleKeyPressed(KeyEvent event); + public abstract boolean handleCharTyped(CharacterEvent event); + public abstract boolean handleMouseClicked(MouseButtonEvent event); + public abstract boolean handleMouseDragged(MouseButtonEvent event); + public abstract boolean handleMouseReleased(MouseButtonEvent event); + public abstract boolean handleMouseScrolled(double scrollY); + + public int getZIndex() { + return z_index; + } + + public void setZIndex(int z_index) { + this.z_index = z_index; + } +} diff --git a/src/client/java/com/aranroig/client/mixin/ExampleClientMixin.java b/src/client/java/com/aranroig/client/mixin/ExampleClientMixin.java new file mode 100644 index 0000000..ebc7730 --- /dev/null +++ b/src/client/java/com/aranroig/client/mixin/ExampleClientMixin.java @@ -0,0 +1,15 @@ +package com.aranroig.client.mixin; + +import net.minecraft.client.Minecraft; +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(Minecraft.class) +public class ExampleClientMixin { + @Inject(at = @At("HEAD"), method = "run") + private void init(CallbackInfo info) { + // This code is injected into the start of Minecraft.run()V + } +} \ No newline at end of file diff --git a/src/client/java/com/aranroig/client/translations/CodecraftEnglishLangProvider.java b/src/client/java/com/aranroig/client/translations/CodecraftEnglishLangProvider.java new file mode 100644 index 0000000..6987ffd --- /dev/null +++ b/src/client/java/com/aranroig/client/translations/CodecraftEnglishLangProvider.java @@ -0,0 +1,19 @@ +package com.aranroig.client.translations; + +import net.fabricmc.fabric.api.datagen.v1.FabricPackOutput; +import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider; +import net.minecraft.core.HolderLookup; + +import java.util.concurrent.CompletableFuture; + +public class CodecraftEnglishLangProvider extends FabricLanguageProvider { + public CodecraftEnglishLangProvider(FabricPackOutput dataOutput, CompletableFuture registryLookup) { + super(dataOutput, "en_us", registryLookup); + } + + @Override + public void generateTranslations(HolderLookup.Provider registryLookup, TranslationBuilder translationBuilder) { + translationBuilder.add("key.codecraft.open_editor", "Open Editor"); + translationBuilder.add("key.category.codecraft.codecraft", "Codecraft"); + } +} diff --git a/src/client/java/com/aranroig/client/wrapper/Logger.java b/src/client/java/com/aranroig/client/wrapper/Logger.java new file mode 100644 index 0000000..f8dbf4e --- /dev/null +++ b/src/client/java/com/aranroig/client/wrapper/Logger.java @@ -0,0 +1,24 @@ +package com.aranroig.client.wrapper; + +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; +import party.iroiro.luajava.value.LuaFunction; + +public class Logger { + public static LuaFunction print(){ + return (lua, args) -> { + Minecraft client = Minecraft.getInstance(); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < args.length; i++) { + if (i > 0) sb.append('\t'); + sb.append(args[i]); + } + + client.player.sendSystemMessage(Component.literal(sb.toString())); + + return null; + }; + } +} diff --git a/src/client/resources/codecraft.client.mixins.json b/src/client/resources/codecraft.client.mixins.json new file mode 100644 index 0000000..8fad0d9 --- /dev/null +++ b/src/client/resources/codecraft.client.mixins.json @@ -0,0 +1,14 @@ +{ + "required": true, + "package": "com.aranroig.client.mixin", + "compatibilityLevel": "JAVA_25", + "client": [ + "ExampleClientMixin" + ], + "injectors": { + "defaultRequire": 1 + }, + "overwrites": { + "requireAnnotations": true + } +} \ No newline at end of file diff --git a/src/main/generated/assets/codecraft/lang/en_us.json b/src/main/generated/assets/codecraft/lang/en_us.json new file mode 100644 index 0000000..52c8d0b --- /dev/null +++ b/src/main/generated/assets/codecraft/lang/en_us.json @@ -0,0 +1,4 @@ +{ + "key.category.codecraft.codecraft": "Codecraft", + "key.codecraft.open_editor": "Open Editor" +} \ No newline at end of file diff --git a/src/main/java/com/aranroig/Codecraft.java b/src/main/java/com/aranroig/Codecraft.java new file mode 100644 index 0000000..c7f0ecb --- /dev/null +++ b/src/main/java/com/aranroig/Codecraft.java @@ -0,0 +1,39 @@ +package com.aranroig; + +import com.aranroig.payloads.ServerboundSaveCodePayload; +import net.fabricmc.api.ModInitializer; + +import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.resources.Identifier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Codecraft implements ModInitializer { + public static final String MOD_ID = "codecraft"; + + // This logger is used to write text to the console and the log file. + // It is considered best practice to use your mod id as the logger's name. + // That way, it's clear which mod wrote info, warnings, and errors. + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + LOGGER.info("Hello Fabric world!"); + + PayloadTypeRegistry.serverboundPlay().register(ServerboundSaveCodePayload.TYPE, ServerboundSaveCodePayload.CODEC); + + ServerPlayNetworking.registerGlobalReceiver(ServerboundSaveCodePayload.TYPE, (payload, context) -> { + System.out.println(payload.data().getName()); + System.out.println(payload.data().getText()); + }); + } + + public static Identifier id(String path) { + return Identifier.fromNamespaceAndPath(MOD_ID, path); + } +} diff --git a/src/main/java/com/aranroig/editor/EditorFile.java b/src/main/java/com/aranroig/editor/EditorFile.java new file mode 100644 index 0000000..393781f --- /dev/null +++ b/src/main/java/com/aranroig/editor/EditorFile.java @@ -0,0 +1,40 @@ +package com.aranroig.editor; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; + +public class EditorFile { + public static final StreamCodec CODEC = + StreamCodec.composite( + ByteBufCodecs.STRING_UTF8, + EditorFile::getName, + + ByteBufCodecs.STRING_UTF8, + EditorFile::getText, + + EditorFile::new + ); + + // Class with file info + private String name; + private String text; + + public EditorFile(String name, String text) { + this.name = name; + this.text = text; + } + + public String getName() { + return name; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + +} diff --git a/src/main/java/com/aranroig/mixin/ExampleMixin.java b/src/main/java/com/aranroig/mixin/ExampleMixin.java new file mode 100644 index 0000000..127ffbe --- /dev/null +++ b/src/main/java/com/aranroig/mixin/ExampleMixin.java @@ -0,0 +1,15 @@ +package com.aranroig.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 = "loadLevel") + private void init(CallbackInfo info) { + // This code is injected into the start of MinecraftServer.loadLevel()V + } +} \ No newline at end of file diff --git a/src/main/java/com/aranroig/payloads/ClientboundSaveCodePayload.java b/src/main/java/com/aranroig/payloads/ClientboundSaveCodePayload.java new file mode 100644 index 0000000..197f800 --- /dev/null +++ b/src/main/java/com/aranroig/payloads/ClientboundSaveCodePayload.java @@ -0,0 +1,23 @@ +package com.aranroig.payloads; + +import com.aranroig.Codecraft; +import com.aranroig.editor.EditorFile; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; + +public record ClientboundSaveCodePayload(EditorFile data) implements CustomPacketPayload { + + public static final Identifier SAVE_CODE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "save_code"); + + public static final CustomPacketPayload.Type TYPE = new CustomPacketPayload.Type<>(SAVE_CODE_PAYLOAD_ID); + + public static final StreamCodec CODEC = + StreamCodec.composite(EditorFile.CODEC, ClientboundSaveCodePayload::data, ClientboundSaveCodePayload::new); + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/com/aranroig/payloads/ServerboundSaveCodePayload.java b/src/main/java/com/aranroig/payloads/ServerboundSaveCodePayload.java new file mode 100644 index 0000000..2deb09c --- /dev/null +++ b/src/main/java/com/aranroig/payloads/ServerboundSaveCodePayload.java @@ -0,0 +1,22 @@ +package com.aranroig.payloads; + +import com.aranroig.Codecraft; +import com.aranroig.editor.EditorFile; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; + +public record ServerboundSaveCodePayload(EditorFile data) implements CustomPacketPayload { + public static final Identifier SAVE_CODE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "save_code"); + + public static final CustomPacketPayload.Type TYPE = new CustomPacketPayload.Type<>(SAVE_CODE_PAYLOAD_ID); + + public static final StreamCodec CODEC = + StreamCodec.composite(EditorFile.CODEC, ServerboundSaveCodePayload::data, ServerboundSaveCodePayload::new); + + @Override + public CustomPacketPayload.Type type() { + return TYPE; + } +} diff --git a/src/main/resources/assets/codecraft/icon.png b/src/main/resources/assets/codecraft/icon.png new file mode 100644 index 0000000..1f56d2e Binary files /dev/null and b/src/main/resources/assets/codecraft/icon.png differ diff --git a/src/main/resources/codecraft.mixins.json b/src/main/resources/codecraft.mixins.json new file mode 100644 index 0000000..87d7912 --- /dev/null +++ b/src/main/resources/codecraft.mixins.json @@ -0,0 +1,14 @@ +{ + "required": true, + "package": "com.aranroig.mixin", + "compatibilityLevel": "JAVA_25", + "mixins": [ + "ExampleMixin" + ], + "injectors": { + "defaultRequire": 1 + }, + "overwrites": { + "requireAnnotations": true + } +} \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..ac6cd08 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,41 @@ +{ + "schemaVersion": 1, + "id": "codecraft", + "version": "${version}", + "name": "codecraft", + "description": "Codecraft Mod", + "authors": [ + "Aran Roig" + ], + "contact": { + "homepage": "https://aranroig.com/", + "sources": "https://github.com/FabricMC/fabric-example-mod" + }, + "license": "CC0-1.0", + "icon": "assets/codecraft/icon.png", + "environment": "*", + "entrypoints": { + "main": [ + "com.aranroig.Codecraft" + ], + "client": [ + "com.aranroig.client.CodecraftClient" + ], + "fabric-datagen": [ + "com.aranroig.client.CodecraftDataGenerator" + ] + }, + "mixins": [ + "codecraft.mixins.json", + { + "config": "codecraft.client.mixins.json", + "environment": "client" + } + ], + "depends": { + "fabricloader": ">=0.19.3", + "minecraft": "~26.2", + "java": ">=25", + "fabric-api": "*" + } +} \ No newline at end of file