9
0
mirror of https://github.com/Xiao-MoMi/craft-engine.git synced 2025-12-19 15:09:15 +00:00

优化插件启动过程

This commit is contained in:
XiaoMoMi
2025-11-15 22:17:28 +08:00
parent a8eca7edc1
commit 13f1d96e34
14 changed files with 273 additions and 185 deletions

View File

@@ -2,11 +2,13 @@ package net.momirealms.craftengine.bukkit.compatibility;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.momirealms.craftengine.bukkit.block.BukkitBlockManager;
import net.momirealms.craftengine.bukkit.block.entity.renderer.element.BukkitBlockEntityElementConfigs;
import net.momirealms.craftengine.bukkit.compatibility.item.*;
import net.momirealms.craftengine.bukkit.compatibility.legacy.slimeworld.LegacySlimeFormatStorageAdaptor;
import net.momirealms.craftengine.bukkit.compatibility.leveler.*;
import net.momirealms.craftengine.bukkit.compatibility.model.bettermodel.BetterModelBlockEntityElementConfig;
import net.momirealms.craftengine.bukkit.compatibility.model.bettermodel.BetterModelModel;
import net.momirealms.craftengine.bukkit.compatibility.model.bettermodel.BetterModelUtils;
import net.momirealms.craftengine.bukkit.compatibility.model.modelengine.ModelEngineBlockEntityElementConfig;
import net.momirealms.craftengine.bukkit.compatibility.model.modelengine.ModelEngineModel;
import net.momirealms.craftengine.bukkit.compatibility.model.modelengine.ModelEngineUtils;
import net.momirealms.craftengine.bukkit.compatibility.mythicmobs.MythicItemDropListener;
@@ -68,16 +70,6 @@ public class BukkitCompatibilityManager implements CompatibilityManager {
@Override
public void onEnable() {
this.initSlimeWorldHook();
if (this.isPluginEnabled("PlaceholderAPI")) {
PlaceholderAPIUtils.registerExpansions(this.plugin);
this.hasPlaceholderAPI = true;
logHook("PlaceholderAPI");
}
if (this.isPluginEnabled("Skript")) {
SkriptHook.register();
logHook("Skript");
}
// WorldEdit
// FastAsyncWorldEdit
if (this.isPluginEnabled("FastAsyncWorldEdit")) {
@@ -91,16 +83,48 @@ public class BukkitCompatibilityManager implements CompatibilityManager {
this.initWorldEditHook();
logHook("WorldEdit");
}
if (this.hasPlugin("BetterModel")) {
BukkitBlockEntityElementConfigs.register(Key.of("craftengine:better_model"), new BetterModelBlockEntityElementConfig.Factory());
logHook("BetterModel");
}
if (this.hasPlugin("ModelEngine")) {
BukkitBlockEntityElementConfigs.register(Key.of("craftengine:model_engine"), new ModelEngineBlockEntityElementConfig.Factory());
logHook("ModelEngine");
}
if (this.hasPlugin("CustomNameplates")) {
registerTagResolverProvider(new CustomNameplateProviders.Background());
registerTagResolverProvider(new CustomNameplateProviders.Nameplate());
registerTagResolverProvider(new CustomNameplateProviders.Bubble());
logHook("CustomNameplates");
}
Key worldGuardRegion = Key.of("worldguard:region");
if (this.hasPlugin("WorldGuard")) {
EventConditions.register(worldGuardRegion, new WorldGuardRegionCondition.FactoryImpl<>());
LootConditions.register(worldGuardRegion, new WorldGuardRegionCondition.FactoryImpl<>());
logHook("WorldGuard");
} else {
EventConditions.register(worldGuardRegion, new AlwaysFalseCondition.FactoryImpl<>());
LootConditions.register(worldGuardRegion, new AlwaysFalseCondition.FactoryImpl<>());
}
}
@Override
public void onDelayedEnable() {
this.initSlimeWorldHook();
if (this.isPluginEnabled("PlaceholderAPI")) {
PlaceholderAPIUtils.registerExpansions(this.plugin);
this.hasPlaceholderAPI = true;
logHook("PlaceholderAPI");
}
this.initItemHooks();
if (this.isPluginEnabled("LuckPerms")) {
this.initLuckPermsHook();
logHook("LuckPerms");
}
if (this.isPluginEnabled("Skript")) {
SkriptHook.register();
logHook("Skript");
}
if (this.isPluginEnabled("AuraSkills")) {
this.registerLevelerProvider("AuraSkills", new AuraSkillsLevelerProvider());
logHook("AuraSkills");
@@ -133,33 +157,10 @@ public class BukkitCompatibilityManager implements CompatibilityManager {
new MythicItemDropListener(this.plugin);
logHook("MythicMobs");
}
Key worldGuardRegion = Key.of("worldguard:region");
if (this.isPluginEnabled("WorldGuard")) {
EventConditions.register(worldGuardRegion, new WorldGuardRegionCondition.FactoryImpl<>());
LootConditions.register(worldGuardRegion, new WorldGuardRegionCondition.FactoryImpl<>());
logHook("WorldGuard");
} else {
EventConditions.register(worldGuardRegion, new AlwaysFalseCondition.FactoryImpl<>());
LootConditions.register(worldGuardRegion, new AlwaysFalseCondition.FactoryImpl<>());
}
if (this.isPluginEnabled("BetterModel")) {
BetterModelUtils.registerConstantBlockEntityRender();
logHook("BetterModel");
}
if (this.isPluginEnabled("ModelEngine")) {
ModelEngineUtils.registerConstantBlockEntityRender();
logHook("ModelEngine");
}
if (this.isPluginEnabled("QuickShop-Hikari")) {
new QuickShopItemExpressionHandler(this.plugin).register();
logHook("QuickShop-Hikari");
}
if (this.isPluginEnabled("CustomNameplates")) {
registerTagResolverProvider(new CustomNameplateProviders.Background());
registerTagResolverProvider(new CustomNameplateProviders.Nameplate());
registerTagResolverProvider(new CustomNameplateProviders.Bubble());
logHook("CustomNameplates");
}
}
@Override

View File

@@ -2,11 +2,11 @@ package net.momirealms.craftengine.bukkit.compatibility.model.bettermodel;
import kr.toxicity.model.api.BetterModel;
import kr.toxicity.model.api.data.renderer.ModelRenderer;
import net.momirealms.craftengine.bukkit.block.entity.renderer.element.BukkitBlockEntityElementConfigs;
import net.momirealms.craftengine.core.util.Key;
import org.bukkit.entity.Entity;
public class BetterModelUtils {
public final class BetterModelUtils {
private BetterModelUtils() {}
public static void bindModel(Entity base, String id) {
ModelRenderer renderer = BetterModel.plugin().modelManager().model(id);
@@ -15,8 +15,4 @@ public class BetterModelUtils {
}
renderer.create(base);
}
public static void registerConstantBlockEntityRender() {
BukkitBlockEntityElementConfigs.register(Key.of("craftengine:better_model"), new BetterModelBlockEntityElementConfig.Factory());
}
}

View File

@@ -3,11 +3,11 @@ package net.momirealms.craftengine.bukkit.compatibility.model.modelengine;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.ModeledEntity;
import net.momirealms.craftengine.bukkit.block.entity.renderer.element.BukkitBlockEntityElementConfigs;
import net.momirealms.craftengine.core.util.Key;
import org.bukkit.entity.Entity;
public class ModelEngineUtils {
public final class ModelEngineUtils {
private ModelEngineUtils() {}
public static void bindModel(Entity base, String id) {
ModeledEntity modeledEntity = ModelEngineAPI.createModeledEntity(base);
@@ -26,8 +26,4 @@ public class ModelEngineUtils {
}
return entityId;
}
public static void registerConstantBlockEntityRender() {
BukkitBlockEntityElementConfigs.register(Key.of("craftengine:model_engine"), new ModelEngineBlockEntityElementConfig.Factory());
}
}

View File

@@ -44,14 +44,14 @@ tasks.withType<JavaCompile> {
}
bukkit {
load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.POSTWORLD
load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.STARTUP
main = "net.momirealms.craftengine.bukkit.plugin.BukkitCraftEnginePlugin"
version = rootProject.properties["project_version"] as String
name = "CraftEngine"
apiVersion = "1.20"
authors = listOf("XiaoMoMi")
contributors = listOf("https://github.com/Xiao-MoMi/craft-engine/graphs/contributors")
softDepend = listOf("PlaceholderAPI", "WorldEdit", "FastAsyncWorldEdit", "Skript")
softDepend = listOf("WorldEdit", "FastAsyncWorldEdit")
foliaSupported = true
}

View File

@@ -46,7 +46,7 @@ tasks.withType<JavaCompile> {
}
paper {
load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.POSTWORLD
load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.STARTUP
main = "net.momirealms.craftengine.bukkit.plugin.PaperCraftEnginePlugin"
bootstrapper = "net.momirealms.craftengine.bukkit.plugin.PaperCraftEngineBootstrap"
version = rootProject.properties["project_version"] as String
@@ -56,10 +56,7 @@ paper {
contributors = listOf("https://github.com/Xiao-MoMi/craft-engine/graphs/contributors")
foliaSupported = true
serverDependencies {
register("PlaceholderAPI") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
// WorldEdit
register("WorldEdit") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
@@ -69,10 +66,9 @@ paper {
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
joinClasspath = false
}
register("Skript") {
required = false
load = PaperPluginDescription.RelativeLoadOrder.BEFORE
}
register("PlaceholderAPI") { required = false }
register("Skript") { required = false }
register("LuckPerms") { required = false }
register("ViaVersion") { required = false }
register("QuickShop-Hikari") { required = false }

View File

@@ -75,7 +75,6 @@ public class BukkitFurniture implements Furniture {
this.hasExternalModel = false;
}
Quaternionf conjugated = QuaternionUtils.toQuaternionf(0, Math.toRadians(180 - this.location.getYaw()), 0).conjugate();
List<Object> packets = new ArrayList<>();
List<Object> minimizedPackets = new ArrayList<>();

View File

@@ -56,6 +56,7 @@ public class BukkitPackManager extends AbstractPackManager implements Listener {
public void onPlayerJoin(PlayerJoinEvent event) {
if (Config.sendPackOnJoin() && !VersionHelper.isOrAbove1_20_2()) {
Player player = BukkitAdaptors.adapt(event.getPlayer());
// 可能有假人
if (player == null) return;
this.sendResourcePack(player);
}

View File

@@ -35,8 +35,6 @@ import net.momirealms.craftengine.core.plugin.compatibility.CompatibilityManager
import net.momirealms.craftengine.core.plugin.config.Config;
import net.momirealms.craftengine.core.plugin.dependency.Dependencies;
import net.momirealms.craftengine.core.plugin.dependency.Dependency;
import net.momirealms.craftengine.core.plugin.gui.category.ItemBrowserManagerImpl;
import net.momirealms.craftengine.core.plugin.locale.TranslationManagerImpl;
import net.momirealms.craftengine.core.plugin.logger.JavaPluginLogger;
import net.momirealms.craftengine.core.plugin.logger.PluginLogger;
import net.momirealms.craftengine.core.plugin.scheduler.SchedulerAdapter;
@@ -56,7 +54,6 @@ import org.jspecify.annotations.Nullable;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
@@ -104,17 +101,13 @@ public class BukkitCraftEngine extends CraftEngine {
this.javaPlugin = javaPlugin;
}
protected void setUpConfigAndLocale() {
this.config = new Config(this);
this.config.updateConfigCache();
// 先读取语言后,再重载语言文件系统
this.config.loadForcedLocale();
this.translationManager = new TranslationManagerImpl(this);
this.translationManager.reload();
// 最后才加载完整的config配置
this.config.loadFullSettings();
@Override
public void setUpConfigAndLocale() {
super.setUpConfigAndLocale();
super.packManager = new BukkitPackManager(this);
}
// 这个方法应该尽早被执行最好是boostrap阶段
public void injectRegistries() {
if (super.blockManager != null) return;
try {
@@ -143,9 +136,11 @@ public class BukkitCraftEngine extends CraftEngine {
@Override
public void onPluginLoad() {
// 普通bukkit插件会到这里才注册自定义方块
if (super.blockManager == null) {
this.injectRegistries();
}
// 注入一些新的类型,但是并不需要太早
try {
WorldStorageInjector.init();
} catch (Exception e) {
@@ -161,12 +156,44 @@ public class BukkitCraftEngine extends CraftEngine {
} catch (Exception e) {
throw new InjectionException("Error initializing ProtectedFieldVisitor", e);
}
// 初始化一些注册表
super.onPluginLoad();
super.networkManager = new BukkitNetworkManager(this);
super.blockManager.init();
super.itemManager = new BukkitItemManager(this);
this.successfullyLoaded = true;
BukkitBlockBehaviors.init();
BukkitItemBehaviors.init();
BukkitHitBoxTypes.init();
BukkitBlockEntityElementConfigs.init();
// 初始化 onload 阶段的兼容性
super.compatibilityManager().onLoad();
// 创建网络管理器
super.networkManager = new BukkitNetworkManager(this);
// 初始化方块管理器,获取镜像注册表,初始化网络映射
super.blockManager.init();
// 初始化物品管理器
super.itemManager = new BukkitItemManager(this);
// 初始化配方管理器
super.recipeManager = new BukkitRecipeManager(this);
// 初始化GUI管理器
super.guiManager = new BukkitGuiManager(this);
// 初始化世界管理器
super.worldManager = new BukkitWorldManager(this);
// 初始化声音管理器
super.soundManager = new BukkitSoundManager(this);
// 初始化战利品管理器
super.vanillaLootManager = new BukkitVanillaLootManager(this);
// 初始化字体管理器
super.fontManager = new BukkitFontManager(this);
// 初始化进度管理器
super.advancementManager = new BukkitAdvancementManager(this);
// 初始化弹射物管理器
super.projectileManager = new BukkitProjectileManager(this);
// 初始化座椅管理器
super.seatManager = new BukkitSeatManager(this);
// 初始化家具管理器
super.furnitureManager = new BukkitFurnitureManager(this);
// 注册默认的parser
this.registerDefaultParsers();
// 完成加载
this.successfullyLoaded = true;
}
@Override
@@ -203,24 +230,10 @@ public class BukkitCraftEngine extends CraftEngine {
Bukkit.getServer().shutdown();
return;
}
BukkitBlockBehaviors.init();
BukkitItemBehaviors.init();
BukkitHitBoxTypes.init();
BukkitBlockEntityElementConfigs.init();
super.packManager = new BukkitPackManager(this);
// 初始化指令发送者工厂
super.senderFactory = new BukkitSenderFactory(this);
super.recipeManager = new BukkitRecipeManager(this);
// 初始化指令管理器
super.commandManager = new BukkitCommandManager(this);
super.itemBrowserManager = new ItemBrowserManagerImpl(this);
super.guiManager = new BukkitGuiManager(this);
super.worldManager = new BukkitWorldManager(this);
super.soundManager = new BukkitSoundManager(this);
super.vanillaLootManager = new BukkitVanillaLootManager(this);
super.fontManager = new BukkitFontManager(this);
super.advancementManager = new BukkitAdvancementManager(this);
super.projectileManager = new BukkitProjectileManager(this);
super.furnitureManager = new BukkitFurnitureManager(this);
super.seatManager = new BukkitSeatManager(this);
super.onPluginEnable();
super.compatibilityManager().onEnable();
}

View File

@@ -49,6 +49,7 @@ public class BukkitWorldManager implements WorldManager, Listener {
this.plugin = plugin;
this.worlds = ConcurrentUUID2ReferenceChainedHashTable.createWithCapacity(10, 0.5f);
this.storageAdaptor = new DefaultStorageAdaptor();
// fixme 初始化
for (World world : Bukkit.getWorlds()) {
this.worlds.put(world.getUID(), new BukkitCEWorld(new BukkitWorld(world), this.storageAdaptor));
}

View File

@@ -8,6 +8,4 @@ public abstract class AbstractAdvancementManager implements AdvancementManager {
public AbstractAdvancementManager(CraftEngine plugin) {
this.plugin = plugin;
}
}

View File

@@ -301,9 +301,8 @@ public abstract class AbstractPackManager implements PackManager {
}
@Override
public void loadResources(boolean recipe) {
this.loadPacks();
this.loadResourceConfigs(recipe ? (p) -> true : (p) -> p.loadingSequence() != LoadingSequence.RECIPE);
public void loadResources(Predicate<ConfigParser> predicate) {
this.loadResourceConfigs(predicate);
}
@Override
@@ -362,7 +361,8 @@ public abstract class AbstractPackManager implements PackManager {
return true;
}
private void loadPacks() {
@Override
public void loadPacks() {
Path resourcesFolder = this.plugin.dataFolderPath().resolve("resources");
try {
if (Files.notExists(resourcesFolder)) {
@@ -621,7 +621,8 @@ public abstract class AbstractPackManager implements PackManager {
plugin.saveResource("resources/default/resourcepack/assets/minecraft/models/block/custom/magma_plant_stage_3.json");
}
private void updateCachedConfigFiles() {
@Override
public void updateCachedConfigFiles() {
Map<Path, CachedConfigFile> previousFiles = this.cachedConfigFiles;
this.cachedConfigFiles = new HashMap<>(64, 0.5f);
for (Pack pack : loadedPacks()) {
@@ -684,25 +685,26 @@ public abstract class AbstractPackManager implements PackManager {
}
private void loadResourceConfigs(Predicate<ConfigParser> predicate) {
long o1 = System.nanoTime();
this.updateCachedConfigFiles();
long o2 = System.nanoTime();
this.plugin.logger().info("Loaded packs. Took " + String.format("%.2f", ((o2 - o1) / 1_000_000.0)) + " ms");
for (ConfigParser parser : this.sortedParsers) {
if (!predicate.test(parser)) {
parser.clear();
continue;
}
long t1 = System.nanoTime();
parser.preProcess();
parser.loadAll();
parser.postProcess();
parser.clear();
long t2 = System.nanoTime();
this.plugin.logger().info("Loaded " + parser.sectionId()[0] + " in " + String.format("%.2f", ((t2 - t1) / 1_000_000.0)) + " ms");
}
}
@Override
public void clearResourceConfigs() {
for (ConfigParser parser : this.sortedParsers) {
parser.clear();
}
}
private void processConfigEntry(Map.Entry<String, Object> entry, Path path, Pack pack, BiConsumer<ConfigParser, CachedConfigSection> callback) {
if (entry.getValue() instanceof Map<?,?> typeSections0) {
String key = entry.getKey();

View File

@@ -9,12 +9,13 @@ import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.function.Predicate;
public interface PackManager extends Manageable {
ConfigParser parser();
void loadResources(boolean recipe);
void loadResources(Predicate<ConfigParser> predicate);
void initCachedAssets();
@@ -37,6 +38,12 @@ public interface PackManager extends Manageable {
}
}
void loadPacks();
void updateCachedConfigFiles();
void clearResourceConfigs();
void generateResourcePack() throws IOException;
Path resourcePackPath();

View File

@@ -12,6 +12,7 @@ import net.momirealms.craftengine.core.item.recipe.network.legacy.LegacyRecipeTy
import net.momirealms.craftengine.core.item.recipe.network.modern.display.RecipeDisplayTypes;
import net.momirealms.craftengine.core.item.recipe.network.modern.display.slot.SlotDisplayTypes;
import net.momirealms.craftengine.core.loot.VanillaLootManager;
import net.momirealms.craftengine.core.pack.LoadingSequence;
import net.momirealms.craftengine.core.pack.PackManager;
import net.momirealms.craftengine.core.plugin.classpath.ClassPathAppender;
import net.momirealms.craftengine.core.plugin.command.CraftEngineCommandManager;
@@ -30,6 +31,7 @@ import net.momirealms.craftengine.core.plugin.gui.GuiManager;
import net.momirealms.craftengine.core.plugin.gui.category.ItemBrowserManager;
import net.momirealms.craftengine.core.plugin.gui.category.ItemBrowserManagerImpl;
import net.momirealms.craftengine.core.plugin.locale.TranslationManager;
import net.momirealms.craftengine.core.plugin.locale.TranslationManagerImpl;
import net.momirealms.craftengine.core.plugin.logger.PluginLogger;
import net.momirealms.craftengine.core.plugin.logger.filter.DisconnectLogFilter;
import net.momirealms.craftengine.core.plugin.logger.filter.LogFilter;
@@ -79,8 +81,8 @@ public abstract class CraftEngine implements Plugin {
protected ProjectileManager projectileManager;
protected SeatManager seatManager;
private final PluginTaskRegistry preLoadTaskRegistry = new PluginTaskRegistry();
private final PluginTaskRegistry postLoadTaskRegistry = new PluginTaskRegistry();
private final PluginTaskRegistry beforeEnableTaskRegistry = new PluginTaskRegistry();
private final PluginTaskRegistry afterEnableTaskRegistry = new PluginTaskRegistry();
private final Consumer<CraftEngine> reloadEventDispatcher;
private boolean isReloading;
@@ -110,6 +112,24 @@ public abstract class CraftEngine implements Plugin {
RecipeDisplayTypes.init();
SlotDisplayTypes.init();
LegacyRecipeTypes.init();
// 初始化模板管理器
this.templateManager = new TemplateManagerImpl();
// 初始化全局变量管理器
this.globalVariableManager = new GlobalVariableManager();
// 初始化物品浏览器
this.itemBrowserManager = new ItemBrowserManagerImpl(this);
}
public void setUpConfigAndLocale() {
this.config = new Config(this);
this.config.updateConfigCache();
// 先读取语言后,再重载语言文件系统
this.config.loadForcedLocale();
this.translationManager = new TranslationManagerImpl(this);
this.translationManager.reload();
// 最后才加载完整的config配置
this.config.loadFullSettings();
}
public record ReloadResult(boolean success, long asyncTime, long syncTime) {
@@ -123,6 +143,48 @@ public abstract class CraftEngine implements Plugin {
}
}
private void reloadManagers() {
this.templateManager.reload();
this.globalVariableManager.reload();
this.furnitureManager.reload();
this.fontManager.reload();
this.itemManager.reload();
this.soundManager.reload();
this.itemBrowserManager.reload();
this.blockManager.reload();
this.worldManager.reload();
this.vanillaLootManager.reload();
this.guiManager.reload();
this.packManager.reload();
this.advancementManager.reload();
this.projectileManager.reload();
this.seatManager.reload();
}
private void runDelayTasks(boolean reloadRecipe) {
List<CompletableFuture<Void>> delayedLoadTasks = new ArrayList<>();
// 指令补全,重置外部配方原料
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.itemManager.delayedLoad(), this.scheduler.async()));
// 重置映射表指令补全发送tags收集声音
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.blockManager.delayedLoad(), this.scheduler.async()));
// 处理block_name特殊语言键
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.translationManager.delayedLoad(), this.scheduler.async()));
// 指令补全
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.furnitureManager.delayedLoad(), this.scheduler.async()));
// 处理外部category加载ui常量
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.itemBrowserManager.delayedLoad(), this.scheduler.async()));
// 收集非法字符,构造前缀树,指令补全
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.fontManager.delayedLoad(), this.scheduler.async()));
// 指令补全
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.soundManager.delayedLoad(), this.scheduler.async()));
// 如果重载配方
if (reloadRecipe) {
// 转换数据包配方
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.recipeManager.delayedLoad(), this.scheduler.async()));
}
CompletableFutures.allOf(delayedLoadTasks).join();
}
public CompletableFuture<ReloadResult> reloadPlugin(Executor asyncExecutor, Executor syncExecutor, boolean reloadRecipe) {
CompletableFuture<ReloadResult> future = new CompletableFuture<>();
asyncExecutor.execute(() -> {
@@ -134,56 +196,26 @@ public abstract class CraftEngine implements Plugin {
}
this.isReloading = true;
long time1 = System.currentTimeMillis();
// firstly reload main config
// 重载config
this.config.load();
// now we reload the translations
// 重载翻译
this.translationManager.reload();
// clear the outdated cache by reloading the managers
this.templateManager.reload();
this.globalVariableManager.reload();
this.furnitureManager.reload();
this.fontManager.reload();
this.itemManager.reload();
this.soundManager.reload();
this.itemBrowserManager.reload();
this.blockManager.reload();
this.worldManager.reload();
this.vanillaLootManager.reload();
this.guiManager.reload();
this.packManager.reload();
this.advancementManager.reload();
this.projectileManager.reload();
this.seatManager.reload();
// 重载其他管理器
this.reloadManagers();
if (reloadRecipe) {
this.recipeManager.reload();
}
try {
// now we load resources
this.packManager.loadResources(reloadRecipe);
// 加载全部配置资源
this.packManager.loadPacks();
this.packManager.updateCachedConfigFiles();
this.packManager.loadResources(reloadRecipe ? (p) -> true : (p) -> p.loadingSequence() != LoadingSequence.RECIPE);
this.packManager.clearResourceConfigs();
} catch (Exception e) {
this.logger().warn("Failed to load resources folder", e);
}
List<CompletableFuture<Void>> delayedLoadTasks = new ArrayList<>();
// 指令补全,重置外部配方原料
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.itemManager.delayedLoad(), this.scheduler.async()));
// 重置映射表指令补全发送tags收集声音
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.blockManager.delayedLoad(), this.scheduler.async()));
// 处理block_name特殊语言键
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.translationManager.delayedLoad(), this.scheduler.async()));
// 指令补全
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.furnitureManager.delayedLoad(), this.scheduler.async()));
// 处理外部category加载ui常量
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.itemBrowserManager.delayedLoad(), this.scheduler.async()));
// 收集非法字符,构造前缀树,指令补全
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.fontManager.delayedLoad(), this.scheduler.async()));
// 指令补全
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.soundManager.delayedLoad(), this.scheduler.async()));
// 如果重载配方
if (reloadRecipe) {
// 转换数据包配方
delayedLoadTasks.add(CompletableFuture.runAsync(() -> this.recipeManager.delayedLoad(), this.scheduler.async()));
}
CompletableFutures.allOf(delayedLoadTasks).join();
// 执行延迟任务
this.runDelayTasks(reloadRecipe);
// 重新发送tags需要等待tags更新完成
this.networkManager.delayedLoad();
long time2 = System.currentTimeMillis();
@@ -193,9 +225,9 @@ public abstract class CraftEngine implements Plugin {
syncExecutor.execute(() -> {
try {
long time3 = System.currentTimeMillis();
// register songs
// 注册唱片机音乐
this.soundManager.runDelayedSyncTasks();
// register recipes
// 重载配方
if (reloadRecipe) {
this.recipeManager.runDelayedSyncTasks();
}
@@ -214,43 +246,76 @@ public abstract class CraftEngine implements Plugin {
protected void onPluginEnable() {
this.isInitializing = true;
// 注册网络相关的bukkit事件监听器
this.networkManager.init();
this.templateManager = new TemplateManagerImpl();
this.globalVariableManager = new GlobalVariableManager();
this.itemBrowserManager = new ItemBrowserManagerImpl(this);
// 注册指令
this.commandManager.registerDefaultFeatures();
// delay the reload so other plugins can register some custom parsers
// 注册物品相关的事件监听器
this.itemManager.delayedInit();
// 注册方块相关的事件监听器
this.blockManager.delayedInit();
// 注册容器相关的监听器
this.guiManager.delayedInit();
// 注册配方相关的监听器
this.recipeManager.delayedInit();
// 注册数据包状态的监听器
this.packManager.delayedInit();
// 注册聊天监听器
this.fontManager.delayedInit();
// 注册实体死亡监听器
this.vanillaLootManager.delayedInit();
// 注册脱离坐骑监听器
this.seatManager.delayedInit();
// 延迟任务
this.beforeEnableTaskRegistry.executeTasks();
// 清理缓存初始化一些东西不需要读config和translation因为boostrap阶段已经读取过了
this.reloadManagers();
// 加载packs
this.packManager.loadPacks();
this.packManager.updateCachedConfigFiles();
// 不要加载配方
this.packManager.loadResources((p) -> p.loadingSequence() != LoadingSequence.RECIPE);
this.runDelayTasks(false);
// 延迟任务
this.afterEnableTaskRegistry.executeTasks();
// 延迟重载以便其他依赖CraftEngine的插件能注册parser
this.scheduler.sync().runDelayed(() -> {
this.preLoadTaskRegistry.executeTasks();
this.registerDefaultParsers();
// hook external item plugins
this.itemManager.delayedInit();
// hook worldedit
this.blockManager.delayedInit();
// register listeners and tasks
this.guiManager.delayedInit();
this.recipeManager.delayedInit();
this.packManager.delayedInit();
this.fontManager.delayedInit();
this.vanillaLootManager.delayedInit();
this.advancementManager.delayedInit();
this.seatManager.delayedInit();
// 初始化一些平台的任务
this.platformDelayedEnable();
// 延迟兼容性任务,比如物品库的支持。保证后续配方正确加载
this.compatibilityManager.onDelayedEnable();
// reload the plugin
try {
this.reloadPlugin(Runnable::run, Runnable::run, true);
} catch (Exception e) {
this.logger.warn("Failed to reload plugin on enable stage", e);
}
// must be after reloading because this process loads furniture
// 单独加载配方
this.recipeManager.reload();
this.packManager.loadResources((p) -> p.loadingSequence() == LoadingSequence.RECIPE);
this.recipeManager.delayedLoad();
this.packManager.clearResourceConfigs();
// 重新发送tags需要等待tags更新完成
this.networkManager.delayedLoad();
// 注册唱片机音乐
this.soundManager.runDelayedSyncTasks();
this.recipeManager.runDelayedSyncTasks();
// 必须要在完整重载后再初始化,否则会因为配置不存在,导致家具、弹射物等无法正确被加载
this.projectileManager.delayedInit();
this.worldManager.delayedInit();
this.furnitureManager.delayedInit();
// set up some platform extra tasks
this.platformDelayedEnable();
// 完成初始化
this.isInitializing = false;
this.postLoadTaskRegistry.executeTasks();
// 异步去缓存资源包相关文件
this.scheduler.executeAsync(() -> this.packManager.initCachedAssets());
// 正式完成重载
this.reloadEventDispatcher.accept(this);
});
}
@@ -490,13 +555,27 @@ public abstract class CraftEngine implements Plugin {
return platform;
}
/**
*
* This task registry allows you to schedule tasks to run before CraftEngine enable, without dealing with plugin dependencies.
* You must register these tasks during the onLoad phase; otherwise, they will not be executed.
*
* @return PluginTaskRegistry
*/
@ApiStatus.Experimental
public PluginTaskRegistry preLoadTaskRegistry() {
return preLoadTaskRegistry;
public PluginTaskRegistry beforeEnableTaskRegistry() {
return beforeEnableTaskRegistry;
}
/**
*
* This task registry allows you to schedule tasks to run after CraftEngine enable, without dealing with plugin dependencies.
* You must register these tasks during the onLoad phase; otherwise, they will not be executed.
*
* @return PluginTaskRegistry
*/
@ApiStatus.Experimental
public PluginTaskRegistry postLoadTaskRegistry() {
return postLoadTaskRegistry;
public PluginTaskRegistry afterEnableTaskRegistry() {
return afterEnableTaskRegistry;
}
}

View File

@@ -2,7 +2,6 @@ package net.momirealms.craftengine.core.plugin;
public interface Manageable {
// on plugin enable
default void init() {
}