Skip to content

Commit

Permalink
Fixed generateData not being called for server registries, disabled s…
Browse files Browse the repository at this point in the history
…cript loading during datagen gradle task, cleaned up event handlers, added custom formatted name support for blocks, removed BasicItemJS
  • Loading branch information
LatvianModder committed Jul 25, 2024
1 parent 07087b5 commit 3f55a8b
Show file tree
Hide file tree
Showing 20 changed files with 233 additions and 224 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import dev.latvian.mods.kubejs.fluid.ThickFluidBuilder;
import dev.latvian.mods.kubejs.fluid.ThinFluidBuilder;
import dev.latvian.mods.kubejs.item.ArmorMaterialBuilder;
import dev.latvian.mods.kubejs.item.ItemBuilder;
import dev.latvian.mods.kubejs.item.ItemEnchantmentsWrapper;
import dev.latvian.mods.kubejs.item.ItemPredicate;
import dev.latvian.mods.kubejs.item.ItemStackJS;
Expand All @@ -67,7 +68,6 @@
import dev.latvian.mods.kubejs.item.JukeboxSongBuilder;
import dev.latvian.mods.kubejs.item.creativetab.CreativeTabBuilder;
import dev.latvian.mods.kubejs.item.custom.ArmorItemBuilder;
import dev.latvian.mods.kubejs.item.custom.BasicItemJS;
import dev.latvian.mods.kubejs.item.custom.DiggerItemBuilder;
import dev.latvian.mods.kubejs.item.custom.ShearsItemBuilder;
import dev.latvian.mods.kubejs.item.custom.SmithingTemplateItemBuilder;
Expand Down Expand Up @@ -271,7 +271,7 @@ public void registerBuilderTypes(BuilderTypeRegistry registry) {
reg.add("carpet", CarpetBlockBuilder.class, CarpetBlockBuilder::new);
});

registry.addDefault(Registries.ITEM, BasicItemJS.Builder.class, BasicItemJS.Builder::new);
registry.addDefault(Registries.ITEM, ItemBuilder.class, ItemBuilder::new);

