Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ModularMCLib Utils

面向 Minecraft 26.1.2、NeoForge 26.1.2.126 与 Java 25 的通用工具库。模组标识为 `mmclutils`。
面向 Minecraft 1.21.1、NeoForge 21.1.265 与 Java 21 的通用工具库。模组标识为 `mmclutils`。

## 安装与构建

Expand Down
11 changes: 10 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ version = "${mod_version}" + (isSnapshot ? "-SNAPSHOT" : "")
boolean isCI = System.getenv("CI") != null

java {
toolchain.languageVersion = JavaLanguageVersion.of(25)
toolchain.languageVersion = JavaLanguageVersion.of(21)
}

kotlin {
jvmToolchain(21)
}

sourceSets {
Expand All @@ -32,6 +36,11 @@ sourceSets {
runtimeClasspath += main.output + main.runtimeClasspath
}

test {
compileClasspath += main.output + main.compileClasspath
runtimeClasspath += main.output + main.runtimeClasspath
}

extra {
compileClasspath += main.output
runtimeClasspath += main.output + main.runtimeClasspath
Expand Down
11 changes: 6 additions & 5 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
[versions]
minecraft = "26.1.2"
neoForge = "26.1.2.126"
lombok = "9.8.2"
minecraft = "1.21.1"
neoForge = "21.1.265"
lombok = "9.8.3"
loader = "4"
parchment = "2024.11.17" # https://parchmentmc.org/docs/getting-started
shadow = "9.6.1"
spotless = "8.11.0"
modDevGradle = "2.0.148"
kotlin = "2.4.21"
jetbrains-annotations = "26.1.0"
jspecify = "1.0.0"
fastutil = "8.5.18"
jspecify = "1.0.1"
fastutil = "8.5.12"
renderNurse = "0.0.26"
mixin = "0.8.7"

Expand Down
20 changes: 17 additions & 3 deletions gradle/scripts/moddevgradle.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
neoForge {
version = libs.versions.neoForge.get()

parchment {
minecraftVersion = libs.versions.minecraft.get()
mappingsVersion = libs.versions.parchment.get()
}

accessTransformers {
var file = project.file('src/main/resources/META-INF/accesstransformer.cfg')
from(file)
Expand All @@ -27,6 +32,13 @@ neoForge {
sourceSet(sourceSets.extra)
sourceSet(sourceSets.clientExtra)
}
"${mod_id}_test" {
sourceSet(sourceSets.main)
sourceSet(sourceSets.client)
sourceSet(sourceSets.extra)
sourceSet(sourceSets.clientExtra)
sourceSet(sourceSets.test)
}
}

runs {
Expand All @@ -48,18 +60,20 @@ neoForge {
programArguments.addAll('--nogui', '--world', 'world-extra')
}

// 让持续集成使用原版自带用例启动服务器、推进 Tick 并退出。
// 用启动用例确认服务端已加载模组并开始推进 Tick。
gameTestServer {
type = "gameTestServer"
sourceSet = sourceSets.extra
sourceSet = sourceSets.test
loadedMods = [mods["${mod_id}_test"]]
ideName = "Game Tests"

gameDirectory.set(file('run/gametest/server'))
programArguments.addAll('--tests', 'minecraft:always_pass')
systemProperty('neoforge.enabledGameTestNamespaces', 'minecraft')
}

// applies to all the run configs above
configureEach {
loadedMods.convention([mods[project.mod_id]])
systemProperty 'forge.logging.markers', 'REGISTRIES'
jvmArgument('-ea:com.modularmc.template...')
logLevel = org.slf4j.event.Level.INFO
Expand Down
4 changes: 2 additions & 2 deletions gradle/scripts/resources.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var generateModMetadata = tasks.register("generateModMetadata", ProcessResources
var replaceProperties = [
version : version_toml,
mod_id : mod_id,
minecraft_version : "[26.1,)",
minecraft_version : "[${libs.versions.minecraft.get()}]",
loader_version : libs.versions.loader.get(),
neo_version : neoVersion,
mod_license : mod_license,
Expand All @@ -50,4 +50,4 @@ var generateModMetadata = tasks.register("generateModMetadata", ProcessResources
into "build/generated/sources/modMetadata"
}
sourceSets.main.resources.srcDir generateModMetadata
neoForge.ideSyncTask generateModMetadata
neoForge.ideSyncTask generateModMetadata
12 changes: 6 additions & 6 deletions src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.modularmc.mmclutils.api.input.SyncedKeyMappings;
import com.modularmc.mmclutils.client.ModularMCLibUtilsClient;

import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModList;
Expand Down Expand Up @@ -46,8 +46,8 @@ public ModularMCLibUtils(IEventBus modBus) {
* @param path 标识路径
* @return 属于 {@link #MOD_ID} 的标识
*/
public static Identifier id(String path) {
return Identifier.fromNamespaceAndPath(MOD_ID, path);
public static ResourceLocation id(String path) {
return ResourceLocation.fromNamespaceAndPath(MOD_ID, path);
}

/** 返回当前专用服或本地集成服。服务器尚未启动或已停止时返回空值。 */
Expand All @@ -72,7 +72,7 @@ public static Path getGameDir() {

/** 判断当前运行是否为生产环境。 */
public static boolean isProd() {
return FMLEnvironment.isProduction();
return FMLLoader.isProduction();
}

/** 判断当前运行是否为开发环境。 */
Expand All @@ -93,12 +93,12 @@ public static boolean isDataGen() {
*/
public static boolean isModLoaded(String modId) {
ModList mods = ModList.get();
return mods == null ? FMLLoader.getCurrent().getLoadingModList().getModFileById(modId) != null : mods.isLoaded(modId);
return mods == null ? FMLLoader.getLoadingModList().getModFileById(modId) != null : mods.isLoaded(modId);
}

/** 判断物理运行端。集成服务器所在进程同样返回真。 */
public static boolean isClientSide() {
return FMLEnvironment.getDist().isClient();
return FMLEnvironment.dist.isClient();
}

/** 判断当前线程是否为物理客户端主线程。专用服务器上始终返回假。 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import com.modularmc.mmclutils.api.schedule.SerialTaskExecutor;
import com.modularmc.mmclutils.utils.FileUtils;

import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.dimension.DimensionType;
Expand Down Expand Up @@ -40,7 +40,7 @@
@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID)
public final class FastSavedData<T> {

private static final LevelStore<Map<Identifier, FastSavedData<?>>> DATA = LevelStore.create(HashMap::new, entries -> entries.values().forEach(value -> value.save(true)));
private static final LevelStore<Map<ResourceLocation, FastSavedData<?>>> DATA = LevelStore.create(HashMap::new, entries -> entries.values().forEach(value -> value.save(true)));
private static final Map<MinecraftServer, SerialTaskExecutor> EXECUTORS = new IdentityHashMap<>();

private final Type<T> type;
Expand Down Expand Up @@ -83,7 +83,8 @@ public static <T> FastSavedData<T> get(ServerLevel level, Type<T> type) throws I
}
Path worldRoot = level.getServer().getWorldPath(LevelResource.ROOT).toAbsolutePath().normalize();
Path directory = DimensionType.getStorageFolder(level.dimension(), worldRoot).resolve("data/mmclutils").normalize();
Path path = type.id().withSuffix(".bin").resolveAgainst(directory).normalize();
ResourceLocation file = type.id().withSuffix(".bin");
Path path = directory.resolve(file.getNamespace()).resolve(file.getPath()).normalize();
if (!path.startsWith(directory)) throw new IllegalArgumentException("存档路径超出维度数据目录:" + type.id());

boolean imported = false;
Expand Down Expand Up @@ -191,7 +192,7 @@ private static void checkOwner(ServerLevel level) {
* @param legacy 仅在新文件缺失时使用的旧格式入口,可以为空
* @param <T> 存档值的类型
*/
public record Type<T>(Identifier id, Supplier<T> factory, UnaryOperator<T> copyForWrite,
public record Type<T>(ResourceLocation id, Supplier<T> factory, UnaryOperator<T> copyForWrite,
FileUtils.Reader<T> reader, FileUtils.Writer<T> writer,
@Nullable LegacyFile<T> legacy) {

Expand All @@ -204,7 +205,7 @@ public record Type<T>(Identifier id, Supplier<T> factory, UnaryOperator<T> copyF
* @param reader 解码当前文件
* @param writer 在后台编码交付的数据
*/
public Type(Identifier id, Supplier<T> factory, UnaryOperator<T> copyForWrite,
public Type(ResourceLocation id, Supplier<T> factory, UnaryOperator<T> copyForWrite,
FileUtils.Reader<T> reader, FileUtils.Writer<T> writer) {
this(id, factory, copyForWrite, reader, writer, null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.IEventBus;
Expand All @@ -29,12 +29,12 @@
@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID)
public final class SyncedKeyMappings {

private static final ConcurrentHashMap<Identifier, Key> KEYS = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<ResourceLocation, Key> KEYS = new ConcurrentHashMap<>();

private SyncedKeyMappings() {}

/** 在模组初始化时于两端声明一次。标识应使用调用方的命名空间,重复声明会抛出异常。 */
public static Key define(Identifier id) {
public static Key define(ResourceLocation id) {
var key = new Key(id);
if (KEYS.putIfAbsent(id, key) != null) throw new IllegalArgumentException("同步按键已经声明 " + id);
return key;
Expand All @@ -51,7 +51,7 @@ private static void initPayload(RegisterPayloadHandlersEvent event) {
(payload, context) -> apply((ServerPlayer) context.player(), payload.changes));
}

private static void apply(ServerPlayer player, Object2BooleanMap<Identifier> changes) {
private static void apply(ServerPlayer player, Object2BooleanMap<ResourceLocation> changes) {
var accepted = new Object2BooleanLinkedOpenHashMap<Key>();
for (var change : changes.object2BooleanEntrySet()) {
Key key = KEYS.get(change.getKey());
Expand Down Expand Up @@ -98,17 +98,17 @@ private static void release(ServerPlayer player) {
/** 一个可被客户端绑定并由服务端读取的按键。状态和玩家监听仅在服务端线程访问。 */
public static final class Key {

private final Identifier id;
private final ResourceLocation id;
private final ReferenceOpenHashSet<ServerPlayer> pressed = new ReferenceOpenHashSet<>();
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
private final Reference2ObjectOpenHashMap<ServerPlayer, CopyOnWriteArrayList<Listener>> playerListeners = new Reference2ObjectOpenHashMap<>();

private Key(Identifier id) {
private Key(ResourceLocation id) {
this.id = id;
}

/** 返回两端共享的按键标识。 */
public Identifier id() {
public ResourceLocation id() {
return id;
}

Expand Down Expand Up @@ -171,7 +171,7 @@ public interface Listener {
* @param changes 已登记按键的标识及其按下状态
*/
@ApiStatus.Internal
public record ChangeSet(Object2BooleanMap<Identifier> changes) implements CustomPacketPayload {
public record ChangeSet(Object2BooleanMap<ResourceLocation> changes) implements CustomPacketPayload {

/** 单个载荷允许的最大变化条目数。 */
public static final int MAX_CHANGES = 64;
Expand All @@ -182,9 +182,9 @@ public record ChangeSet(Object2BooleanMap<Identifier> changes) implements Custom
private static ChangeSet read(FriendlyByteBuf buffer) {
int count = buffer.readVarInt();
if (count < 1 || count > MAX_CHANGES) throw new DecoderException("同步按键数量超出范围 " + count);
var changes = new Object2BooleanLinkedOpenHashMap<Identifier>(count);
var changes = new Object2BooleanLinkedOpenHashMap<ResourceLocation>(count);
for (int i = 0; i < count; i++) {
Identifier id = Identifier.STREAM_CODEC.decode(buffer);
ResourceLocation id = ResourceLocation.STREAM_CODEC.decode(buffer);
if (changes.containsKey(id)) throw new DecoderException("同步按键标识重复 " + id);
changes.put(id, buffer.readBoolean());
}
Expand All @@ -194,7 +194,7 @@ private static ChangeSet read(FriendlyByteBuf buffer) {
private static void write(FriendlyByteBuf buffer, ChangeSet state) {
buffer.writeVarInt(state.changes.size());
for (var change : state.changes.object2BooleanEntrySet()) {
Identifier.STREAM_CODEC.encode(buffer, change.getKey());
ResourceLocation.STREAM_CODEC.encode(buffer, change.getKey());
buffer.writeBoolean(change.getBooleanValue());
}
}
Expand Down
Loading
Loading