registry.of(Registries.ITEM, reg -> {
reg.add("sword", SwordItemBuilder.class, SwordItemBuilder::new);
Expand Down
148 changes: 12 additions & 136 deletions src/main/java/dev/latvian/mods/kubejs/KubeJS.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,65 +8,36 @@
import dev.latvian.mods.kubejs.gui.KubeJSMenus;
import dev.latvian.mods.kubejs.holder.KubeJSHolderSets;
import dev.latvian.mods.kubejs.ingredient.KubeJSIngredients;
import dev.latvian.mods.kubejs.item.creativetab.CreativeTabCallbackForge;
import dev.latvian.mods.kubejs.item.creativetab.CreativeTabKubeEvent;
import dev.latvian.mods.kubejs.item.creativetab.KubeJSCreativeTabs;
import dev.latvian.mods.kubejs.level.ruletest.KubeJSRuleTests;
import dev.latvian.mods.kubejs.plugin.KubeJSPlugin;
import dev.latvian.mods.kubejs.plugin.KubeJSPlugins;
import dev.latvian.mods.kubejs.recipe.KubeJSRecipeSerializers;
import dev.latvian.mods.kubejs.registry.RegistryType;
import dev.latvian.mods.kubejs.script.ConsoleJS;
import dev.latvian.mods.kubejs.script.ConsoleLine;
import dev.latvian.mods.kubejs.script.KubeJSBackgroundThread;
import dev.latvian.mods.kubejs.script.PlatformWrapper;
import dev.latvian.mods.kubejs.script.ScriptFileInfo;
import dev.latvian.mods.kubejs.script.ScriptManager;
import dev.latvian.mods.kubejs.script.ScriptPack;
import dev.latvian.mods.kubejs.script.ScriptType;
import dev.latvian.mods.kubejs.script.ScriptsLoadedEvent;
import dev.latvian.mods.kubejs.script.data.KubeFileResourcePack;
import dev.latvian.mods.kubejs.util.RecordDefaults;
import dev.latvian.mods.kubejs.util.UtilsJS;
import net.minecraft.Util;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.ModList;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.fml.event.lifecycle.FMLLoadCompleteEvent;
import net.neoforged.fml.loading.FMLLoader;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.common.NeoForgeMod;
import net.neoforged.neoforge.event.AddPackFindersEvent;
import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent;
import net.neoforged.neoforgespi.language.IModFileInfo;
import net.neoforged.neoforgespi.language.IModInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;

@Mod(KubeJS.MOD_ID)
@EventBusSubscriber(modid = KubeJS.MOD_ID, bus = EventBusSubscriber.Bus.MOD)
public class KubeJS {
public static final String MOD_ID = "kubejs";
public static final String MOD_NAME = "KubeJS";
Expand Down Expand Up @@ -99,6 +70,7 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable {
modEventBus = bus;
thisMod = mod;
VERSION = mod.getModInfo().getVersion().toString();
QUERY = "source=kubejs&mc=" + MC_VERSION_NUMBER + "&loader=neoforge&v=" + URLEncoder.encode(mod.getModInfo().getVersion().toString(), StandardCharsets.UTF_8);

if (Files.notExists(KubeJSPaths.README)) {
try {
Expand Down Expand Up @@ -127,7 +99,9 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable {

RecordDefaults.init();

if (!PlatformWrapper.isGeneratingData()) {
boolean datagen = PlatformWrapper.isGeneratingData();

if (!datagen) {
new KubeJSBackgroundThread().start();
// Required to be called this way because ConsoleJS class hasn't been initialized yet
ScriptType.STARTUP.console.startCapturingErrors();
Expand All @@ -148,11 +122,17 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable {
KubeJSPlugins.forEachPlugin(KubeJSPlugin::init);

startupScriptManager = new StartupScriptManager();
startupScriptManager.reload();

if (!datagen) {
startupScriptManager.reload();
}

if (dist.isClient()) {
clientScriptManager = new ClientScriptManager();
clientScriptManager.reload();

if (!datagen) {
clientScriptManager.reload();
}
}

KubeJSPlugins.forEachPlugin(KubeJSPlugin::initStartup);
Expand Down Expand Up @@ -180,108 +160,4 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable {
StartupEvents.INIT.post(ScriptType.STARTUP, KubeStartupEvent.BASIC);
// KubeJSRegistries.chunkGenerators().register(new ResourceLocation(KubeJS.MOD_ID, "flat"), () -> KJSFlatLevelSource.CODEC);
}

public static void loadScripts(ScriptPack pack, Path dir, String path) {
if (!path.isEmpty() && !path.endsWith("/")) {
path += "/";
}

final var pathPrefix = path;

try {
for (var file : Files.walk(dir, 10, FileVisitOption.FOLLOW_LINKS).filter(Files::isRegularFile).toList()) {
var fileName = dir.relativize(file).toString().replace(File.separatorChar, '/');

if (fileName.endsWith(".js") || fileName.endsWith(".ts") && !fileName.endsWith(".d.ts")) {
pack.info.scripts.add(new ScriptFileInfo(pack.info, file, pathPrefix + fileName));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

public static Path verifyFilePath(Path path) throws IOException {
if (!path.normalize().toAbsolutePath().startsWith(KubeJSPaths.GAMEDIR)) {
throw new IOException("You can't access files outside Minecraft directory!");
}

return path;
}

@SubscribeEvent(priority = EventPriority.LOW)
public static void commonSetup(FMLCommonSetupEvent event) {
}

@SubscribeEvent(priority = EventPriority.LOW)
public static void creativeTab(BuildCreativeModeTabContentsEvent event) {
var tabId = event.getTabKey().location();

if (StartupEvents.MODIFY_CREATIVE_TAB.hasListeners(tabId)) {
StartupEvents.MODIFY_CREATIVE_TAB.post(ScriptType.STARTUP, tabId, new CreativeTabKubeEvent(event.getTab(), event.hasPermissions(), new CreativeTabCallbackForge(event)));
}
}

@SubscribeEvent(priority = EventPriority.LOW)
public static void loadComplete(FMLLoadCompleteEvent event) {
KubeJSPlugins.forEachPlugin(KubeJSPlugin::afterInit);
NeoForge.EVENT_BUS.post(new ScriptsLoadedEvent());
StartupEvents.POST_INIT.post(ScriptType.STARTUP, KubeStartupEvent.BASIC);
UtilsJS.postModificationEvents();

if (!ConsoleJS.STARTUP.errors.isEmpty()) {
var list = new ArrayList<String>();
list.add("Startup script errors:");

var lines = ConsoleJS.STARTUP.errors.toArray(ConsoleLine.EMPTY_ARRAY);

for (int i = 0; i < lines.length; i++) {
list.add((i + 1) + ") " + lines[i]);
}

LOGGER.error(String.join("\n", list));

ConsoleJS.STARTUP.flush(true);

if (FMLLoader.getDist() == Dist.DEDICATED_SERVER || !CommonProperties.get().startupErrorGUI) {
throw new RuntimeException("There were KubeJS startup script syntax errors! See logs/kubejs/startup.log for more info");
}
}

ConsoleJS.STARTUP.stopCapturingErrors();

QUERY = "source=kubejs&mc=" + MC_VERSION_NUMBER + "&loader=neoforge&v=" + URLEncoder.encode(thisMod.getModInfo().getVersion().toString(), StandardCharsets.UTF_8);

Util.nonCriticalIoPool().submit(() -> {
try {
var response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.connectTimeout(Duration.ofSeconds(5L))
.build()
.send(HttpRequest.newBuilder().uri(URI.create("https://v.kubejs.com/update-check?" + QUERY)).GET().build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() == 200) {
var body = response.body().trim();

if (!body.isEmpty()) {
ConsoleJS.STARTUP.info("Update available: " + body);
}
}
} catch (Exception ignored) {
}
});
}

@SubscribeEvent(priority = EventPriority.HIGH)
public static void addPacksFirst(AddPackFindersEvent event) {
if (event.getPackType() == PackType.SERVER_DATA) {
// ServerScriptManager.addPacksFirst(event);
}
}

@SubscribeEvent(priority = EventPriority.LOW)
public static void addPacksLast(AddPackFindersEvent event) {
if (event.getPackType() == PackType.SERVER_DATA) {
// ServerScriptManager.addPacksLast(event);
}
}
}
117 changes: 117 additions & 0 deletions src/main/java/dev/latvian/mods/kubejs/KubeJSModEventHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package dev.latvian.mods.kubejs;

import dev.latvian.mods.kubejs.bindings.event.StartupEvents;
import dev.latvian.mods.kubejs.event.KubeStartupEvent;
import dev.latvian.mods.kubejs.item.creativetab.CreativeTabCallbackForge;
import dev.latvian.mods.kubejs.item.creativetab.CreativeTabKubeEvent;
import dev.latvian.mods.kubejs.plugin.KubeJSPlugin;
import dev.latvian.mods.kubejs.plugin.KubeJSPlugins;
import dev.latvian.mods.kubejs.script.ConsoleJS;
import dev.latvian.mods.kubejs.script.ConsoleLine;
import dev.latvian.mods.kubejs.script.ScriptType;
import dev.latvian.mods.kubejs.script.ScriptsLoadedEvent;
import dev.latvian.mods.kubejs.util.UtilsJS;
import net.minecraft.Util;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.event.lifecycle.FMLLoadCompleteEvent;
import net.neoforged.fml.loading.FMLLoader;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;

@EventBusSubscriber(modid = KubeJS.MOD_ID, bus = EventBusSubscriber.Bus.MOD)
public class KubeJSModEventHandler {
/*
@SubscribeEvent(priority = EventPriority.LOW)
public static void commonSetup(FMLCommonSetupEvent event) {
}
*/

@SubscribeEvent(priority = EventPriority.LOW)
public static void creativeTab(BuildCreativeModeTabContentsEvent event) {
var tabId = event.getTabKey().location();

if (StartupEvents.MODIFY_CREATIVE_TAB.hasListeners(tabId)) {
StartupEvents.MODIFY_CREATIVE_TAB.post(ScriptType.STARTUP, tabId, new CreativeTabKubeEvent(event.getTab(), event.hasPermissions(), new CreativeTabCallbackForge(event)));
}
}

@SubscribeEvent(priority = EventPriority.LOW)
public static void loadComplete(FMLLoadCompleteEvent event) {
event.enqueueWork(KubeJSModEventHandler::loadComplete0);
}

private static void loadComplete0() {
KubeJSPlugins.forEachPlugin(KubeJSPlugin::afterInit);
NeoForge.EVENT_BUS.post(new ScriptsLoadedEvent());
StartupEvents.POST_INIT.post(ScriptType.STARTUP, KubeStartupEvent.BASIC);
UtilsJS.postModificationEvents();

if (!ConsoleJS.STARTUP.errors.isEmpty()) {
var list = new ArrayList<String>();
list.add("Startup script errors:");

var lines = ConsoleJS.STARTUP.errors.toArray(ConsoleLine.EMPTY_ARRAY);

for (int i = 0; i < lines.length; i++) {
list.add((i + 1) + ") " + lines[i]);
}

KubeJS.LOGGER.error(String.join("\n", list));

ConsoleJS.STARTUP.flush(true);

if (FMLLoader.getDist() == Dist.DEDICATED_SERVER || !CommonProperties.get().startupErrorGUI) {
throw new RuntimeException("There were KubeJS startup script syntax errors! See logs/kubejs/startup.log for more info");
}
}

ConsoleJS.STARTUP.stopCapturingErrors();
ConsoleJS.CLIENT.stopCapturingErrors();

Util.nonCriticalIoPool().submit(() -> {
try {
var response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.connectTimeout(Duration.ofSeconds(5L))
.build()
.send(HttpRequest.newBuilder().uri(URI.create("https://v.kubejs.com/update-check?" + KubeJS.QUERY)).GET().build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() == 200) {
var body = response.body().trim();

if (!body.isEmpty()) {
ConsoleJS.STARTUP.info("Update available: " + body);
}
}
} catch (Exception ignored) {
}
});
}

/*
@SubscribeEvent(priority = EventPriority.HIGH)
public static void addPacksFirst(AddPackFindersEvent event) {
if (event.getPackType() == PackType.SERVER_DATA) {
// ServerScriptManager.addPacksFirst(event);
}
}
@SubscribeEvent(priority = EventPriority.LOW)
public static void addPacksLast(AddPackFindersEvent event) {
if (event.getPackType() == PackType.SERVER_DATA) {
// ServerScriptManager.addPacksLast(event);
}
}
*/
}
9 changes: 9 additions & 0 deletions src/main/java/dev/latvian/mods/kubejs/KubeJSPaths.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import net.neoforged.fml.loading.FMLPaths;
import org.apache.commons.lang3.mutable.MutableBoolean;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

Expand Down Expand Up @@ -58,4 +59,12 @@ static Path get(PackType type) {
static Path getLocalDevProperties() {
return CommonProperties.get().saveDevPropertiesInConfig ? CONFIG_DEV_PROPERTIES : LOCAL_DEV_PROPERTIES;
}

static Path verifyFilePath(Path path) throws IOException {
if (!path.normalize().toAbsolutePath().startsWith(GAMEDIR)) {
throw new IOException("You can't access files outside Minecraft directory!");
}

return path;
}
}
Loading

0 comments on commit 3f55a8b

Please sign in to comment.