diff --git a/dependencies.gradle b/dependencies.gradle index fb5d39c..c742ee3 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -5,6 +5,8 @@ dependencies { jarJar(api(libs.kotlin.stdlib.get())) { exclude group: 'org.jetbrains', module: 'annotations' } + jarJar(implementation(forge.mmclutils.get())) + renderNurseCfg(libs.renderNurse) ////////////////////////////////////////////////////// diff --git a/gradle/forge.versions.toml b/gradle/forge.versions.toml index eb179be..c603044 100644 --- a/gradle/forge.versions.toml +++ b/gradle/forge.versions.toml @@ -1,4 +1,5 @@ [versions] +mmclutils = "0.1.0-SNAPSHOT" ## modrinth maven ## @@ -9,5 +10,6 @@ [libraries] +mmclutils = { module = "com.modularmc.mmclutils:mmclutils-26.1.2", version.ref = "mmclutils" } [bundles] \ No newline at end of file diff --git a/gradle/scripts/repositories.gradle b/gradle/scripts/repositories.gradle index 4fec516..5784bce 100644 --- a/gradle/scripts/repositories.gradle +++ b/gradle/scripts/repositories.gradle @@ -25,6 +25,10 @@ repositories { name = "ModMaven" url = "https://modmaven.dev" } + maven { + name = "fury" + url = uri("https://maven.fury.io/modularmclib/") + } exclusiveContent { // terraformers - EMI forRepository { maven { url = "https://maven.terraformersmc.com/releases/" } } filter { includeGroup("dev.emi") } diff --git a/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt index 76071e3..265b88c 100644 --- a/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt +++ b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt @@ -1,4 +1,4 @@ -// KtLint folds forwarding overloads across the configured line limit during formatting. +// 格式化时,KtLint 会根据行宽限制折叠转发用的重载。 @file:Suppress("ktlint:standard:max-line-length") package com.modularmc.registrate @@ -108,30 +108,25 @@ import java.util.function.Function import java.util.function.Supplier /** - * Manages all registrations and data generators for a mod. + * 统一管理一个模组的条目注册和数据生成回调。 * - * Generally *not* thread-safe, as it holds the current name of the object being built statefully, and uses - * non-concurrent collections. - * - * Begin a new object via [object]. This name will be used for all future entries until the next - * invocation of [object]. Alternatively, the methods that accept a name - * parameter (such as [block]) can be used. These do not affect the current name state. - * - * A simple use may look like: + * 通过 [object] 设置当前条目名称。后续省略名称的构建入口会沿用它,直到再次调用 [object]。 + * 也可用 [block] 等带名称的重载直接指定条目名称,当前名称保持原值。 + * 构建过程持有可变状态,由模组初始化线程负责。 * * ```java * public static final Registrate REGISTRATE = Registrate.create("mymod"); - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final BlockEntry MY_BLOCK = REGISTRATE.object("my_block") * .block(MyBlock::new) - * .defaultItem() + * .simpleItem() * .register(); * ``` * - * For specifics as to building different registry entries, read the documentation on their respective builders. + * 各类条目的默认值及数据生成入口见对应构建器。 */ abstract class AbstractRegistrate> protected constructor( /** - * The mod ID that this [AbstractRegistrate] is creating objects for + * 本实例管理的模组标识。创建注册条目时使用它作为命名空间。 */ val modid: String, ) { @@ -181,11 +176,11 @@ abstract class AbstractRegistrate> protected construct private val dataGeneration = NonNullSupplier.lazy(DatagenModLoader::isRunningDataGen) + /** 返回延迟读取本次启动是否启用数据生成的取值器。首次查询后复用该结果。 */ open fun doDatagen(): NonNullSupplier = dataGeneration /** - * Get the mod event bus that event listeners will be registered to. Useful when Registrate is used in mods that use - * alternative language loaders, such as forgelin. + * 模组的事件总线,用于绑定注册及数据生成监听器。绑定前为空,扩展构建器可在绑定后用它登记监听器。 */ var modEventBus: IEventBus? = null @@ -194,22 +189,18 @@ abstract class AbstractRegistrate> protected construct private var skipErrors = false /** - * Use this in custom implementations to hide unsafe casts to [S] when returning self. + * 把当前实例转换为子类声明的 [S],便于扩展方法返回自身并继续链式调用。 * - * @return This [AbstractRegistrate] object, cast to [S] + * @return 当前实例,类型为 [S] */ @Suppress("UNCHECKED_CAST") protected fun self(): S = this as S /** - * Called during [creation][Registrate.create] to initialize event listeners. Custom implementations - * may add their own event listeners by overriding this. - * - * *Always* call `super` in your override unless you know what you are doing! + * 在 [Registrate.create] 绑定模组事件总线时初始化监听器。子类可以重写此方法添加监听器,需调用父类实现完成基础绑定。 * - * @param bus - * The event bus - * @return This [AbstractRegistrate] object + * @param bus 要绑定的模组事件总线 + * @return 当前实例 */ open fun registerEventListeners(bus: IEventBus): S { lifecycle.register(bus) @@ -217,38 +208,28 @@ abstract class AbstractRegistrate> protected construct } /** - * Called once per registry to gather collected registrations and add entries to the registry. May be overriden in - * custom implementations to perform additional actions upon entry registration, but - * *must* call `super`. + * 每个注册表触发一次,将此前收集的条目提交到对应注册表。重写时须调用父类实现。 * - * @param event - * The [RegisterEvent] being fired, use [RegisterEvent.getRegistryKey] to query the - * registry type + * @param event 当前注册事件,通过 [RegisterEvent.getRegistryKey] 取得注册表键 */ protected open fun onRegister(event: RegisterEvent) { registrationTracker.onRegister(event, skipErrors, isDevEnvironment) } /** - * Called once per registry at the [lowest priority][net.neoforged.bus.api.EventPriority.LOWEST] to perform any actions that must - * happen after all other entries have been registered, including from other mods. May - * be overriden in custom implementations to perform additional actions upon entry registration, but *must* - * call `super`. + * 以[最低优先级][net.neoforged.bus.api.EventPriority.LOWEST] 处理每个注册表的注册事件。 + * 用于执行依赖当前注册表已完成注册的操作,包括依赖其他模组条目的操作。重写时须调用父类实现。 * - * @param event - * The [RegisterEvent] being fired, use [RegisterEvent.getRegistryKey] to query the - * registry type + * @param event 当前注册事件,通过 [RegisterEvent.getRegistryKey] 取得注册表键 */ protected open fun onRegisterLate(event: RegisterEvent) { registrationTracker.onRegisterLate(event) } /** - * Called when a [CreativeModeTab] is being populated to fill in any entries that belong there. Can be - * overriden in custom implementations. + * 填充创造模式物品栏时触发,执行针对当前标签页的修改回调。 * - * @param event - * The event + * @param event 当前标签页的填充事件 */ protected open fun onBuildCreativeModeTabContents(event: BuildCreativeModeTabContentsEvent) { val modifier = CreativeModeTabModifier( @@ -266,10 +247,9 @@ abstract class AbstractRegistrate> protected construct private var provider: RegistrateDataProvider? = null /** - * Called when datagen begins to add our provider to the generator. Can be overriden in custom implementations. + * 数据生成开始时绑定本实例的生成器。扩展实现可重写此方法,为同一轮生成追加数据。 * - * @param event - * The event + * @param event 本轮数据生成事件 */ protected open fun onData(event: GatherDataEvent) { val dataProvider = RegistrateDataProvider(this, modid, event) @@ -278,114 +258,83 @@ abstract class AbstractRegistrate> protected construct } /** - * Get the current name (from the last call to [object]), throwing an exception if it is not set. + * 读取最近一次由 [object] 设置的条目名称。 * - * @return The current entry name - + * @return 当前条目名称 + * @throws UninitializedPropertyAccessException 尚未设置当前名称 */ protected open fun currentName(): String = currentName /** - * Allows retrieval of a previously created entry, of the current name (from the last invocation of - * [object]). Useful to retrieve a different entry than the final state of your - * chain may produce, e.g. + * 在指定注册表中查找当前名称对应的条目。可用于取得构建链一并创建的同名条目,例如方块的物品。 * * ```java - * public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.object("my_block") + * public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.object("my_block") * .block(MyBlock::new) - * .defaultItem() + * .simpleItem() * .lang("My Special Block") * .build() - * .get(Item.class); + * .get(Registries.ITEM); * ``` * - * @param R - * The type of the registry for which to retrieve the entry - * @param T - * The type of the entry to return - * @param type - * A [ResourceKey] for the registry - * @return A [RegistryEntry] which will supply the requested entry, if it exists - * @throws IllegalArgumentException - * if no such registration has been done - * @throws NullPointerException - * if current name has not been set via [object] + * @param R 注册表中的基础类型 + * @param T 所需条目的具体类型 + * @param type 注册表键 + * @return 指定注册表中的 [RegistryEntry],对象在注册绑定后可读 + * @throws IllegalArgumentException 尚未提交对应条目 + * @throws UninitializedPropertyAccessException 尚未通过 [object] 设置当前名称 */ open fun get(type: ResourceKey>) = this.get(currentName(), type) /** - * Allows retrieval of a previously created entry. Useful to retrieve arbitrary entries that may have been created - * as side-effects of earlier registrations. + * 按名称和注册表查找已提交的条目,也可取得构建器一并创建的附属条目。 * * ```java - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final BlockEntry MY_BLOCK = REGISTRATE.object("my_block") * .block(MyBlock::new) - * .defaultItem() + * .simpleItem() * .register(); - * ... public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.get("my_block", Registries.ITEM); + * public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.get("my_block", Registries.ITEM); * ``` * - * @param R - * The type of the registry for which to retrieve the entry - * @param T - * The type of the entry to return - * @param name - * The name of the registry entry to request - * @param type - * A [ResourceKey] for the registry - * @return A [RegistryEntry] which will supply the requested entry, if it exists - * @throws IllegalArgumentException - * if no such registration has been done + * @param R 注册表中的基础类型 + * @param T 所需条目的具体类型 + * @param name 本模组命名空间内的条目名称 + * @param type 注册表键 + * @return 指定的 [RegistryEntry],对象在注册绑定后可读 + * @throws IllegalArgumentException 尚未提交对应条目 */ open fun get(name: String, type: ResourceKey>) = registrationTracker.get(name, type) /** - * Allows retrieval of a previously created entry that may or may not exist. Possibly useful in some very specific - * scenarios, internally used during fluid registration. + * 按名称和注册表查找可选条目。流体注册会用此入口查询可能缺省的附属条目。 * - * @param R - * The type of the registry for which to retrieve the entry - * @param T - * The type of the entry to return - * @param name - * The name of the registry entry to request - * @param type - * A class representing the registry type - * @return A [RegistryEntry] which will supply the requested entry, if it exists + * @param R 注册表中的基础类型 + * @param T 所需条目的具体类型 + * @param name 本模组命名空间内的条目名称 + * @param type 注册表键 + * @return 找到时返回包含 [RegistryEntry] 的 [Optional],查不到时返回空值 */ open fun getOptional(name: String, type: ResourceKey>) = registrationTracker.getOptional(name, type) /** - * Gather a collection of all entries registered for a certain registry - * - * Note that this can be called before registration is complete, but the [entries][RegistryEntry] will be empty - * at that time. + * 收集本实例已提交给指定注册表的条目。注册完成前也可查询,条目引用要等各自绑定后才能取得对象。 * - * @param R - * Registry type - * @param type - * A [ResourceKey] for the registry in question - * @return A collection of [RegistryEntry] objects representing all entries in the given registry which are - * known to this [AbstractRegistrate] object. + * @param R 注册表中的基础类型 + * @param type 注册表键 + * @return 该注册表中由本实例提交的 [RegistryEntry] 集合 */ open fun getAll(type: ResourceKey>) = registrationTracker.getAll(type) /** - * Add a callback to be invoked when a certain entry has been registered. This will be invoked *immediately* - * following registration, before further entries are registered. + * 为指定条目添加注册回调。条目写入注册表后立即执行,再继续注册后续条目。 * - * @param R - * Registry type - * @param T - * Entry type - * @param name - * The name of the entry to watch (implicitly within the [modid][modid] of this - * instance - * @param registryType - * A [ResourceKey] for the registry in question - * @param callback - * The callback to invoke, which will be passed the created entry object - * @return This [AbstractRegistrate] instance + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param name 本实例的 [modid] 命名空间内要监听的条目名称 + * @param registryType 注册表键 + * @param callback 接收已注册对象的回调 + * @return 当前实例 */ open fun addRegisterCallback(name: String, registryType: ResourceKey>, callback: NonNullConsumer): S { registrationTracker.addRegisterCallback(name, registryType, callback) @@ -393,16 +342,12 @@ abstract class AbstractRegistrate> protected construct } /** - * Add a callback to be invoked when a certain registry has fully completed registration, i.e. all objects of that - * type have been registered. + * 在指定注册表完成所有条目的注册后执行回调。 * - * @param R - * The registry type - * @param registryType - * A [ResourceKey] for the registry in question - * @param callback - * The callback to invoke - * @return This [AbstractRegistrate] instance + * @param R 注册表中的基础类型 + * @param registryType 注册表键 + * @param callback 注册表完成时执行的回调 + * @return 当前实例 */ open fun addRegisterCallback(registryType: ResourceKey>, callback: Runnable): S { registrationTracker.addAfterRegisterCallback(registryType, callback) @@ -410,28 +355,21 @@ abstract class AbstractRegistrate> protected construct } /** - * Check if a certain registry has completed registration. + * 查询指定注册表是否完成注册。 * - * @param R - * The registry type - * @param registryType - * A [ResourceKey] for the registry in question - * @return `true` iff the given registry has finished the registration step + * @param R 注册表中的基础类型 + * @param registryType 注册表键 + * @return 已完成注册时返回真 */ open fun isRegistered(registryType: ResourceKey>) = registrationTracker.isRegistered(registryType) /** - * Get the data provider instance for a given [GeneratorType]. Only works within datagen context, not during - * registration or init. + * 在数据生成阶段查询指定类型的提供器。此入口供生成回调使用。 * - * @param P - * The type of the provider - * @param type - * A [GeneratorType] representing the desired provider - * @return An [Optional] holding the provider, or empty if this provider was not registered. This can happen - * if datagen is run only for client or server providers. - * @throws IllegalStateException - * if datagen has not started yet + * @param P 提供器类型 + * @param type 要查询的 [GeneratorType] + * @return 包含提供器的 [Optional]。本轮未启用对应侧的生成任务时可能为空 + * @throws IllegalStateException 数据生成尚未开始 */ open fun

getDataProvider(type: GeneratorType

): Optional

{ val provider = this.provider @@ -442,57 +380,39 @@ abstract class AbstractRegistrate> protected construct } /** - * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data - * gen callback if it exists. + * 为构建器的条目设置指定类型的数据生成回调。重复设置会替换该条目原有的同类型回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param builder - * The builder for the entry - * @param type - * The [GeneratorType] to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param builder 条目的构建器 + * @param type 要生成的 [GeneratorType] + * @param cons 数据生成时执行的回调 + * @return 当前实例 */ open fun

setDataGenerator(builder: Builder, type: GeneratorType, cons: NonNullConsumer) = this.setDataGenerator(builder.name, builder.registryKey, type, cons) /** - * Mostly internal, removes the data generator for a certain entry/type combination if one was previously - * registered. + * 移除构建器的条目此前配置的指定类型数据生成回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param builder - * The builder for the entry - * @param type - * The [GeneratorType] to stop generating data for - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param builder 条目的构建器 + * @param type 要移除的 [GeneratorType] + * @return 当前实例 */ open fun

removeDataGenerator(builder: Builder, type: GeneratorType): S = this.removeDataGenerator(builder.name, builder.registryKey, type) /** - * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data - * gen callback if it exists. + * 为指定条目和生成器类型设置回调。重复设置会替换该条目原有的同类型回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param entry - * The name of the entry which the provider is for - * @param registryType - * A [Class] representing the registry type of the entry - * @param type - * The [GeneratorType] to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param entry 条目名称 + * @param registryType 条目所属的注册表键 + * @param type 要生成的 [GeneratorType] + * @param cons 数据生成时执行的回调 + * @return 当前实例 */ open fun

setDataGenerator(entry: String, registryType: ResourceKey>, type: GeneratorType, cons: NonNullConsumer) = setDataGenerator(entry, registryType, EntryMetadata.DataGenerator(type, cons)) @@ -506,20 +426,14 @@ abstract class AbstractRegistrate> protected construct } /** - * Mostly internal, removes the data generator for a certain entry/type combination if one was previously - * registered. + * 移除指定条目此前配置的同类型数据生成回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param entry - * The name of the entry which the provider is for - * @param registryType - * The registry type of the entry - * @param type - * The [GeneratorType] to stop generating data for - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param entry 条目名称 + * @param registryType 条目所属的注册表键 + * @param type 要移除的 [GeneratorType] + * @return 当前实例 */ open fun

removeDataGenerator(entry: String, registryType: ResourceKey>, type: GeneratorType): S { val existing = datagensByEntry.remove(Pair.of(entry, registryType), type) @@ -530,18 +444,12 @@ abstract class AbstractRegistrate> protected construct } /** - * Add a data generator callback that is not associated with any entry, which can never replace an existing data - * generator. - * - * This is useful to add data generator callbacks for miscellaneous data not strictly associated with an entry. + * 追加独立于注册条目的数据生成回调,用于生成没有绑定条目的资源。重复调用会累加回调。 * - * @param T - * The type of provider - * @param type - * The [GeneratorType] to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this [AbstractRegistrate] + * @param T 提供器类型 + * @param type 要生成的 [GeneratorType] + * @param cons 数据生成时执行的回调 + * @return 当前实例 */ open fun addDataGenerator(type: GeneratorType, cons: NonNullConsumer): S { if (dataGeneration.get()) { @@ -551,7 +459,7 @@ abstract class AbstractRegistrate> protected construct return self() } - /** Adds a callback before other callbacks registered for the same generator type. */ + /** 将回调插入指定生成器类型的队首,使它先于同类型的其他回调执行。 */ open fun addDataGeneratorFirst(type: GeneratorType, cons: NonNullConsumer): S { if (dataGeneration.get()) { check(provider == null) { "Cannot add data generator after construction of root generator" } @@ -574,13 +482,13 @@ abstract class AbstractRegistrate> protected construct private val terminology = Terminology() private val localeDerivations = EnumMap(MinecraftLocale::class.java) - /** Configures the source locale for this mod before data generation. */ + /** 在数据生成开始前配置本模组的源语言,供本地化声明解释源文本。 */ open fun sourceLocale(locale: MinecraftLocale): S { sourceLocale = locale return self() } - /** Starts a chain for export files created during this Registrate's DataGen run. */ + /** 开始配置本实例随数据生成写出的导出文件。 */ open fun export(): RegistrateExportBuilder = RegistrateExportBuilder(this) internal fun requestLocalizationExport(path: Path) { @@ -589,7 +497,7 @@ abstract class AbstractRegistrate> protected construct internal fun localizationExportPath(): Path? = localizationExportPath - /** Sets the defaults applied to localization declarations created after this call. */ + /** 设置此后创建的本地化声明使用的默认值。 */ open fun localizationDefaults(defaults: DeclarationDefaults): S { defaultLocalization = defaults return self() @@ -597,16 +505,17 @@ abstract class AbstractRegistrate> protected construct internal fun localizationDefaultValues(): DeclarationDefaults = defaultLocalization - /** Returns the source locale after validating this mod's configuration. */ + /** 读取本模组的源语言。数据生成前须显式配置。 */ open fun requireSourceLocale(): MinecraftLocale { val locale = sourceLocale requireNotNull(locale) { "[$modid] Configure sourceLocale before generating languages" } return locale } + /** 返回当前模组的术语表,供初始化时登记领域、术语和单位。 */ open fun terminology(): Terminology = terminology - /** Registers an imported target translation during mod setup for subsequent client DataGen runs. */ + /** 在模组初始化期间登记外部译文,供后续客户端侧数据生成解析。 */ open fun importTranslation(translation: ImportedTranslation): S { importedTranslations.add(translation) return self() @@ -617,7 +526,7 @@ abstract class AbstractRegistrate> protected construct for (translation in importedTranslations) registry.addImported(locale, translation, terminology) } - /** Configures how DataGen fills a missing locale for this mod. The rule for a target can be replaced during setup. */ + /** 指定数据生成补齐缺失译文的规则。初始化期间可替换同一目标语言的规则。 */ open fun deriveLocale(derivation: LocaleDerivation): S { localeDerivations[derivation.output] = derivation return self() @@ -644,47 +553,32 @@ abstract class AbstractRegistrate> protected construct } /** - * Add a custom translation mapping using the vanilla style of Identifier -> translation key conversion. + * 按原版的命名规则从类型和资源标识生成翻译键,再登记源文本。方块 `mymod:myblock` 的键是 `block.mymod.myblock`。 * - * @param type - * Type of the object, this is used as a prefix (e.g. - * `["block", "mymod:myblock"] -> "block.mymod.myblock"`) - * @param id - * ID of the object, which will be converted to a lang key via - * [Util.makeDescriptionId] - * @param localizedName - * (English) translation value - * @return A [MutableComponent] representing the translated text + * @param type 翻译键的类型前缀 + * @param id 对象的资源标识,由 [Util.makeDescriptionId] 转换 + * @param localizedName 使用本模组源语言书写的名称 + * @return 使用生成键的 [MutableComponent] */ open fun addLang(type: String, id: Identifier, localizedName: String): MutableComponent = addRawLang(Util.makeDescriptionId(type, id), localizedName) /** - * Add a custom translation mapping using the vanilla style of Identifier -> translation key conversion. - * Also - * appends a suffix to the key. + * 按原版规则生成翻译键,并在键末尾以点号连接后缀,再登记源文本。 * - * @param type - * Type of the object, this is used as a prefix (e.g. - * `["block", "mymod:myblock"] -> "block.mymod.myblock"`) - * @param id - * ID of the object, which will be converted to a lang key via - * [Util.makeDescriptionId] - * @param suffix - * A suffix which will be appended to the generated key (separated by a dot) - * @param localizedName - * (English) translation value - * @return A [MutableComponent] representing the translated text + * @param type 翻译键的类型前缀 + * @param id 对象的资源标识,由 [Util.makeDescriptionId] 转换 + * @param suffix 追加到翻译键末尾的片段 + * @param localizedName 使用本模组源语言书写的名称 + * @return 使用生成键的 [MutableComponent] */ open fun addLang(type: String, id: Identifier, suffix: String, localizedName: String): MutableComponent = addRawLang(Util.makeDescriptionId(type, id) + "." + suffix, localizedName) /** - * Add a custom translation mapping directly to the lang provider. + * 使用指定的翻译键直接登记源文本。 * - * @param key - * The translation key - * @param value - * The (English) translation value - * @return A [MutableComponent] representing the translated text + * @param key 原样写入语言资源的翻译键 + * @param value 使用本模组源语言书写的文本 + * @return 使用指定键的 [MutableComponent] */ open fun addRawLang(key: String, value: String): MutableComponent = addRawLang(key, value, TranslationSource.Kind.DECLARED) @@ -695,7 +589,7 @@ abstract class AbstractRegistrate> protected construct return Component.translatable(key) } - /** Declares independent text and returns a component that uses its exact translation key. */ + /** 声明独立于注册条目的本地化文本,并返回使用该翻译键的组件。 */ open fun addLocalization(key: TranslationKey, configure: Consumer): MutableComponent { if (dataGeneration.get()) { val builder = LocalizationDeclaration.Builder() @@ -739,7 +633,7 @@ abstract class AbstractRegistrate> protected construct return null } - /** Runs the registered callbacks for the supplied generator. */ + /** 依次执行为指定数据生成器登记的回调。 */ @Suppress("UNCHECKED_CAST") open fun genData(type: GeneratorType, gen: T) { if (!dataGeneration.get()) return @@ -768,14 +662,10 @@ abstract class AbstractRegistrate> protected construct } /** - * Enable skipping of registry entries and data generators that error during registration/generation. + * 开发时可跳过执行失败的注册条目和生成回调,便于继续排查其余条目。该设置仅在开发环境生效。 * - * **Should only be used for debugging!** `skipErrors(true)` will do nothing outside of a dev - * environment. - * - * @param skipErrors - * `true` to skip errors during registration/generation - * @return this [AbstractRegistrate] + * @param skipErrors 是否跳过注册及生成时的错误 + * @return 当前实例 */ open fun skipErrors(skipErrors: Boolean): S { if (skipErrors && !isDevEnvironment) { @@ -790,13 +680,10 @@ abstract class AbstractRegistrate> protected construct } /** - * Begin a new object, this is typically used at the beginning of a builder chain. The given name will be used until - * this method is called again. This makes it simple to create multiple entries - * with the same name, as is often the case with blocks/items, items/entities, and blocks/TEs. + * 为后续构建链设置当前条目名称。同名的方块和方块物品等条目可共用这个名称,下次调用会替换它。 * - * @param name - * The name to use for future entries - * @return this [AbstractRegistrate] + * @param name 后续条目默认采用的名称 + * @return 当前实例 */ open fun `object`(name: String): S { this.currentName = name @@ -804,14 +691,10 @@ abstract class AbstractRegistrate> protected construct } /** - * Set the default CreativeModeTab to be passed onto future builders. - * - * This special case method should be used if your creative tab instance was not created by Registrate, otherwise - * use [defaultCreativeTab]. + * 为之后创建的物品构建器指定默认创造模式标签页。已有标签页时传入其注册键,通过 Registrate 创建新标签页时使用对应重载。 * - * @param creativeModeTab - * The new default CreativeModeTab type - * @return This [AbstractRegistrate] instance + * @param creativeModeTab 默认创造模式标签页的注册键 + * @return 当前实例 */ open fun defaultCreativeTab(creativeModeTab: ResourceKey): S { defaultCreativeModeTab = creativeModeTab @@ -819,17 +702,11 @@ abstract class AbstractRegistrate> protected construct } /** - * Registers a new modifier callback to be used to modify the given CreativeModeTab. - * - * - * Registers a new callback to be invoked during the [BuildCreativeModeTabContentsEvent] event and - * used to modify what items are displayed on the given [CreativeModeTab]. - * - * Calling this method multiple times will add additional callbacks. + * 为指定创造模式标签页追加内容修改回调。每次 [BuildCreativeModeTabContentsEvent] 填充该页时,依次执行已登记的回调。 * - * @param creativeModeTab The [CreativeModeTab] to register this callback for - * @param modifier The modifier callback to be registered - * @return This [AbstractRegistrate] instance + * @param creativeModeTab 要修改的标签页 + * @param modifier 用来修改显示内容的回调 + * @return 当前实例 */ open fun modifyCreativeModeTab(creativeModeTab: ResourceKey, modifier: Consumer): S { creativeModeTabModifiers.put(creativeModeTab, modifier) @@ -837,112 +714,77 @@ abstract class AbstractRegistrate> protected construct } /** - * Apply a transformation to this [AbstractRegistrate]. Useful to apply helper methods within a fluent chain, - * e.g. + * 在链式调用中应用接收当前 [AbstractRegistrate] 实例的扩展函数。 * * ```java - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") * .transform(Utils::createMyBlock) - * .get(Block.class); + * .get(Registries.BLOCK); * ``` * - * @param func - * The [function][java.util.function.UnaryOperator] to apply - * @return this [AbstractRegistrate] + * @param func 接收并返回当前实例类型的转换函数 + * @return 转换函数的返回值 */ open fun transform(func: NonNullUnaryOperator): S = func.apply(self()) /** - * Apply a transformation to this [AbstractRegistrate]. Similar to [transform], - * but for actions that return a builder in-progress. Useful to apply helper methods - * within a fluent chain, e.g. + * 在链式调用中执行生成构建器的扩展函数。返回的构建器仍可继续配置。 * * ```java - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") * .transform(Utils::createMyBlock) - * .lang("My Block") // Can modify the builder afterwards + * .lang("My Block") // 继续配置构建器 * .register(); * ``` * - * @param R - * Registry type - * @param T - * Entry type - * @param P - * Parent type - * @param S2 - * Self type - * @param func - * The [function][Function] to apply - * @return the resultant [Builder] + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param P 父级对象类型 + * @param S2 返回的构建器类型 + * @param func 接收当前实例并创建构建器的函数 + * @return 转换函数创建的 [Builder] */ open fun > transform(func: NonNullFunction): S2 = func.apply(self()) /** - * Create a builder for a new entry. This is typically not needed, unless you are implementing a - * [custom builder type](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders). + * 以当前条目名称创建构建器,供[自定义构建器](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders)接入。 + * 工厂的首个参数是最近一次由 [object] 设置的名称。 * - * Uses the currently set name (via [object]) as the name for the new entry, and passes it to the - * factory as the first parameter. - * - * @param R - * Registry type - * @param T - * Entry type - * @param P - * Parent type - * @param S2 - * Self type - * @param factory - * The factory to create the builder - * @return The [Builder] instance + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param P 父级对象类型 + * @param S2 返回的构建器类型 + * @param factory 接收条目名称和注册回调的工厂 + * @return 工厂创建的 [Builder] */ open fun > entry(factory: NonNullBiFunction) = entry( currentName(), ) { callback: BuilderCallback -> factory.apply(currentName(), callback) } /** - * Create a builder for a new entry. This is typically not needed, unless you are implementing a - * [custom builder type](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders). + * 调用工厂创建可提交到当前实例的[自定义构建器](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders)。 * - * @param R - * Registry type - * @param T - * Entry type - * @param P - * Parent type - * @param S2 - * Self type - * @param name - * The name to use for the entry - * @param factory - * The factory to create the builder - * @return The [Builder] instance + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param P 父级对象类型 + * @param S2 返回的构建器类型 + * @param name 本次创建所用的条目名称 + * @param factory 接收注册回调的构建器工厂 + * @return 工厂创建的 [Builder] */ open fun > entry(name: String, factory: NonNullFunction): S2 = factory.apply(callback) /** - * Factory method to accept a completed builder and add it to the registration queue. - * - * Satisfies the functional interface [BuilderCallback], which is typically given to new builder instances - * when they are constructed. + * 接收配置完成的构建器,并将其条目加入待注册队列。构建器通常在创建时取得指向此入口的 [BuilderCallback]。 * - * @param R - * Registry type - * @param T - * Entry type - * @param name - * Thename of the entry being created - * @param type - * The registry to add the entry to - * @param builder - * The builder instance that was used to create this entry. Not used by default implementation, - * but custom extensions may use it for some purpose - * @param creator - * Constructor for the new entry object - * @param entryFactory - * Optional custom factory to create special [RegistryEntry] types - * @return A [RegistryEntry] that will hold the created entry after registration is complete + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param name 要创建的条目名称 + * @param type 要向其中登记条目的注册表键 + * @param builder 提供条目声明的构建器 + * @param creator 注册时创建条目对象的工厂 + * @param entryFactory 可选的 [RegistryEntry] 工厂,用于返回专用条目类型 + * @return 注册完成后可取得对象的 [RegistryEntry] */ protected open fun accept( name: String, @@ -974,28 +816,18 @@ abstract class AbstractRegistrate> protected construct } /** - * Returns the declarations for an entry submitted by this Registrate instance. + * 读取本实例为已提交条目保存的声明。 */ open fun getEntryMetadata(key: ResourceKey<*>): EntryMetadata = registrationTracker.getMetadata(key) /** - * Helper to create a new registry for custom objects. The returned [ResourceKey] can be used immediately in - * methods like [simple][simple] or - * [generic][generic]. - * - * Alternatively, a custom [builder][Builder] can be created. + * 为自定义对象创建注册表。返回的 [ResourceKey] 可立即用于 [simple]、[generic] 或自定义 [Builder]。 + * 注册表本身在 [NewRegistryEvent] 触发时创建。 * - * This method will automatically subscribe to the [NewRegistryEvent] and create the registry at the proper - * time. Thus, the new registry will not exist immediately after this is called. - * - * @param R - * The type of object the new registry will contain - * @param name - * The ID of this registry - * @param builder - * A function to create the [RegistryBuilder] that defines the other properties/behaviors of - * the created registry - * @return A [resource key][ResourceKey] referencing the to-be-created registry. + * @param R 新注册表收录的对象类型 + * @param name 注册表标识的路径部分 + * @param builder 接收注册表键并创建 [RegistryBuilder] 的函数 + * @return 待创建注册表的 [ResourceKey] */ open fun makeRegistry(name: String, builder: Function>, RegistryBuilder>): ResourceKey> { val registryId = ResourceKey.createRegistryKey(Identifier.fromNamespaceAndPath(modid, name)) @@ -1008,38 +840,25 @@ abstract class AbstractRegistrate> protected construct } /** - * Registers the given registry key as an unsynced datapack registry, which will cause data to be loaded from - * a datapack folder based on the registry's name. The datapack registry is not required to be present - * on clients when connecting to servers with the mod/registry. - * - * Data JSONs will be loaded from `data//modid/registryname/`, where `modid` is the - * namespace of the registry key. + * 注册一个仅在服务端加载的数据包注册表,客户端连接时可省略该注册表。 + * 模组命名空间下的注册表从 `data/<数据包命名空间>/<模组标识>/<注册表路径>/` 读取数据。 * - * @param name The ID of this registry - * @param codec The codec to be used for loading data from datapacks on servers - * @see .makeDatapackRegistry + * @param name 注册表标识的路径部分 + * @param codec 服务端读取数据包条目的编解码器 + * @return 新注册表的 [ResourceKey] + * @see makeDatapackRegistry */ open fun makeDatapackRegistry(name: String, codec: Codec) = makeDatapackRegistry(name, codec, null) /** - * Registers the registry key as a datapack registry, which will cause data to be loaded from - * a datapack folder based on the registry's name. - * - * Data JSONs will be loaded from `data//modid/registryname/`, where `modid` is the - * namespace of the registry key. + * 注册数据包注册表。模组命名空间下的注册表从 `data/<数据包命名空间>/<模组标识>/<注册表路径>/` 读取数据。 + * 提供网络编解码器时,服务器会同步条目,客户端也须拥有该注册表,可通过 [net.minecraft.client.multiplayer.ClientPacketListener.registryAccess] 访问。 + * 网络编解码器为空时由服务端独立加载。 * - * @param name The ID of this registry - * @param codec The codec to be used for loading data from datapacks on servers - * @param networkCodec The codec to be used for syncing loaded data to clients. - * If `networkCodec` is null, data will not be synced, and clients are not required to - * have this - * datapack registry to join a server. - * - * If `networkCodec` is not null, clients must have this datapack registry/mod - * when joining a server that has this datapack registry/mod. - * The data will be synced using the network codec and accessible via - * [net.minecraft.client.multiplayer.ClientPacketListener.registryAccess]. - * @see .makeDatapackRegistry + * @param name 注册表标识的路径部分 + * @param codec 服务端读取数据包条目的编解码器 + * @param networkCodec 同步到客户端时使用的编解码器,可以为空 + * @return 新注册表的 [ResourceKey] */ open fun makeDatapackRegistry(name: String, codec: Codec, networkCodec: Codec?): ResourceKey> { val registryId = ResourceKey.createRegistryKey(Identifier.fromNamespaceAndPath(modid, name)) @@ -1051,25 +870,48 @@ abstract class AbstractRegistrate> protected construct return registryId } - /* === Builder helpers === */ - // Generic + /* === 条目构建入口 === */ + // 通用条目 + + /** 使用当前条目名称提交注册,创建游戏对象时调用 [factory]。 */ open fun simple(registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = simple(currentName(), registryType, factory) + /** 以 [name] 提交指定注册表的条目。返回的引用在注册事件绑定后可取得对象。 */ open fun simple(name: String, registryType: ResourceKey>, factory: NonNullSupplier) = simple(this, name, registryType, factory) + /** 使用当前条目名称提交注册,将 [parent] 作为通用构建器的返回目标。 */ open fun simple(parent: P, registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = simple(parent, currentName(), registryType, factory) + /** + * 创建通用构建器并立即提交注册。对象由注册事件调用工厂创建。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的条目名称 + * @param registryType 目标注册表的键 + * @param factory 注册时创建条目对象的工厂 + * @return 延迟绑定的条目引用 + */ open fun simple(parent: P, name: String, registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = generic(parent, name, registryType, factory).register() + /** 使用当前名称创建通用构建器,可继续附加标签和数据生成配置。 */ open fun generic(registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(self(), registryType, factory) + /** 以 [name] 创建通用构建器。注册时执行 [factory]。 */ open fun generic(name: String, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(self(), name, registryType, factory) + /** 为当前名称创建通用构建器,调用其 `build` 后返回 [parent]。 */ open fun generic(parent: P, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(parent, currentName(), registryType, factory) + /** + * 为任意注册表创建通用条目构建器,供没有专用构建器的条目使用。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的条目名称 + * @param registryType 目标注册表的键 + * @param factory 注册时创建条目对象的工厂 + * @return 可继续设置标签、本地化和数据生成回调的构建器 + */ open fun generic(parent: P, name: String, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = entry>( name, @@ -1084,13 +926,24 @@ abstract class AbstractRegistrate> protected construct ) } - // Items + // 物品 + + /** 使用当前条目名称创建物品构建器,由 [factory] 接收配置完成的物品属性。 */ open fun item(factory: NonNullFunction): ItemBuilder = item(self(), factory) + /** 以 [name] 创建物品构建器,由 [factory] 接收配置完成的物品属性。 */ open fun item(name: String, factory: NonNullFunction): ItemBuilder = item(self(), name, factory) + /** 使用当前条目名称创建物品构建器,调用其 `build` 后返回 [parent]。 */ open fun item(parent: P, factory: NonNullFunction): ItemBuilder = item(parent, currentName(), factory) + /** + * 创建指定名称的物品构建器。构建器应用属性变换后,才将结果传给 [factory]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的物品名称 + * @param factory 使用最终物品属性创建物品的工厂 + * @return 可继续配置物品属性和数据生成的构建器 + */ open fun item(parent: P, name: String, factory: NonNullFunction): ItemBuilder = entry>( name, ) { callback: BuilderCallback -> @@ -1098,13 +951,24 @@ abstract class AbstractRegistrate> protected construct .tab(defaultCreativeModeTab) } - // Blocks + // 方块 + + /** 使用当前条目名称创建方块构建器,由 [factory] 接收配置完成的方块属性。 */ open fun block(factory: NonNullFunction): BlockBuilder = block(self(), factory) + /** 以 [name] 创建方块构建器,由 [factory] 接收配置完成的方块属性。 */ open fun block(name: String, factory: NonNullFunction): BlockBuilder = block(self(), name, factory) + /** 使用当前条目名称创建方块构建器,调用其 `build` 后返回 [parent]。 */ open fun block(parent: P, factory: NonNullFunction): BlockBuilder = block(parent, currentName(), factory) + /** + * 创建指定名称的方块构建器。构建器应用属性变换后,才将结果传给 [factory]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的方块名称 + * @param factory 使用最终方块属性创建方块的工厂 + * @return 可继续配置方块属性、附属物品和数据生成的构建器 + */ open fun block(parent: P, name: String, factory: NonNullFunction): BlockBuilder = entry>( name, ) { callback: BuilderCallback -> @@ -1117,13 +981,25 @@ abstract class AbstractRegistrate> protected construct ) } - // Entities + // 实体 + + /** 使用当前条目名称创建实体类型构建器,以 [classification] 设置原版实体分类。 */ open fun entity(factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(self(), factory, classification) + /** 以 [name] 创建实体类型构建器,以 [classification] 设置原版实体分类。 */ open fun entity(name: String, factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(self(), name, factory, classification) + /** 使用当前条目名称创建实体类型构建器,调用其 `build` 后返回 [parent]。 */ open fun entity(parent: P, factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(parent, currentName(), factory, classification) + /** + * 创建指定名称的实体类型构建器。游戏创建实体实例时调用 [factory]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的实体类型名称 + * @param factory 由实体类型和所在世界创建实体实例的工厂 + * @param classification 原版使用的实体分类 + * @return 可继续配置实体类型、渲染器和生成数据的构建器 + */ open fun entity(parent: P, name: String, factory: EntityFactory, classification: MobCategory): EntityBuilder = entry, EntityType, P, EntityBuilder>( name, @@ -1138,13 +1014,24 @@ abstract class AbstractRegistrate> protected construct ) } - // Block Entities + // 方块实体 + + /** 使用当前条目名称创建方块实体类型构建器,可接着指定适用方块。 */ open fun blockEntity(factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(self(), factory) + /** 以 [name] 创建方块实体类型构建器,可接着指定适用方块。 */ open fun blockEntity(name: String, factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(self(), name, factory) + /** 使用当前条目名称创建方块实体类型构建器,调用其 `build` 后返回 [parent]。 */ open fun blockEntity(parent: P, factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(parent, currentName(), factory) + /** + * 创建指定名称的方块实体类型构建器,由 [factory] 为指定位置创建方块实体实例。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的方块实体类型名称 + * @param factory 使用类型、位置和方块状态创建实例的工厂 + * @return 可继续指定适用方块和渲染器的构建器 + */ open fun blockEntity(parent: P, name: String, factory: BlockEntityFactory): BlockEntityBuilder = entry, BlockEntityType, P, BlockEntityBuilder>( name, @@ -1158,48 +1045,67 @@ abstract class AbstractRegistrate> protected construct ) } - // Fluids + // 流体 + + /** 为当前名称创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。 */ open fun fluid(): FluidBuilder = fluid(self()) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。 */ open fun fluid(typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), typeFactory) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。 */ open fun fluid(fluidType: NonNullSupplier): FluidBuilder = fluid(self(), fluidType) + /** 为当前名称创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。 */ open fun fluid(stillTexture: Identifier, flowingTexture: Identifier): FluidBuilder = fluid(self(), stillTexture, flowingTexture) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。 */ open fun fluid(stillTexture: Identifier, flowingTexture: Identifier, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, typeFactory) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。 */ open fun fluid(stillTexture: Identifier, flowingTexture: Identifier, fluidType: NonNullSupplier): FluidBuilder = fluid(self(), stillTexture, flowingTexture, fluidType) + /** 为当前名称创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid(stillTexture: Identifier, flowingTexture: Identifier, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。 */ open fun fluid(stillTexture: Identifier, flowingTexture: Identifier, typeFactory: FluidTypeFactory, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, typeFactory, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid(stillTexture: Identifier, flowingTexture: Identifier, fluidType: NonNullSupplier, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, fluidType, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun fluid(name: String): FluidBuilder = fluid(self(), name) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun fluid(name: String, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), name, typeFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun fluid(name: String, fluidType: NonNullSupplier): FluidBuilder = fluid(self(), name, fluidType) + /** 以 [name] 为注册名创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。 */ open fun fluid(name: String, stillTexture: Identifier, flowingTexture: Identifier): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。 */ open fun fluid(name: String, stillTexture: Identifier, flowingTexture: Identifier, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, typeFactory) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。 */ open fun fluid(name: String, stillTexture: Identifier, flowingTexture: Identifier, fluidType: NonNullSupplier): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, fluidType) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid(name: String, stillTexture: Identifier, flowingTexture: Identifier, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。 */ open fun fluid(name: String, stillTexture: Identifier, flowingTexture: Identifier, typeFactory: FluidTypeFactory, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, typeFactory, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid( name: String, stillTexture: Identifier, @@ -1208,26 +1114,35 @@ abstract class AbstractRegistrate> protected construct fluidFactory: FluidFactory, ): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, fluidType, fluidFactory) + /** 为当前名称创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P): FluidBuilder = fluid(parent, currentName()) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, currentName(), typeFactory) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, currentName(), fluidType) + /** 为当前名称创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, stillTexture: Identifier, flowingTexture: Identifier): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, stillTexture: Identifier, flowingTexture: Identifier, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, stillTexture: Identifier, flowingTexture: Identifier, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, fluidType) + /** 为当前名称创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid(parent: P, stillTexture: Identifier, flowingTexture: Identifier, fluidFactory: FluidFactory): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid(parent: P, stillTexture: Identifier, flowingTexture: Identifier, typeFactory: FluidTypeFactory, fluidFactory: FluidFactory): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid( parent: P, stillTexture: Identifier, @@ -1236,16 +1151,20 @@ abstract class AbstractRegistrate> protected construct fluidFactory: FluidFactory, ): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, fluidType, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun

fluid(parent: P, name: String): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture()) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun

fluid(parent: P, name: String, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), typeFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun

fluid(parent: P, name: String, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), fluidType) private fun defaultStillTexture(): Identifier = Identifier.fromNamespaceAndPath(modid, "block/" + currentName() + "_still") private fun defaultFlowingTexture(): Identifier = Identifier.fromNamespaceAndPath(modid, "block/" + currentName() + "_flow") + /** 以 [name] 为注册名创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, name: String, stillTexture: Identifier, flowingTexture: Identifier): FluidBuilder = entry>( name, ) { callback: BuilderCallback -> @@ -1258,6 +1177,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, name: String, stillTexture: Identifier, flowingTexture: Identifier, typeFactory: FluidTypeFactory): FluidBuilder = entry>( name, @@ -1271,6 +1191,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, name: String, stillTexture: Identifier, flowingTexture: Identifier, fluidType: NonNullSupplier): FluidBuilder = entry>( name, @@ -1284,6 +1205,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid(parent: P, name: String, stillTexture: Identifier, flowingTexture: Identifier, fluidFactory: FluidFactory): FluidBuilder = entry>( name, @@ -1297,6 +1219,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid( parent: P, name: String, @@ -1317,6 +1240,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid( parent: P, name: String, @@ -1337,16 +1261,28 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) - // Menu + // 菜单 + + /** 使用当前条目名称创建普通菜单构建器。界面工厂仅在客户端取得。 */ open fun menu(factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(currentName(), factory, screenFactory) + /** 以 [name] 创建普通菜单构建器。界面工厂仅在客户端取得。 */ open fun menu(name: String, factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(self(), name, factory, screenFactory) + /** 使用当前条目名称创建普通菜单构建器,调用其 `build` 后返回 [parent]。 */ open fun menu(parent: P, factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(parent, currentName(), factory, screenFactory) + /** + * 创建普通菜单构建器。菜单工厂接收菜单类型、窗口标识和玩家物品栏。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的菜单类型名称 + * @param factory 菜单实例工厂 + * @param screenFactory 客户端的界面工厂取值器 + * @return 尚可配置注册回调的菜单构建器 + */ open fun menu( parent: P, name: String, @@ -1365,15 +1301,26 @@ abstract class AbstractRegistrate> protected construct ) } + /** 使用当前条目名称创建支持读取网络数据的菜单构建器。 */ open fun menu(factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(currentName(), factory, screenFactory) + /** 以 [name] 创建支持读取网络数据的菜单构建器。 */ open fun menu(name: String, factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(self(), name, factory, screenFactory) + /** 使用当前条目名称创建支持读取网络数据的菜单构建器,调用其 `build` 后返回 [parent]。 */ open fun menu(parent: P, factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(parent, currentName(), factory, screenFactory) + /** + * 创建支持读取网络数据的菜单构建器。打开菜单时,工厂可读取服务端发送的附加数据。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的菜单类型名称 + * @param factory 可读取打开数据的菜单实例工厂 + * @param screenFactory 客户端的界面工厂取值器 + * @return 尚可配置注册回调的菜单构建器 + */ open fun menu( parent: P, name: String, @@ -1392,26 +1339,41 @@ abstract class AbstractRegistrate> protected construct ) } - // Creative Tab + // 创造模式标签页 + + /** 使用当前条目名称创建创造模式标签页构建器,并将该标签页设为本实例的默认页。 */ open fun defaultCreativeTab(): NoConfigBuilder = defaultCreativeTab(self()) + /** 以 [name] 创建创造模式标签页构建器,并将该标签页设为本实例的默认页。 */ open fun defaultCreativeTab(name: String): NoConfigBuilder = defaultCreativeTab(self(), name) + /** 使用当前名称创建默认标签页,调用构建器的 `build` 后返回 [parent]。 */ open fun

defaultCreativeTab(parent: P): NoConfigBuilder = defaultCreativeTab(parent, currentName()) + /** 以 [name] 创建默认标签页,调用构建器的 `build` 后返回 [parent]。 */ open fun

defaultCreativeTab(parent: P, name: String): NoConfigBuilder = defaultCreativeTab( parent, name, ) { tab: CreativeModeTab.Builder -> } + /** 为当前名称构建默认标签页,由 [config] 调整原版标签页构建器。 */ open fun defaultCreativeTab(config: Consumer): NoConfigBuilder = defaultCreativeTab(self(), config) + /** 以 [name] 构建默认标签页,由 [config] 调整原版标签页构建器。 */ open fun defaultCreativeTab(name: String, config: Consumer): NoConfigBuilder = defaultCreativeTab(self(), name, config) + /** 为当前名称构建默认标签页,由 [config] 调整原版构建器,完成后返回 [parent]。 */ open fun

defaultCreativeTab(parent: P, config: Consumer): NoConfigBuilder = defaultCreativeTab(parent, currentName(), config) + /** + * 创建标签页构建器并立即更新本实例的默认标签页指向。实际注册时先设置默认标题和图标,再执行 [config]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的标签页名称 + * @param config 用于调整标题、图标或展示内容的回调 + * @return 可追加注册回调的标签页构建器 + */ open fun

defaultCreativeTab(parent: P, name: String, config: Consumer): NoConfigBuilder { this.defaultCreativeModeTab = ResourceKey.create( Registries.CREATIVE_MODE_TAB, @@ -1442,7 +1404,7 @@ abstract class AbstractRegistrate> protected construct private val LOGGER = core() private val DATAGEN_LOGGER = datagen() - /** Enables development diagnostics when NeoForge is running outside production. */ + /** NeoForge 在开发环境中运行时启用开发诊断。 */ @get:JvmStatic val isDevEnvironment: Boolean get() = !FMLEnvironment.isProduction() diff --git a/src/main/java/com/modularmc/registrate/Registrate.kt b/src/main/java/com/modularmc/registrate/Registrate.kt index 8b098b0..7799b37 100644 --- a/src/main/java/com/modularmc/registrate/Registrate.kt +++ b/src/main/java/com/modularmc/registrate/Registrate.kt @@ -4,11 +4,12 @@ import com.modularmc.registrate.internal.util.RegistrateLogger import net.neoforged.fml.ModList +/** 一个模组的默认注册入口。在初始化阶段通过 [create] 创建并绑定到模组事件总线。 */ open class Registrate protected constructor(modid: String) : AbstractRegistrate(modid) { companion object { private val LOGGER = RegistrateLogger.core() - /** Creates a Registrate and attaches its listeners to the owning mod's event bus. */ + /** 创建一个 Registrate 实例,并将监听器绑定到所属模组的事件总线。 */ @JvmStatic fun create(modid: String): Registrate { val registrate = Registrate(modid) diff --git a/src/main/java/com/modularmc/registrate/RegistrateLib.java b/src/main/java/com/modularmc/registrate/RegistrateLib.java index 3846d5b..cb6908b 100644 --- a/src/main/java/com/modularmc/registrate/RegistrateLib.java +++ b/src/main/java/com/modularmc/registrate/RegistrateLib.java @@ -7,13 +7,11 @@ import org.apache.logging.log4j.Logger; /** - * Runtime entrypoint for the ModularMCLib variant of Registrate. + * ModularMCLib 维护的 Registrate 运行时入口。 * *

- * This library is intended to load as its own NeoForge mod so downstream - * mods can depend on it as a prerequisite during development. Integration - * scenarios, sample registrations, and visual validation belong in the test - * harness under {@code test/src/main}. + * 下游模组可将此库作为独立的 NeoForge 模组依赖。集成用例、注册示例和视觉检查入口位于 {@code test/src/main}。 + *

*/ @Mod(RegistrateLib.MOD_ID) public final class RegistrateLib { @@ -23,5 +21,10 @@ public final class RegistrateLib { public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); + /** + * 供 NeoForge 加载运行时库时实例化。各下游模组自行创建其所属的 {@link Registrate}。 + * + * @param modEventBus NeoForge 注入的本库模组事件总线 + */ public RegistrateLib(IEventBus modEventBus) {} } diff --git a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt index c39f350..e50f7d4 100644 --- a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt @@ -36,13 +36,10 @@ import java.util.function.Consumer import java.util.function.Supplier /** - * A builder for blocks, allows for customization of the [Block.Properties], creation of block items, and - * configuration of data associated with blocks (loot tables, recipes, etc.). + * 构建和注册方块,可配置方块属性、创建方块物品,并生成模型、配方和战利品表。 * - * @param T - * The type of block being built - * @param P - * Parent object type + * @param T 要构建的方块类型 + * @param P 父级对象类型 */ open class BlockBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -58,16 +55,10 @@ open class BlockBuilder protected constructor( private var tintSources: NonNullSupplier>>? = null /** - * Modify the properties of the block. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. + * 登记方块属性变换,构建方块时按登记顺序应用。变换返回另一份属性对象时,后续变换从新对象开始。 * - * - * If a different properties instance is returned, it will replace the existing one entirely. - * - * @param func - * The action to perform on the properties - * @return this [BlockBuilder] + * @param func 要应用的属性变换 + * @return 当前构建器 */ open fun properties(func: NonNullUnaryOperator): BlockBuilder { propertiesCallback = propertiesCallback.andThen(func) @@ -75,13 +66,10 @@ open class BlockBuilder protected constructor( } /** - * Replace the initial state of the block properties, without replacing or removing any modifications done via - * [properties]. + * 以另一方块的完整属性副本作为起点,保留已通过 [properties] 登记的变换。 * - * @param block - * The block to create the initial properties from (via - * [Block.Properties.ofFullCopy]) - * @return this [BlockBuilder] + * @param block 用于读取初始属性的方块供应器 + * @return 当前构建器 */ open fun initialProperties(block: NonNullSupplier): BlockBuilder { initialProperties = NonNullSupplier { BlockBehaviour.Properties.ofFullCopy(block.get()) } @@ -89,25 +77,17 @@ open class BlockBuilder protected constructor( } /** - * Create a standard [BlockItem] for this block, building it immediately, and not allowing for further - * configuration. - * + * 用默认配置提交此方块的 [BlockItem]。物品沿用方块的翻译键。 * - * The item will have no lang entry (since it would duplicate the block's) - * - * @return this [BlockBuilder] - * @see .item + * @return 当前构建器 + * @see item */ open fun simpleItem(): BlockBuilder = item().build() /** - * Create a standard [BlockItem] for this block, and return the builder for it so that further customization - * can be done. - * + * 创建标准 [BlockItem] 的构建器,便于继续配置物品。默认使用方块的翻译键。 * - * The item will have no lang entry (since it would duplicate the block's) - * - * @return the [ItemBuilder] for the [BlockItem] + * @return 方块物品的 [ItemBuilder] */ open fun item() = item( NonNullBiFunction { block: T, properties: Item.Properties -> @@ -119,18 +99,11 @@ open class BlockBuilder protected constructor( ) /** - * Create a [BlockItem] for this block, which is created by the given factory, and return the builder for it - * so that further customization can be done. - * + * 使用指定工厂创建方块物品构建器。默认使用简单的方块物品模型,并沿用方块的翻译键。 * - * By default, the item will have no lang entry (since it would duplicate the block's) and a simple block item - * model. - * - * @param I - * The type of the item - * @param factory - * A factory for the item, which accepts the block object and properties and returns a new item - * @return the [ItemBuilder] for the [BlockItem] + * @param I 物品类型 + * @param factory 接收方块和物品属性并创建物品的工厂 + * @return 方块物品的 [ItemBuilder] */ open fun item(factory: NonNullBiFunction): ItemBuilder> = owner.item( this, @@ -151,37 +124,28 @@ open class BlockBuilder protected constructor( } /** - * Create a [BlockEntity] for this block, which is created by the given factory, and assigned this block as - * its one and only valid block. + * 创建并提交方块实体类型,初始有效方块为当前方块。 * - * @param BE - * The type of the block entity - * @param factory - * A factory for the block entity - * @return this [BlockBuilder] - */ + * @param BE 方块实体类型 + * @param factory 创建方块实体的工厂 + * @return 当前构建器 + */ open fun simpleBlockEntity(factory: BlockEntityBuilder.BlockEntityFactory) = blockEntity(factory).build() /** - * Create a [BlockEntity] for this block, which is created by the given factory, and assigned this block as - * its one and only valid block. + * 创建方块实体构建器,初始有效方块为当前方块。可在返回的构建器上继续添加有效方块及其他配置。 * - * - * The created [BlockEntityBuilder] is returned for further configuration. - * - * @param BE - * The type of the block entity - * @param factory - * A factory for the block entity - * @return the [BlockEntityBuilder] - */ + * @param BE 方块实体类型 + * @param factory 创建方块实体的工厂 + * @return 方块实体的 [BlockEntityBuilder] + */ open fun blockEntity(factory: BlockEntityBuilder.BlockEntityFactory) = owner.blockEntity(this, name, factory).validBlock(asSupplier()) /** - * Registers the tint sources for this block in tint index order. + * 按模型的着色索引顺序登记方块着色来源。 * - * @param tintSources A side-safe supplier of the block tint sources - * @return this [BlockBuilder] + * @param tintSources 外层供应器须可在服务端安全创建,内层供应器在客户端取得着色来源 + * @return 当前构建器 */ open fun color(tintSources: NonNullSupplier>>): BlockBuilder { if (this.tintSources == null) { @@ -200,12 +164,10 @@ open class BlockBuilder protected constructor( } /** - * Assign the default blockstate, which maps all states to a single model file (via - * [RegistrateBlockModelGenerator.createTrivialCube]). This is the default, so it is generally not - * necessary - * to call, unless for undoing previous changes. + * 使用 [RegistrateBlockModelGenerator.createTrivialCube] 生成默认方块状态,所有状态共用一个立方体模型。 + * 可再次调用以替换之前设置的生成方式。 * - * @return this [BlockBuilder] + * @return 当前构建器 */ open fun defaultBlockstate(): BlockBuilder = blockstate { NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateBlockModelGenerator -> @@ -216,12 +178,11 @@ open class BlockBuilder protected constructor( } /** - * Configure the blockstate/models for this block. + * 设置此方块的方块状态和模型生成回调。 * - * @param cons - * The callback which will be invoked during data generation. - * @return this [BlockBuilder] - * @see .setData + * @param cons 提供数据生成回调的供应器 + * @return 当前构建器 + * @see setData */ open fun blockstate(cons: NonNullSupplier, RegistrateBlockModelGenerator>>): BlockBuilder { val blockstate: NonNullSupplier, RegistrateBlockModelGenerator>> = @@ -234,48 +195,36 @@ open class BlockBuilder protected constructor( } /** - * Assign the default translation, as specified by - * [RegistrateLangProvider.getAutomaticName]. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. + * 用 [RegistrateLangProvider.getAutomaticName] 从注册名称推导默认翻译,可用于恢复默认生成方式。 * - * @return this [BlockBuilder] + * @return 当前构建器 */ open fun defaultLang(): BlockBuilder = lang { obj: T -> obj.descriptionId } - /** Configures the source text and translations of this entry. */ + /** 使用方块的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): BlockBuilder = localization({ obj: T -> obj.descriptionId }, configure) /** - * Set the translation for this block. + * 为此方块指定源语言名称。 * - * @param name - * A localized English name - * @return this [BlockBuilder] + * @param name 使用模组源语言书写的方块名称 + * @return 当前构建器 */ open fun lang(name: String): BlockBuilder = lang({ obj: T -> obj.descriptionId }, name) /** - * Assign the default loot table, as specified by [RegistrateBlockLootTables.dropSelf]. This is the - * default, so it is generally not necessary to call, unless for - * undoing previous changes. + * 恢复默认战利品表。方块被破坏时按 [RegistrateBlockLootTables.dropSelf] 的规则掉落自身。 * - * @return this [BlockBuilder] + * @return 当前构建器 */ open fun defaultLoot(): BlockBuilder = loot { obj: RegistrateBlockLootTables, block: T -> obj.dropSelf(block) } /** - * Configure the loot table for this block. This is different than most data gen callbacks as the callback does not - * accept a [DataGenContext], but instead a - * [RegistrateBlockLootTables], for creating specifically block loot tables. - * - * - * If the block does not have a loot table (i.e. [Block.Properties.noLootTable] is called) this action will - * be *skipped*. + * 配置方块战利品表。回调接收专用的 [RegistrateBlockLootTables] 和方块对象。 + * 方块通过 [Block.Properties.noLootTable] 禁用战利品表时,跳过该回调。 * - * @param cons - * The callback which will be invoked during block loot table creation. - * @return this [BlockBuilder] + * @param cons 生成方块战利品表时执行的回调 + * @return 当前构建器 */ open fun loot(cons: NonNullBiConsumer) = setData( ProviderType.LOOT, @@ -290,24 +239,21 @@ open class BlockBuilder protected constructor( } /** - * Configure the recipe(s) for this block. + * 设置此方块的配方生成回调。 * - * @param cons - * The callback which will be invoked during data generation. - * @return this [BlockBuilder] - * @see .setData + * @param cons 数据生成时执行的回调 + * @return 当前构建器 + * @see setData */ open fun recipe(cons: NonNullBiConsumer, RegistrateRecipeProvider>) = setData(ProviderType.RECIPE, cons) private var clientExtension: NonNullSupplier>? = null /** - * Register a client extension for this block. - * The [IClientBlockExtensions] instance can be shared across many items. + * 登记方块客户端扩展。同一个 [IClientBlockExtensions] 实例可供多个方块共用。 * - * @param clientExtension - * The client extension to register for this block - * @return this [BlockBuilder] + * @param clientExtension 外层供应器须可在服务端安全创建,内层供应器在客户端取得扩展 + * @return 当前构建器 */ open fun clientExtension(clientExtension: NonNullSupplier>): BlockBuilder { if (this.clientExtension == null) { @@ -331,55 +277,41 @@ open class BlockBuilder protected constructor( } /** - * Assign [TagKey]`s` to this block. Multiple calls will add additional tags. + * 向此方块添加标签。多次调用会累加标签。 * - * @param tags - * The tags to assign - * @return this [BlockBuilder] + * @param tags 要添加的标签键 + * @return 当前构建器 */ @SafeVarargs fun tag(vararg tags: TagKey) = tag(ProviderType.BLOCK_TAGS, *tags) + /** 应用已登记的属性变换,写入注册键,再由工厂创建方块。 */ override fun createEntry(): T { var properties = this.initialProperties.get() properties = propertiesCallback.apply(properties) return factory.apply(properties.setId(resourceKey)) } + /** 用方块专用引用包装延迟绑定的条目,便于获取关联方块物品。 */ override fun createEntryWrapper(delegate: DeferredHolder) = BlockEntry(owner, delegate) + /** 提交方块注册,返回可保存到静态字段的方块引用。 */ override fun register(): BlockEntry = super.register() as BlockEntry companion object { /** - * Create a new [BlockBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - * - * - * The block will be assigned the following data: - * - * * A default blockstate file mapping all states to one model (via [.defaultBlockstate]) - * * A simple cube_all model (used in the blockstate) with one texture (via [.defaultBlockstate]) - * * A self-dropping loot table (via [.defaultLoot]) - * * The default translation (via [.defaultLang]) - * + * 创建带默认数据配置的 [BlockBuilder],集中设置可由子类替换的生成规则。 + * 默认让所有方块状态共用单纹理立方体模型,生成掉落自身的战利品表和默认名称。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the block - * @return A new [BlockBuilder] with reasonable default data generators. -

*/ + * @param T 方块类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 接收属性并创建方块的工厂 + * @return 配置好默认数据生成规则的构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: NonNullFunction) = BlockBuilder( owner, diff --git a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt index b011f88..f40c6ba 100644 --- a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt @@ -20,7 +20,6 @@ import net.minecraft.world.level.block.entity.BlockEntityType import net.minecraft.world.level.block.state.BlockState import net.neoforged.api.distmarker.Dist import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent -import net.neoforged.neoforge.capabilities.Capabilities import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent import net.neoforged.neoforge.registries.DeferredHolder @@ -29,12 +28,10 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.function.Consumer /** - * A builder for block entities, allows for customization of the valid blocks. + * 构建和注册方块实体类型,登记可承载此类型的方块。 * - * @param T - * The type of block entity being built - * @param P - * Parent object type + * @param T 方块实体类型 + * @param P 父级对象类型 */ open class BlockEntityBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -49,7 +46,15 @@ open class BlockEntityBuilder protected constructor( callback, Registries.BLOCK_ENTITY_TYPE, ) { + /** 由模组实现,用于游戏在指定位置创建方块实体实例。回调运行在发起创建的线程上。 */ fun interface BlockEntityFactory { + /** + * 创建与当前位置和方块状态对应的方块实体。 + * @param type 已注册的方块实体类型 + * @param pos 方块在世界中的位置 + * @param state 创建时的方块状态 + * @return 新的方块实体实例 + */ fun create(type: BlockEntityType, pos: BlockPos, state: BlockState): T } @@ -58,11 +63,10 @@ open class BlockEntityBuilder protected constructor( null /** - * Add a valid block for this block entity. + * 添加一个可承载此方块实体的方块。 * - * @param block - * A supplier for the block to add at registration time - * @return this [BlockEntityBuilder] + * @param block 注册时取得方块的供应器 + * @return 当前构建器 */ open fun validBlock(block: NonNullSupplier): BlockEntityBuilder { validBlocks.add(block) @@ -70,11 +74,10 @@ open class BlockEntityBuilder protected constructor( } /** - * Add valid blocks for this block entity. + * 添加多个可承载此方块实体的方块。 * - * @param blocks - * An array of suppliers for the block to add at registration time - * @return this [BlockEntityBuilder] + * @param blocks 注册时取得各个方块的供应器 + * @return 当前构建器 */ @SafeVarargs fun validBlocks(vararg blocks: NonNullSupplier): BlockEntityBuilder { @@ -83,20 +86,13 @@ open class BlockEntityBuilder protected constructor( } /** - * Register an [BlockEntityRenderer] for this block entity. - * - * + * 为此方块实体类型登记客户端渲染器。 * - * @apiNote This requires the [Class] of the block entity object, which can only be gotten by inspecting an - * instance of it. Thus, the entity will be constructed to register the renderer. - * - * @param renderer - * A (server safe) supplier to an [Function] that will provide this block entity's renderer - * given the renderer dispatcher - * @return this [BlockEntityBuilder] + * @param renderer 外层供应器须可在服务端安全创建,内层工厂在客户端接收渲染上下文并创建渲染器 + * @return 当前构建器 */ open fun renderer(renderer: NonNullSupplier>>): BlockEntityBuilder { - if (this.renderer == null) { // First call only + if (this.renderer == null) { // 首次设置时绑定渲染事件,后续设置由该监听器读取。 unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerRenderer() } } } this.renderer = renderer @@ -115,10 +111,10 @@ open class BlockEntityBuilder protected constructor( } /** - * Register [Capabilities] for this block entity. + * 在能力注册事件中为此方块实体登记能力。 * - * @param registerCapabilitiesEvent A consumer for the register capabilities event - * @return this [BlockEntityBuilder] + * @param registerCapabilitiesEvent 接收能力注册事件的回调 + * @return 当前构建器 */ open fun registerCapability(registerCapabilitiesEvent: Consumer): BlockEntityBuilder { addModListener( @@ -129,6 +125,7 @@ open class BlockEntityBuilder protected constructor( return this } + /** 在注册时收集有效方块,并将实例工厂与新类型绑定。 */ override fun createEntry(): BlockEntityType { val factory: BlockEntityFactory = this.factory val supplier: NonNullSupplier> = asSupplier() @@ -137,34 +134,25 @@ open class BlockEntityBuilder protected constructor( return BlockEntityType({ pos, state -> factory.create(supplier.get(), pos, state) }, *valid) } + /** 用方块实体类型的专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder, BlockEntityType>) = BlockEntityEntry(owner, delegate) + /** 提交方块实体类型注册,返回用于创建或查询实例的类型引用。 */ override fun register(): BlockEntityEntry = super.register() as BlockEntityEntry companion object { /** - * Create a new [BlockEntityBuilder] and configure data. Used in lieu of adding side-effects to constructor, - * so that alternate initialization strategies can be done in subclasses. - * - * - * The block entity will be assigned the following data: + * 创建 [BlockEntityBuilder],供子类在此入口附加初始化配置。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the block entity - * @return A new [BlockEntityBuilder] with reasonable default data generators. -

*/ + * @param T 方块实体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 创建方块实体的工厂 + * @return 新的方块实体构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: BlockEntityFactory) = BlockEntityBuilder(owner, parent, name, callback, factory) diff --git a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt index ee0d6b0..fb5df2a 100644 --- a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt @@ -1,4 +1,4 @@ -// Keep the Java overload signatures while formatting the Kotlin declarations. +// 格式化 Kotlin 声明时保留与 Java 调用方对应的重载签名。 @file:Suppress("ktlint:standard:max-line-length") package com.modularmc.registrate.builders @@ -39,13 +39,10 @@ import java.util.function.Consumer import java.util.function.Supplier /** - * A builder for entities, allows for customization of the [EntityType.Builder], easy creation of spawn egg items, - * and configuration of data associated with entities (loot tables, etc.). + * 构建和注册实体类型,可配置原版实体属性、刷怪蛋和实体战利品等数据。 * - * @param T - * The type of entity being built - * @param P - * Parent object type + * @param T 实体类型 + * @param P 父级对象类型 */ open class EntityBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -73,13 +70,10 @@ open class EntityBuilder protected constructor( private var spawnConfigured = false /** - * Modify the properties of the entity. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. + * 登记实体类型属性变换。创建实体类型时按登记顺序应用各次变换。 * - * @param cons - * The action to perform on the properties - * @return this [EntityBuilder] + * @param cons 配置原版实体类型构建器的回调 + * @return 当前构建器 */ open fun properties(cons: NonNullConsumer>): EntityBuilder { builderCallback = builderCallback.andThen(cons) @@ -87,14 +81,10 @@ open class EntityBuilder protected constructor( } /** - * Register an [EntityRenderer] for this entity. + * 登记此类型的实体渲染器,供客户端渲染事件调用。 * - * - * - * @param renderer - * A (server safe) supplier to an [EntityRendererProvider] that will provide this entity's - * renderer - * @return this [EntityBuilder] + * @param renderer 外层供应器须可在服务端安全创建,内层工厂在客户端接收渲染上下文并创建渲染器 + * @return 当前构建器 */ open fun renderer(renderer: NonNullSupplier>>): EntityBuilder { if (this.renderer == null) { @@ -116,17 +106,11 @@ open class EntityBuilder protected constructor( } /** - * Register a attributes for this entity. The entity must extend [LivingEntity]. - * + * 为 [LivingEntity] 类型登记属性。每个构建器只能设置一次。 * - * Cannot be called more than once per builder. - * - * @param attributes - * A supplier to the attributes for this entity, usually of the form - * `EntityClass::createAttributes` - * @return this [EntityBuilder] - * @throws IllegalStateException - * When called more than once + * @param attributes 用于创建属性的供应器,通常为实体类的静态方法引用 + * @return 当前构建器 + * @throws IllegalStateException 已登记过实体属性 */ @Suppress("UNCHECKED_CAST") open fun attributes(attributes: Supplier): EntityBuilder { @@ -146,21 +130,13 @@ open class EntityBuilder protected constructor( } /** - * Register a spawn placement for this entity. The entity must extend [Mob] and allow construction with a - * `null` [net.minecraft.world.level.Level]. - * - * - * Cannot be called more than once per builder. + * 为 [Mob] 类型登记生成位置规则。每个构建器只能设置一次。 * - * @param type - * The type of placement to use - * @param heightmap - * Which heightmap to use to choose placement locations - * @param predicate - * A predicate to check spawn locations for validity - * @return this [EntityBuilder] - * @throws IllegalStateException - * When called more than once + * @param type 生成位置类型 + * @param heightmap 用于查询候选生成位置的高度图 + * @param predicate 判断候选位置能否生成该实体的条件 + * @return 当前构建器 + * @throws IllegalStateException 已登记过生成位置规则 */ open fun spawnPlacement( type: SpawnPlacementType, @@ -184,7 +160,7 @@ open class EntityBuilder protected constructor( return this } - /** Registers a spawn egg for this entity and allows customization of its item builder. */ + /** 为此实体登记刷怪蛋,可通过回调继续配置其物品构建器。 */ @JvmOverloads open fun spawnEgg(consumer: NonNullConsumer>> = NonNullConsumer.noop()): EntityBuilder { val eggBuilder = owner @@ -196,35 +172,26 @@ open class EntityBuilder protected constructor( } /** - * Assign the default translation, as specified by - * [com.modularmc.registrate.providers.RegistrateLangProvider.getAutomaticName]. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. - * - * @return this [EntityBuilder] + * 从注册名称推导默认实体名称。可再次调用以恢复默认翻译。 */ open fun defaultLang(): EntityBuilder = lang { obj: EntityType -> obj.descriptionId } - /** Configures the source text and translations of this entry. */ + /** 使用实体类型的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): EntityBuilder = localization({ obj: EntityType -> obj.descriptionId }, configure) /** - * Set the translation for this entity. + * 为此实体指定源语言名称。 * - * @param name - * A localized English name - * @return this [EntityBuilder] + * @param name 使用模组源语言书写的实体名称 + * @return 当前构建器 */ open fun lang(name: String): EntityBuilder = lang({ obj: EntityType -> obj.descriptionId }, name) /** - * Configure the loot table for this entity. This is different than most data gen callbacks as the callback does not - * accept a [DataGenContext], but instead a - * [RegistrateEntityLootTables], for creating specifically entity loot tables. + * 设置实体战利品表。回调接收 [RegistrateEntityLootTables] 和实体类型。 * - * @param cons - * The callback which will be invoked during entity loot table creation. - * @return this [EntityBuilder] + * @param cons 生成实体战利品表时执行的回调 + * @return 当前构建器 */ open fun loot(cons: NonNullBiConsumer>) = setData( ProviderType.LOOT, @@ -235,54 +202,41 @@ open class EntityBuilder protected constructor( } /** - * Assign [TagKey]`s` to this entity. Multiple calls will add additional tags. + * 向此实体类型添加标签。多次调用会累加标签。 * - * @param tags - * The tags to assign - * @return this [EntityBuilder] + * @param tags 要添加的标签键 + * @return 当前构建器 */ @SafeVarargs fun tag(vararg tags: TagKey>) = tag(ProviderType.ENTITY_TAGS, *tags) + /** 将构建回调应用到原版构建器,再使用当前注册键创建实体类型。 */ override fun createEntry(): EntityType { val builder: EntityType.Builder = this.builder.get() builderCallback.accept(builder) return builder.build(resourceKey) } + /** 用实体类型专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder, EntityType>) = EntityEntry(owner, delegate) + /** 提交实体类型注册,返回供后续生成和查询实体使用的引用。 */ override fun register(): EntityEntry = super.register() as EntityEntry companion object { /** - * Create a new [EntityBuilder] and configure data. Used in lieu of adding side-effects to constructor, so - * that alternate initialization strategies can be done in subclasses. - * - * - * The entity will be assigned the following data: - * - * * The default translation (via [.defaultLang]) - * + * 创建 [EntityBuilder] 并配置默认翻译。子类可在此入口扩展初始化。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the entity - * @param classification - * The [MobCategory] of the entity - * @return A new [EntityBuilder] with reasonable default data generators. -

*/ + * @param T 实体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 创建实体的工厂 + * @param classification 实体的 [MobCategory] + * @return 配置好默认翻译的实体构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: EntityFactory, classification: MobCategory) = EntityBuilder(owner, parent, name, callback, factory, classification) diff --git a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt index d501123..29b083b 100644 --- a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt @@ -1,4 +1,4 @@ -@file:Suppress("ktlint:standard:max-line-length") // Spotless reports a line-length violation at the file header during formatting. +@file:Suppress("ktlint:standard:max-line-length") // Spotless 格式化时会在文件头报告行宽超限。 package com.modularmc.registrate.builders @@ -53,12 +53,17 @@ import java.util.function.Consumer import java.util.function.Supplier import java.util.function.ToIntFunction +/** 配置流体类型、源流体和流动流体的注册,并可附带方块、桶及客户端模型。 */ open class FluidBuilder : AbstractBuilder> { + /** 由模组提供,用于在注册阶段按配置创建一个新的 NeoForge 流体类型。 */ fun interface FluidTypeFactory { + /** 以配置完成的 [properties] 创建流体类型,返回供源流体与流动流体共享的实例。 */ fun create(properties: FluidType.Properties): FluidType } + /** 由模组提供,用于在流体注册阶段创建具体的流动流体。 */ fun interface FluidFactory { + /** 用已配置的 [properties] 创建流动流体。属性中引用的附属条目由注册流程延迟取得。 */ fun create(properties: BaseFlowingFluid.Properties): T } @@ -67,10 +72,10 @@ open class FluidBuilder : AbstractBuilder> /** - * Supplies the client extension for this fluid type. + * 为该流体类型登记客户端扩展。 * - * @param clientExtension the side-safe supplier of the client extension - * @return this fluid builder + * @param clientExtension 外层供应器须可在服务端安全创建,内层供应器在客户端读取扩展 + * @return 当前构建器 */ open fun clientExtension(clientExtension: NonNullSupplier>): FluidBuilder { if (!this::clientExtensionFactory.isInitialized) { @@ -81,7 +86,7 @@ open class FluidBuilder : AbstractBuilder { unsafeRunWhenOn(Dist.CLIENT) { @@ -95,6 +100,7 @@ open class FluidBuilder : AbstractBuilder>): FluidBuilder { if (!this::fluidModel.isInitialized) { unsafeRunWhenOn(Dist.CLIENT) { Runnable { registerModel() } } @@ -105,7 +111,7 @@ open class FluidBuilder : AbstractBuilder - // Model loading runs again after resource reloads. + // 资源重载后会重新加载模型。 owner.modEventBus!!.addListener { event: RegisterFluidModelsEvent -> event.register(fluidModel.get().get(), source.get(), flowing) } @@ -140,6 +146,7 @@ open class FluidBuilder : AbstractBuilder private val tags = ObjectOpenHashSet>() + /** 创建会同时注册新流体类型的流体构建器。实际类型由 [typeFactory] 延迟创建。 */ constructor( owner: AbstractRegistrate<*>, parent: P, @@ -155,6 +162,7 @@ open class FluidBuilder : AbstractBuilder, parent: P, @@ -167,17 +175,14 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { typeProperties = typeProperties.andThen(cons) @@ -185,42 +190,36 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { fluidProperties = fluidProperties.andThen(cons) return this } - /** Generates a default name from the source fluid's registry path using the fluid type's description key. */ + /** 根据源流体的注册路径推导默认名称,并使用流体类型的描述键。 */ open fun defaultLang(): FluidBuilder = defaultLang({ f: T -> f.fluidType.descriptionId }, sourceName) - /** Configures the source text and translations of this entry. */ + /** 使用流体类型的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): FluidBuilder = localization({ fluid: T -> fluid.fluidType.descriptionId }, configure) /** - * Set the translation for this fluid. + * 为此流体指定源语言名称。 * - * @param name - * A localized English name - * @return this [FluidBuilder] + * @param name 使用模组源语言书写的流体名称 + * @return 当前构建器 */ open fun lang(name: String): FluidBuilder = lang({ f: T -> f.fluidType.descriptionId }, name) /** - * Create a standard [BaseFlowingFluid.Source] for this fluid which will be built and registered along with - * this fluid. + * 为此流体配置标准 [BaseFlowingFluid.Source],随流动流体一起构建和登记。 * - * @return this [FluidBuilder] - * @see .source - * @throws IllegalStateException - * If [source] has been called before this method + * @return 当前构建器 + * @see source + * @throws IllegalStateException 已配置过源流体 */ open fun defaultSource(): FluidBuilder { check(this.defaultSource == null) { "Cannot set a default source after a custom source has been created" } @@ -229,12 +228,10 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { this.defaultSource = false @@ -243,14 +240,10 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBlock == null) { "Cannot set a default block after a custom block has been created" } @@ -259,10 +252,9 @@ open class FluidBuilder : AbstractBuilder @@ -274,14 +266,11 @@ open class FluidBuilder : AbstractBuilder block(factory: NonNullBiFunction): BlockBuilder> { check(this.defaultBlock != false) { "Only one call to block/noBlock per builder allowed" } @@ -313,6 +302,7 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBlock != false) { "Only one call to block/noBlock per builder allowed" } @@ -321,14 +311,10 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBucket == null) { "Cannot set a default bucket after a custom bucket has been created" } @@ -337,10 +323,9 @@ open class FluidBuilder : AbstractBuilder @@ -352,15 +337,11 @@ open class FluidBuilder : AbstractBuilder bucket(factory: NonNullBiFunction): ItemBuilder> { check(this.defaultBucket != false) { "Only one call to bucket/noBucket per builder allowed" } @@ -383,6 +364,7 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBucket != false) { "Only one call to bucket/noBucket per builder allowed" } @@ -391,11 +373,10 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { @@ -417,11 +398,10 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { @@ -442,7 +422,7 @@ open class FluidBuilder : AbstractBuilder(sourceName, Registries.BLOCK) this.typeProperties.accept(properties) - // Use the sibling block's description ID for the default FluidType when it is already registered. + // 关联方块已注册时,默认流体类型沿用该方块的描述键。 if (block.isPresent && block.get().isBound) { properties.descriptionId(block.get().get().descriptionId) } else { @@ -457,13 +437,11 @@ open class FluidBuilder : AbstractBuilder { if (registerType) { @@ -485,26 +463,20 @@ open class FluidBuilder : AbstractBuilder } + /** 将流动流体包装为流体专用引用,供查询同组的源流体、方块和桶。 */ override fun createEntryWrapper(delegate: DeferredHolder): RegistryEntry = FluidEntry(owner, delegate) companion object { /** - * Create a new [FluidBuilder] and configure data. The created builder will use a default ([FluidType]) - * and fluid class ([BaseFlowingFluid.Flowing]). + * 创建使用默认 [FluidType] 和 [BaseFlowingFluid.Flowing] 的构建器。 * - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @return A new [FluidBuilder] with reasonable default data generators. - * @see .create -

*/ + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback) = create( owner, @@ -516,108 +488,65 @@ open class FluidBuilder : AbstractBuilder - * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param typeFactory - * A factory that creates the fluid type - * @return A new [FluidBuilder] with reasonable default data generators. - * @see .create -

*/ + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param typeFactory 创建流体类型的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, typeFactory: FluidTypeFactory): FluidBuilder = create(owner, parent, name, callback, typeFactory, ::Flowing) /** - * Create a new [FluidBuilder] and configure data. The created builder will use a default fluid class - * ([BaseFlowingFluid.Flowing]). + * 复用已注册的流体类型,流动流体采用 [BaseFlowingFluid.Flowing]。 * - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidType - * An existing and registered fluid type. - * @return A new [FluidBuilder] with reasonable default data generators. - * @see .create -

*/ + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param fluidType 已注册的流体类型 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, fluidType: NonNullSupplier): FluidBuilder = create(owner, parent, name, callback, FluidTypeFactory { fluidType.get() }, ::Flowing) /** - * Create a new [FluidBuilder] and configure data. The created builder will use a default ([FluidType]) - * and fluid class ([BaseFlowingFluid.Flowing]). + * 使用默认 [FluidType],由调用方提供流动流体的工厂。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new [FluidBuilder] with reasonable default data generators. -

*/ + * @param T 流体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param fluidFactory 创建流动流体的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, fluidFactory: FluidFactory): FluidBuilder = create(owner, parent, name, callback, ::FluidType, fluidFactory) /** - * Create a new [FluidBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - * - * - * The fluid will be assigned the following data: - * - * * The default translation (via [.defaultLang]) - * * A default [source fluid][BaseFlowingFluid.Source] (via [.defaultSource]) - * * A default block for the fluid, with its own default blockstate and model that configure the particle texture - * (via [.defaultBlock]) - * * A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid - * (via [.defaultBucket]) + * 创建 [FluidBuilder] 并安装默认配置,便于子类自定义初始化过程。 + * 默认生成源流体及其名称、带粒子纹理的液体方块模型,以及使用同名纹理的桶物品模型。 * - * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param typeFactory - * A factory that creates the fluid type - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new [FluidBuilder] with reasonable default data generators. -

*/ + * @param T 流体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param typeFactory 创建流体类型的工厂 + * @param fluidFactory 创建流动流体的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun create( owner: AbstractRegistrate<*>, @@ -634,38 +563,19 @@ open class FluidBuilder : AbstractBuilder - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidType - * An existing and registered fluid type - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new [FluidBuilder] with reasonable default data generators. -

*/ + * @param T 流体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param fluidType 已注册并由当前流体复用的类型 + * @param fluidFactory 创建流动流体的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun create( owner: AbstractRegistrate<*>, diff --git a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt index a0660c8..fa4d0da 100644 --- a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt @@ -38,13 +38,10 @@ import java.util.function.Consumer import java.util.function.Supplier /** - * A builder for items, allows for customization of the [Item.Properties] and configuration of data associated - * with items (models, recipes, etc.). + * 构建和注册物品,可配置物品属性、模型和配方等数据。 * - * @param T - * The type of item being built - * @param P - * Parent object type + * @param T 物品类型 + * @param P 父级对象类型 */ open class ItemBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -60,16 +57,10 @@ open class ItemBuilder protected constructor( Object2ObjectLinkedOpenHashMap() /** - * Modify the properties of the item. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. + * 登记物品属性变换,构建物品时按登记顺序应用。变换返回另一份属性对象时,后续变换从新对象开始。 * - * - * If a different properties instance is returned, it will replace the existing one entirely. - * - * @param func - * The action to perform on the properties - * @return this [ItemBuilder] + * @param func 要应用的属性变换 + * @return 当前构建器 */ open fun properties(func: NonNullUnaryOperator): ItemBuilder { propertiesCallback = propertiesCallback.andThen(func) @@ -77,19 +68,17 @@ open class ItemBuilder protected constructor( } /** - * Replace the initial state of the item properties, without replacing or removing any modifications done via - * [properties]. + * 设置物品属性的起点,保留已通过 [properties] 登记的变换。 * - * @param properties - * A supplier to to create the initial properties - * @return this [ItemBuilder] + * @param properties 创建初始属性的供应器 + * @return 当前构建器 */ open fun initialProperties(properties: NonNullSupplier): ItemBuilder { initialProperties = properties return this } - /** Adds this item to a tab, with an optional callback to customize its display. */ + /** 将物品加入指定创造模式标签页。可选的回调控制该物品在标签页中的呈现。 */ @JvmOverloads open fun tab( tab: ResourceKey, @@ -97,17 +86,17 @@ open class ItemBuilder protected constructor( modifier.accept(item) }, ): ItemBuilder { - creativeModeTabs[tab] = modifier // Should we get the current value in the map [if one exists] and - // .andThen() the 2 together? right now we replace any consumer that - // currently exists + creativeModeTabs[tab] = modifier // 同一个标签页只保存一个回调。 + // 重复登记会替换之前的回调。 + // 如果需要组合回调,由调用方组合后登记。 return this } /** - * Removes the modifier from this builder from the given [CreativeModeTab]. + * 移除该物品对此创造模式标签页登记的回调。 * - * @param tab A [ResourceKey] representing the [CreativeModeTab] to remove the modifier from - * @return This builder + * @param tab 要移除回调的标签页键 + * @return 当前构建器 */ open fun removeTab(tab: ResourceKey): ItemBuilder { creativeModeTabs.remove(tab) @@ -115,9 +104,9 @@ open class ItemBuilder protected constructor( } /** - * Assign the default model to this item, which is simply a generated model with a single texture of the same name. + * 使用与注册名称同名的单张纹理生成默认物品模型。 * - * @return this [ItemBuilder] + * @return 当前构建器 */ open fun defaultModel(): ItemBuilder = model { NonNullBiConsumer { ctx, provider -> @@ -126,10 +115,10 @@ open class ItemBuilder protected constructor( } /** - * Generates the default item model with the supplied layer tints. + * 生成默认物品模型,并为模型各层配置着色来源。 * - * @param tints The tint sources in model layer order - * @return this [ItemBuilder] + * @param tints 按模型图层顺序排列的着色来源 + * @return 当前构建器 */ open fun defaultModel(vararg tints: ItemTintSource): ItemBuilder = model { NonNullBiConsumer { ctx, provider -> @@ -139,12 +128,11 @@ open class ItemBuilder protected constructor( } /** - * Configure the model for this item. + * 设置此物品的模型生成回调。 * - * @param cons - * The callback which will be invoked during data creation - * @return this [ItemBuilder] - * @see .setData + * @param cons 提供数据生成回调的供应器 + * @return 当前构建器 + * @see setData */ open fun model(cons: NonNullSupplier, RegistrateItemModelGenerator>>): ItemBuilder { val model: NonNullSupplier, RegistrateItemModelGenerator>> = @@ -157,48 +145,43 @@ open class ItemBuilder protected constructor( } /** - * Assign the default translation, as specified by - * [RegistrateLangProvider.getAutomaticName]. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. + * 用 [RegistrateLangProvider.getAutomaticName] 从注册名称推导默认翻译,可用于恢复默认生成方式。 * - * @return this [ItemBuilder] + * @return 当前构建器 */ open fun defaultLang(): ItemBuilder = lang { obj: T -> obj.descriptionId } - /** Configures the source text and translations of this entry. */ + /** 使用物品的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): ItemBuilder = localization({ obj: T -> obj.descriptionId }, configure) /** - * Set the translation for this item. + * 为此物品指定源语言名称。 * - * @param name - * A localized English name - * @return this [ItemBuilder] + * @param name 使用模组源语言书写的物品名称 + * @return 当前构建器 */ open fun lang(name: String): ItemBuilder = lang({ obj: T -> obj.descriptionId }, name) /** - * Configure the recipe(s) for this item. + * 设置此物品的配方生成回调。 * - * @param cons - * The callback which will be invoked during data generation. - * @return this [ItemBuilder] - * @see .setData + * @param cons 数据生成时执行的回调 + * @return 当前构建器 + * @see setData */ open fun recipe(cons: NonNullBiConsumer, RegistrateRecipeProvider>) = setData(ProviderType.RECIPE, cons) /** - * Add burn time for the item + * 将物品登记为熔炉燃料。 * - * @param tick time in ticks for this item to burn in furnace. + * @param tick 该物品在熔炉中燃烧的游戏刻数 */ open fun burnTime(tick: Int): ItemBuilder = dataMap(NeoForgeDataMaps.FURNACE_FUELS, FurnaceFuel(tick)) /** - * Add compost chance for the item + * 登记物品的堆肥成功概率。 * - * @param chance chance for composter to increase one level when composting this item. + * @param chance 投入一个该物品时堆肥桶增加一层的概率 */ open fun compostable(chance: Float): ItemBuilder = dataMap(NeoForgeDataMaps.COMPOSTABLES, Compostable(chance)) @@ -217,18 +200,16 @@ open class ItemBuilder protected constructor( ) } } - creativeModeTabs.clear() // this registration should only fire once, to doubly ensure this, clear the map + creativeModeTabs.clear() // 这个注册回调只需执行一次,用完即清空待处理的扩展。 }, ) } /** - * Register a client extension for this item. The [IClientItemExtensions] instance can be shared across many - * items. + * 登记物品客户端扩展。同一个 [IClientItemExtensions] 实例可供多个物品共用。 * - * @param clientExtension - * The client extension to register for this item - * @return this [ItemBuilder] + * @param clientExtension 外层供应器须可在服务端安全创建,内层供应器在客户端取得扩展 + * @return 当前构建器 */ open fun clientExtension(clientExtension: NonNullSupplier>): ItemBuilder { if (this.clientExtension == null) { @@ -252,53 +233,40 @@ open class ItemBuilder protected constructor( } /** - * Assign [TagKey]`s` to this item. Multiple calls will add additional tags. + * 向物品添加标签。多次调用会累加标签。 * - * @param tags - * The tag to assign - * @return this [ItemBuilder] + * @param tags 要添加的物品标签 + * @return 当前构建器 */ @SafeVarargs fun tag(vararg tags: TagKey) = tag(ProviderType.ITEM_TAGS, *tags) + /** 应用物品属性变换,写入注册键,再由工厂创建物品。 */ override fun createEntry(): T { var properties = this.initialProperties.get() properties = propertiesCallback.apply(properties) return factory.apply(properties.setId(resourceKey)) } + /** 用物品专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder): RegistryEntry = ItemEntry(owner, delegate) + /** 提交物品注册,返回可用于构造物品堆叠的物品引用。 */ override fun register(): ItemEntry = super.register() as ItemEntry companion object { /** - * Create a new [ItemBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - * - * - * The item will be assigned the following data: - * - * * A simple generated model with one texture (via [.defaultModel]) - * * The default translation (via [.defaultLang]) - * + * 创建 [ItemBuilder],并配置使用单张纹理的默认物品模型及默认翻译。子类可在此入口扩展初始化。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the item - * @return A new [ItemBuilder] with reasonable default data generators. -

*/ + * @param T 物品类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 接收属性并创建物品的工厂 + * @return 配置好默认模型和翻译的物品构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: NonNullFunction) = ItemBuilder(owner, parent, name, callback, factory) diff --git a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt index 6ff81c2..443ac20 100644 --- a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt @@ -22,6 +22,7 @@ import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent import net.neoforged.neoforge.common.extensions.IMenuTypeExtension import net.neoforged.neoforge.registries.DeferredHolder +/** 注册菜单类型,并在客户端为该类型绑定界面。菜单实例由打开菜单的游戏流程创建。 */ open class MenuBuilder( owner: AbstractRegistrate<*>, parent: P, @@ -36,18 +37,44 @@ open class MenuBuilder( callback, Registries.MENU, ) where S : Screen, S : MenuAccess { + /** 由模组提供,适用于只用菜单类型、窗口标识和物品栏即可创建的菜单。 */ fun interface MenuFactory { + /** + * 创建本次打开操作对应的菜单。 + * @param type 已注册的菜单类型 + * @param windowId 本次打开操作分配的窗口标识 + * @param inv 打开菜单的玩家物品栏 + * @return 新的菜单实例 + */ fun create(type: MenuType, windowId: Int, inv: Inventory): T } + /** 由模组提供,在普通菜单参数之外还可读取服务端发来的打开数据。 */ fun interface ForgeMenuFactory { + /** + * 使用当前窗口和玩家物品栏创建菜单。 + * @param type 已注册的菜单类型 + * @param windowId 本次打开操作分配的窗口标识 + * @param inv 打开菜单的玩家物品栏 + * @param buffer 可用时读取服务端附加数据,未附带数据时可为 `null` + * @return 新的菜单实例 + */ fun create(type: MenuType, windowId: Int, inv: Inventory, buffer: RegistryFriendlyByteBuf?): T } + /** 在客户端打开菜单时创建对应界面,界面可以通过 [MenuAccess] 访问该菜单。 */ fun interface ScreenFactory where T : Screen, T : MenuAccess { + /** + * 为已经创建的菜单实例构造客户端界面。 + * @param menu 当前打开的菜单 + * @param inv 当前玩家的物品栏 + * @param displayName 打开菜单时提供的标题组件 + * @return 要显示的界面 + */ fun create(menu: M, inv: Inventory, displayName: Component): T } + /** 使用只接收普通菜单参数的工厂构建菜单类型。界面工厂延迟到客户端注册时获取。 */ constructor( owner: AbstractRegistrate<*>, parent: P, @@ -64,6 +91,7 @@ open class MenuBuilder( screenFactory, ) + /** 创建菜单类型。客户端还会在界面注册事件中绑定对应的界面工厂。 */ override fun createEntry(): MenuType { val supplier = asSupplier() val menu = IMenuTypeExtension.create { id, inventory, buffer -> @@ -80,7 +108,9 @@ open class MenuBuilder( return menu } + /** 用菜单专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder, MenuType>): RegistryEntry, MenuType> = MenuEntry(owner, delegate) + /** 提交菜单类型注册,返回供后续打开菜单使用的引用。 */ override fun register(): MenuEntry = super.register() as MenuEntry } diff --git a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt index 7cc5457..005b6cf 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt @@ -30,6 +30,7 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.function.Consumer +/** 保存条目提交前的标签、本地化及数据生成配置,供具体条目构建器复用。构建器由模组初始化线程配置。 */ abstract class AbstractBuilder>( override val owner: AbstractRegistrate<*>, override val parent: P, @@ -44,9 +45,10 @@ abstract class AbstractBuilder { val entry = callback.accept(name, registryKey, this, ::createEntry, ::createEntryWrapper) submitted = true @@ -54,10 +56,13 @@ abstract class AbstractBuilder> = dataGenerators.values + /** 返回当前构建器的本地化声明。没有声明时返回 `null`。 */ fun localization(): EntryLocalization? = localization + /** 设置或替换指定类型的生成回调。提交前暂存在构建器中,提交后更新所属 Registrate 的回调。 */ override fun setData(type: GeneratorType, cons: NonNullBiConsumer, D>): S { if (submitted) return super.setData(type, cons) if (type === ProviderType.LANG) localization = null @@ -65,6 +70,7 @@ abstract class AbstractBuilder removeData(type: GeneratorType): S { if (submitted) return super.removeData(type) if (type === ProviderType.LANG) localization = null @@ -74,8 +80,10 @@ abstract class AbstractBuilder): RegistryEntry = RegistryEntry(owner, delegate) + /** 返回可提前保存的条目取值器。调用它取值时,条目须已注册并绑定。 */ override fun asSupplier(): NonNullSupplier = safeSupplier + /** 为当前条目追加标签。生成时由 [type] 对应的提供器写入,重复的标签键会合并。 */ fun tag(type: ProviderType, vararg tags: TagKey): S where TP : TagsProvider, TP : RegistrateTagsProvider { val keys = tagsByType.getOrPut(type) { val registered = ObjectOpenHashSet>() @@ -89,6 +97,7 @@ abstract class AbstractBuilder removeTag(type: ProviderType, vararg tags: TagKey): S where TP : TagsProvider, TP : RegistrateTagsProvider { val keys = tagsByType[type] ?: return self() for (key in tags) keys.remove(key) return self() } + /** 用条目名称生成默认源文,由 [langKeyProvider] 从已绑定对象取得翻译键。 */ open fun lang(langKeyProvider: NonNullFunction): S = defaultLang(langKeyProvider, name) + /** 为翻译键登记显式源文。键在生成阶段从已绑定对象读取,声明采用所属模组的默认元数据。 */ open fun lang(langKeyProvider: NonNullFunction, name: String): S = localization( langKeyProvider, { LocalizationDeclaration.sourceText(name, owner.localizationDefaultValues()) }, @@ -116,7 +128,7 @@ abstract class AbstractBuilder, path: String): S = localization(key, { LocalizationDeclaration.sourceText(RegistrateLangProvider.toEnglishName(path), owner.localizationDefaultValues()) }, Kind.AUTOMATIC) - /** Declares text whose translation key is read from the registered object during DataGen. */ + /** 登记本地化声明。数据生成时从已绑定的注册对象解析翻译键。 */ open fun localization(key: NonNullFunction, configure: Consumer): S { val declaration = LocalizationDeclaration.Builder().also(configure::accept).build(owner.localizationDefaultValues()) return localization(key, { declaration }, Kind.DECLARED) diff --git a/src/main/java/com/modularmc/registrate/builders/base/Builder.kt b/src/main/java/com/modularmc/registrate/builders/base/Builder.kt index fab48e6..2a3baf9 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/Builder.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/Builder.kt @@ -16,50 +16,71 @@ import net.minecraft.core.Registry import net.minecraft.resources.ResourceKey import net.neoforged.neoforge.registries.datamaps.DataMapType -/** Collects entry declarations during mod setup and submits them to the owning Registrate. */ +/** + * 在模组初始化期间收集条目配置,并将其提交给所属 Registrate。 + * 提交前可继续链式配置,条目对象在延迟引用绑定后可读。 + * + * @param R 注册表中的基础类型 + * @param T 条目的具体类型 + * @param P 构建链的父级类型 + * @param S 当前构建器类型 + */ interface Builder> : NonNullSupplier> { val owner: AbstractRegistrate<*> val parent: P val name: String val registryKey: ResourceKey> - /** Submits the entry and returns its deferred holder. Each ID can be submitted once per registry. */ + /** 提交条目并返回延迟引用。同一注册表内每个资源标识只能提交一次。 */ fun register(): RegistryEntry + /** 返回已经提交给 Registrate 的条目引用。条目尚未提交时抛出 [IllegalArgumentException]。 */ override fun get(): RegistryEntry = owner.get(name, registryKey) - /** The registered object, available after its holder binds. */ + /** 读取已注册的对象。调用前须等该条目的延迟引用完成绑定。 */ val entry: T get() = get().get() + /** 返回延迟取得实际游戏对象的取值器。可在注册前保存取值器,实际取值须等待条目绑定。 */ fun asSupplier(): NonNullSupplier + /** 为当前条目设置指定类型的生成回调。重复设置会替换此前为该条目配置的同类型回调。 */ @Suppress("UNCHECKED_CAST") fun setData(type: GeneratorType, cons: NonNullBiConsumer, D>): S { owner.setDataGenerator(this, type) { cons.accept(DataGenContext.from(this), it) } return this as S } + /** 移除当前条目指定类型的生成回调。 */ @Suppress("UNCHECKED_CAST") fun removeData(type: GeneratorType): S { owner.removeDataGenerator(this, type) return this as S } + /** 为当前模组追加独立的生成回调,回调只接收匹配类型的生成器。 */ @Suppress("UNCHECKED_CAST") fun addMiscData(type: GeneratorType, cons: NonNullConsumer): S { owner.addDataGenerator(type, cons) return this as S } + /** 为当前条目的数据映射设置固定值,由数据生成阶段写出。 */ fun dataMap(type: DataMapType, value: D): S = dataMap(type) { value } + /** 在数据生成期间根据当前条目的上下文计算数据映射值。 */ fun dataMap(type: DataMapType, factory: NonNullFunction, D>): S = dataMap(type) { context, _ -> factory.apply( context, ) } + /** + * 在数据生成期间用条目信息和本轮注册表查询计算数据映射值。 + * @param type 要写入的数据映射类型 + * @param factory 接收条目上下文和注册表查询的工厂 + * @return 当前构建器 + */ @Suppress("UNCHECKED_CAST") fun dataMap(type: DataMapType, factory: NonNullBiFunction, HolderLookup.Provider, D>): S { owner.addDataGenerator(ProviderType.DATA_MAP) { provider -> @@ -69,14 +90,14 @@ interface Builder> : NonNullSup return this as S } - /** Adds a callback that runs after the object is inserted into its registry. */ + /** 添加在对象写入所属注册表后执行的回调。 */ @Suppress("UNCHECKED_CAST") fun onRegister(callback: NonNullConsumer): S { owner.addRegisterCallback(name, registryKey, callback) return this as S } - /** Runs the callback after this entry binds and the dependency registry is complete. */ + /** 当本条目已绑定且依赖的注册表完成注册后执行回调。 */ fun onRegisterAfter(dependencyType: ResourceKey>, callback: NonNullConsumer): S = onRegister { value -> if (owner.isRegistered(dependencyType)) { callback.accept(value) @@ -85,10 +106,11 @@ interface Builder> : NonNullSup } } + /** 将当前构建器交给 [func] 转换为另一个类型的构建器,并继续调用其构建链。 */ @Suppress("UNCHECKED_CAST") fun > transform(func: NonNullFunction): S2 = func.apply(this as S) - /** Registers the entry and returns the parent so the enclosing chain can continue. */ + /** 提交条目并返回父级对象,以便继续外层构建链。 */ fun build(): P { register() return parent diff --git a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt index 74a4b44..915e82e 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt @@ -8,9 +8,12 @@ import net.minecraft.core.Registry import net.minecraft.resources.ResourceKey import net.neoforged.neoforge.registries.DeferredHolder -/** Submits a completed builder to its owner during mod setup. The creator runs at registry time. */ +/** + * 接收构建完成的条目,将对象创建推迟到 NeoForge 注册阶段。 + * 所属 Registrate 在模组初始化时将此回调交给构建器。构建器配置完成后调用一次。 + */ interface BuilderCallback { - /** Queues an entry with its holder factory and returns the resulting deferred holder. */ + /** 将条目、对象工厂和引用工厂提交到待注册队列,返回该条目的延迟引用。 */ fun accept( name: String, type: ResourceKey>, @@ -19,7 +22,7 @@ interface BuilderCallback { entryFactory: NonNullFunction, out RegistryEntry>, ): RegistryEntry - /** Queues an entry using the default holder wrapper for its registry. */ + /** 用目标注册表的默认引用类型提交条目。 */ fun accept(name: String, type: ResourceKey>, builder: Builder, factory: NonNullSupplier): RegistryEntry = accept(name, type, builder, factory) { RegistryEntry(builder.owner, it) } } diff --git a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt index 234e49c..cfed634 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt @@ -6,6 +6,7 @@ import com.modularmc.registrate.util.nullness.NonNullSupplier import net.minecraft.core.Registry import net.minecraft.resources.ResourceKey +/** 供没有专用构建器的条目使用。在通用注册、标签和数据生成配置之外,由工厂负责创建对象。 */ open class NoConfigBuilder( owner: AbstractRegistrate<*>, parent: P, @@ -14,5 +15,6 @@ open class NoConfigBuilder( registryType: ResourceKey>, private val factory: NonNullSupplier, ) : AbstractBuilder>(owner, parent, name, callback, registryType) { + /** 在注册时调用传入的条目工厂。 */ override fun createEntry(): T = factory.get() } diff --git a/src/main/java/com/modularmc/registrate/builders/base/package-info.java b/src/main/java/com/modularmc/registrate/builders/base/package-info.java index 3240767..bca52e2 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/package-info.java +++ b/src/main/java/com/modularmc/registrate/builders/base/package-info.java @@ -1,5 +1,5 @@ /** - * Base builder contracts and shared builder implementation scaffolding. + * 声明构建器的公共契约,以及各类构建器共用的基础逻辑。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.builders.base; diff --git a/src/main/java/com/modularmc/registrate/builders/package-info.java b/src/main/java/com/modularmc/registrate/builders/package-info.java index fde0603..3cb4b69 100644 --- a/src/main/java/com/modularmc/registrate/builders/package-info.java +++ b/src/main/java/com/modularmc/registrate/builders/package-info.java @@ -1,10 +1,9 @@ /** - * Fluent concrete builder APIs for registering content. + * 提供物品、方块、实体等具体类型的链式注册入口。 * *

- * These classes form the primary downstream-facing DSL. Shared builder - * contracts and scaffolding live in {@code com.modularmc.registrate.builders.base}, - * while this package focuses on content-specific registration behavior. + * 这些构建器负责各类条目的注册规则和默认配置。共用契约与基础逻辑位于 {@code com.modularmc.registrate.builders.base}。 + *

*/ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.builders; diff --git a/src/main/java/com/modularmc/registrate/difficulty/DifficultyLevel.java b/src/main/java/com/modularmc/registrate/difficulty/DifficultyLevel.java new file mode 100644 index 0000000..d7f67d9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/difficulty/DifficultyLevel.java @@ -0,0 +1,22 @@ +package com.modularmc.registrate.difficulty; + +import net.minecraft.util.StringRepresentable; + +import org.jspecify.annotations.NullMarked; + +/** + * 由模组的难度枚举实现,供配置按稳定标识选择档位。 + * 调用方保存 {@link #getSerializedName()} 返回的标识,枚举常量改名或调整顺序后仍可沿用已有配置。 + * 同一枚举中的档位标识必须唯一,枚举常量初始化后可从任意线程读取。 + */ +@NullMarked +public interface DifficultyLevel extends StringRepresentable { + + /** + * 返回当前档位在配置中使用的标识。 + * + * @return 非空白且在枚举常量初始化后保持固定的标识 + */ + @Override + String getSerializedName(); +} diff --git a/src/main/java/com/modularmc/registrate/difficulty/DifficultyValues.java b/src/main/java/com/modularmc/registrate/difficulty/DifficultyValues.java new file mode 100644 index 0000000..b16f5b1 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/difficulty/DifficultyValues.java @@ -0,0 +1,71 @@ +package com.modularmc.registrate.difficulty; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.jspecify.annotations.NullMarked; + +import java.util.EnumMap; +import java.util.Map; + +/** + * 将配置里的档位标识解析为枚举常量,再按该常量取出业务参数。 + * 建表后可供多线程查询。表中保存参数对象的引用,可变对象的线程安全由调用方负责。 + * + * @param 模组声明的难度枚举 + * @param 各档共用的参数类型 + */ +@NullMarked +public final class DifficultyValues & DifficultyLevel, V> { + + private final Object2ObjectLinkedOpenHashMap levelsById; + private final EnumMap valuesByLevel; + + /** + * 复制档位与取值的映射。多个档位可以引用同一份值。 + * + * @param levels 至少两个档位,通常由枚举的 {@code values()} 提供 + * @param values 每个已声明档位对应的非空值 + * @throws IllegalArgumentException 档位不足两个、标识为空白或重复, + * 或缺少某个档位的值 + */ + public DifficultyValues(D[] levels, Map values) { + if (levels.length < 2) throw new IllegalArgumentException("At least two difficulty levels are required"); + + levelsById = new Object2ObjectLinkedOpenHashMap<>(levels.length); + valuesByLevel = new EnumMap<>(levels[0].getDeclaringClass()); + for (D level : levels) { + String id = level.getSerializedName(); + if (id.isBlank()) throw new IllegalArgumentException("A difficulty ID is required for " + level.name()); + if (levelsById.putIfAbsent(id, level) != null) throw new IllegalArgumentException("Duplicate difficulty ID '" + id + "'"); + + V value = values.get(level); + if (value == null) throw new IllegalArgumentException("Missing value for difficulty '" + id + "'"); + valuesByLevel.put(level, value); + } + } + + /** + * 按配置中的标识查找档位,区分大小写。 + * + * @param id 从配置读取的档位标识 + * @return 与标识对应的枚举常量 + * @throws IllegalArgumentException 标识未声明,异常信息按声明顺序列出可用标识 + */ + public D level(String id) { + D level = levelsById.get(id); + if (level == null) throw new IllegalArgumentException("Unknown difficulty '" + id + "'. Available IDs " + levelsById.keySet()); + return level; + } + + /** + * 取得所选档位的值,供机器初始化或提示文本使用。 + * + * @param level 选中的难度档位 + * @return 建表时为该档位提供的值 + * @throws IllegalArgumentException 建表时未声明该档位 + */ + public V value(D level) { + V value = valuesByLevel.get(level); + if (value == null) throw new IllegalArgumentException("Undeclared difficulty '" + level.getSerializedName() + "'"); + return value; + } +} diff --git a/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt b/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt index cf573b9..a00e635 100644 --- a/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt +++ b/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt @@ -3,8 +3,8 @@ package com.modularmc.registrate.export import com.modularmc.registrate.AbstractRegistrate import com.modularmc.registrate.localization.export.LocalizationExportBuilder -/** Starts export builders for the data produced by one Registrate instance. */ +/** 提供当前 Registrate 实例的数据导出入口。 */ class RegistrateExportBuilder internal constructor(private val registrate: AbstractRegistrate<*>) { - /** Configures localization exchange output for the owning mod. */ + /** 配置所属模组的本地化交换文件。 */ fun localization(): LocalizationExportBuilder = LocalizationExportBuilder(registrate) } diff --git a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt index 6139f53..46e28b2 100644 --- a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt +++ b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt @@ -22,6 +22,7 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.Optional import java.util.function.BiConsumer +/** 在同一模组内按注册表暂存条目,管理绑定阶段、条目元数据和注册回调。 */ class RegistrationTracker(private val modId: String) { private enum class Stage(val description: String) { CREATION("creation"), @@ -70,6 +71,12 @@ class RegistrationTracker(private val modId: String) { private val afterRegisterCallbacks = HashMultimap.create>, Runnable>() private val completedRegistrations = ObjectOpenHashSet>>() + /** + * 在普通优先级处理当前注册表,按提交顺序创建、写入并绑定条目。 + * @param event 当前注册表的注册事件 + * @param skipErrors 条目注册失败时是否记录异常后继续处理下一项 + * @param devEnvironment 开发环境下发现未使用的条目回调时立即抛出异常 + */ fun onRegister(event: RegisterEvent, skipErrors: Boolean, devEnvironment: Boolean) { val registry = event.registryKey if (!pendingEntryCallbacks.isEmpty) { @@ -99,12 +106,23 @@ class RegistrationTracker(private val modId: String) { } } + /** 在最低优先级标记注册表完成,并执行等待此注册表的回调。 */ fun onRegisterLate(event: RegisterEvent) { val registry = event.registryKey completedRegistrations.add(registry) for (callback in afterRegisterCallbacks.removeAll(registry)) callback.run() } + /** + * 暂存同名条目的对象工厂、引用和元数据。返回的引用要等注册事件触发后才绑定。 + * @param name 当前模组命名空间下的条目名称 + * @param registry 目标注册表 + * @param creator 写入注册表时调用的对象工厂 + * @param entryFactory 用延迟引用构造条目包装对象的工厂 + * @param metadata 随条目保存的数据生成回调和本地化声明 + * @return 尚未绑定的条目引用 + * @throws IllegalArgumentException 同一注册表已存在同名条目 + */ fun track( name: String, registry: ResourceKey>, @@ -127,8 +145,10 @@ class RegistrationTracker(private val modId: String) { return registration.delegate } + /** 查询指定注册键的元数据,未提交该条目时抛出 [IllegalArgumentException]。 */ fun getMetadata(key: ResourceKey<*>): EntryMetadata = registration(key.identifier().path, key.registryKey()).metadata + /** 在调用线程上逐一处理已声明本地化的条目,向回调传入条目引用和声明。 */ fun forEachLocalization(action: BiConsumer, EntryLocalization>) { for (row in registrations.values) { for (registration in row.values) { @@ -138,6 +158,7 @@ class RegistrationTracker(private val modId: String) { } } + /** 添加在条目注册时执行的回调。条目尚未提交时先按注册表和名称暂存。 */ fun addRegisterCallback(name: String, registry: ResourceKey>, callback: NonNullConsumer) { val entry = findRegistration(name, registry) if (entry == null) { @@ -147,17 +168,22 @@ class RegistrationTracker(private val modId: String) { } } + /** 暂存注册表完成后运行的回调。应在该注册表的注册完成事件之前调用。 */ fun addAfterRegisterCallback(registry: ResourceKey>, callback: Runnable) { afterRegisterCallbacks.put(registry, callback) } + /** 判断指定注册表是否已进入注册完成阶段。 */ fun isRegistered(registry: ResourceKey>): Boolean = registry in completedRegistrations + /** 按注册表和名称查找已提交条目的引用。缺少该条目时抛出 [IllegalArgumentException]。 */ @Suppress("UNCHECKED_CAST") fun get(name: String, registry: ResourceKey>): RegistryEntry = registration(name, registry).delegate as RegistryEntry + /** 按注册表和名称查找条目引用,没有对应条目时返回空值。 */ fun getOptional(name: String, registry: ResourceKey>): Optional> = Optional.ofNullable(findRegistration(name, registry)?.delegate) + /** 收集当前模组提交到指定注册表的引用,保留提交顺序。 */ @Suppress("UNCHECKED_CAST") fun getAll(registry: ResourceKey>): Collection> = registrations[registry]?.values?.map { it.delegate as RegistryEntry } ?: emptyList() diff --git a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt index f740dc8..bd67208 100644 --- a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt +++ b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt @@ -14,9 +14,11 @@ import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer +/** 将模组事件监听器限制为一次执行,并将注销安排到允许修改监听器的阶段。 */ class OneTimeEventReceiver(private val bus: IEventBus, private val listener: Consumer) : Consumer { private val consumed = AtomicBoolean() + /** 首次收到事件时调用监听器,成功返回后将自身加入注销队列。 */ override fun accept(event: T) { if (consumed.compareAndSet(false, true)) { listener.accept(event) @@ -29,11 +31,19 @@ class OneTimeEventReceiver(private val bus: IEventBus, private val li private val waitingModListeners = Reference2ObjectOpenHashMap, MutableList>>() private val toUnregister = ArrayList() + /** 以普通优先级订阅单次模组事件。实例尚未绑定事件总线时暂存监听器。 */ @JvmStatic fun addModListener(owner: AbstractRegistrate<*>, eventClass: Class, listener: Consumer) where T : Event, T : IModBusEvent { addModListener(owner, EventPriority.NORMAL, eventClass, listener) } + /** + * 以指定优先级订阅单次模组事件。已暂存的监听器在首次使用所属实例的总线时一起挂接。 + * @param owner 事件监听器所属的 Registrate 实例 + * @param priority 监听器执行优先级 + * @param eventClass 接收的模组事件类型 + * @param listener 首次收到事件时执行的回调 + */ @JvmStatic fun addModListener(owner: AbstractRegistrate<*>, priority: EventPriority, eventClass: Class, listener: Consumer) where T : Event, T : IModBusEvent { val bus = owner.modEventBus @@ -49,6 +59,7 @@ class OneTimeEventReceiver(private val bus: IEventBus, private val li addListener(bus, priority, eventClass, listener) } + /** 在模组加载完成时注销监听器。所属实例需已绑定事件总线,[event] 为保留的事件类型参数。 */ @JvmStatic @Suppress("UNUSED_PARAMETER") fun unregister(owner: AbstractRegistrate<*>, listener: Any, event: Class) { diff --git a/src/main/java/com/modularmc/registrate/internal/event/package-info.java b/src/main/java/com/modularmc/registrate/internal/event/package-info.java index be778bf..ea56a0f 100644 --- a/src/main/java/com/modularmc/registrate/internal/event/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/event/package-info.java @@ -1,6 +1,5 @@ /** - * Event-bus plumbing that supports one-shot registration hooks for the public - * Registrate DSL. + * 为 Registrate 注册接口提供一次性事件监听。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal.event; diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt index d24d764..223f6d0 100644 --- a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt @@ -12,25 +12,33 @@ import net.neoforged.neoforge.registries.RegisterEvent import java.util.function.Consumer -/** Attaches the registration and DataGen listeners for one Registrate. */ +/** 把单个 Registrate 实例的注册和数据生成回调接入模组事件总线。 */ class RegistrateLifecycle(private val owner: AbstractRegistrate<*>, private val hooks: Hooks) { - /** Callbacks bound to their owning Registrate before NeoForge posts lifecycle events. */ + /** 定义注册、创造模式物品栏和数据生成回调。NeoForge 派发事件前,所属 Registrate 会把这些回调接入模组事件总线。 */ interface Hooks { + /** 返回绑定的模组事件总线,尚未绑定时返回 `null`。 */ fun modEventBus(): IEventBus? + /** 保存注册期间使用的模组事件总线。 */ fun setModEventBus(bus: IEventBus) + /** 返回当前启动是否正在运行数据生成,用于决定是否订阅收集数据事件。 */ fun doDatagen(): Boolean + /** 在普通优先级接收注册事件,处理当前注册表的条目。 */ fun onRegister(event: RegisterEvent) + /** 在最低优先级接收注册事件,执行等待当前注册表写入结束的操作。 */ fun onRegisterLate(event: RegisterEvent) + /** 接收创造模式标签页填充事件,为对应的标签页追加内容。 */ fun onBuildCreativeModeTabContents(event: BuildCreativeModeTabContentsEvent) + /** 接收数据收集事件,为本轮生成登记所需的提供器。 */ fun onData(event: GatherDataEvent) } + /** 在模组初始化期间挂接注册、创造模式标签页和数据生成所需的监听器。注册监听器会在公共初始化阶段排队移除。 */ fun register(bus: IEventBus) { if (hooks.modEventBus() == null) { hooks.setModEventBus(bus) diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java b/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java index 6a752dd..db7b95b 100644 --- a/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java @@ -1,6 +1,5 @@ /** - * Per-instance lifecycle bridges that attach Registrate owners to the NeoForge - * mod bus. + * 将各个 Registrate 实例接入 NeoForge 模组事件总线。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal.lifecycle; diff --git a/src/main/java/com/modularmc/registrate/internal/package-info.java b/src/main/java/com/modularmc/registrate/internal/package-info.java index 97ad00b..40be79b 100644 --- a/src/main/java/com/modularmc/registrate/internal/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/package-info.java @@ -1,9 +1,8 @@ /** - * Internal implementation details that back the public Registrate API. + * 存放 Registrate 公共接口使用的内部实现。 * *

- * Types in this package are free to change during development and should not - * be treated as stable extension points for downstream mods. + * 此处的类型会随库的实现调整,下游模组应通过公共接口接入。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal; diff --git a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt index c40146b..b3ee010 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt +++ b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt @@ -3,6 +3,7 @@ package com.modularmc.registrate.internal.util import org.apache.logging.log4j.Marker import org.apache.logging.log4j.MarkerManager +/** 提供注册和数据生成日志的分类标记,便于在开发环境中按阶段筛选。 */ object DebugMarkers { private const val PREFIX = "REGISTRATE." diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt index 703b045..f783b01 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt @@ -5,7 +5,9 @@ import net.neoforged.fml.loading.FMLEnvironment import java.util.function.Supplier +/** 根据 NeoForge 的物理侧执行延迟任务,供客户端类的初始化入口使用。 */ object RegistrateDistExecutor { + /** 当前物理侧与 [dist] 匹配时,才获取 [toRun] 并在调用线程执行。客户端任务的类引用应放在取值器内部。 */ @JvmStatic fun unsafeRunWhenOn(dist: Dist, toRun: Supplier) { if (dist == FMLEnvironment.getDist()) { diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt index 940e512..9f60231 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt @@ -5,24 +5,30 @@ import com.modularmc.registrate.RegistrateLib import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger +/** 集中提供 Registrate 各阶段的日志器和带模组标识的消息格式。 */ object RegistrateLogger { private val ROOT = RegistrateLib.LOGGER private val CORE = child("Core") private val DATAGEN = child("Datagen") private val REGISTRATION = child("Registration") + /** 返回本库使用的根日志器。 */ @JvmStatic fun root(): Logger = ROOT + /** 返回用于记录 Registrate 初始化和公共流程的日志器。 */ @JvmStatic fun core(): Logger = CORE + /** 返回用于记录数据生成及本地化解析的日志器。 */ @JvmStatic fun datagen(): Logger = DATAGEN + /** 返回用于记录注册提交、绑定及回调的日志器。 */ @JvmStatic fun registration(): Logger = REGISTRATION + /** 为日志消息加上模组标识占位符。调用记录方法时须将模组标识作为第一个格式化参数。 */ @JvmStatic fun modMessage(message: String): String = "[{}] $message" diff --git a/src/main/java/com/modularmc/registrate/internal/util/package-info.java b/src/main/java/com/modularmc/registrate/internal/util/package-info.java index 9def3cb..b895615 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/util/package-info.java @@ -1,5 +1,5 @@ /** - * Small implementation-only helpers used by runtime internals. + * 存放注册流程在运行时使用的内部工具。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal.util; diff --git a/src/main/java/com/modularmc/registrate/localization/ComponentTemplate.kt b/src/main/java/com/modularmc/registrate/localization/ComponentTemplate.kt new file mode 100644 index 0000000..1a965d5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/ComponentTemplate.kt @@ -0,0 +1,39 @@ +package com.modularmc.registrate.localization + +import net.minecraft.network.chat.Component +import net.minecraft.network.chat.Style + +import it.unimi.dsi.fastutil.objects.ObjectArrayList + +/** + * 把翻译键和样式组成可复用的文本模板,供提示框等多行文本使用。 + * 模组初始化时通过 `addLocalization` 为每行的键声明译文,显示时通过 [build] 传入实际参数。 + * + * @param lines 按显示顺序排列的文本行 + */ +class ComponentTemplate(vararg lines: Line) { + /** + * 模板中的一行,正文和说明都可以使用。 + * + * @param key 该行使用的翻译键 + * @param style 应用在该行组件上的样式 + */ + @JvmRecord + data class Line(val key: TranslationKey, val style: Style) + + private val lines = lines.copyOf() + + /** + * 为一次显示创建新的组件列表。每行可以用 `%1$s`、`%2$s` 等占位符引用同一组参数。 + * + * @param args 传给各行翻译组件的参数 + * @return 按声明顺序排列的组件列表 + */ + fun build(vararg args: Any): List { + val components = ObjectArrayList(lines.size) + for (line in lines) { + components.add(Component.translatable(line.key.value, *args).setStyle(line.style)) + } + return components + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt b/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt index 094df26..5afd6ce 100644 --- a/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt +++ b/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt @@ -7,7 +7,7 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap import it.unimi.dsi.fastutil.objects.ObjectArrayList import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet -/** Reusable domain, text type and glossary defaults for a localization declaration. */ +/** 供本地化声明复用的默认领域、文本类型、术语和单位。 */ @JvmRecord data class DeclarationDefaults @JvmOverloads constructor( val domains: List, @@ -16,18 +16,25 @@ data class DeclarationDefaults @JvmOverloads constructor( val glossaryIds: List = emptyList(), val unitIds: List = emptyList(), ) { - /** Combines existing defaults so that included values take precedence over inherited defaults. */ + /** + * 按字段合并默认值。显式引入的条目优先,其次使用继承值,最后使用基础默认值。 + * 多个引入项的文本类型或同标识术语发生冲突时,构建会抛出异常。 + */ class Builder { private var defaults = EMPTY private var parent = EMPTY private val included = ObjectArrayList() + /** 设置基础默认值。仅在引入项和继承项未提供某字段时使用。 */ fun defaults(defaults: DeclarationDefaults) = apply { this.defaults = defaults } + /** 设置继承来源。字段没有被引入项提供时,先使用继承值再回退到基础默认值。 */ fun inherits(parent: DeclarationDefaults) = apply { this.parent = parent } + /** 引入一组优先级较高的默认值。多次调用会累加引入项。 */ fun include(vararg defaults: DeclarationDefaults) = apply { included.addAll(defaults.asList()) } + /** 合并当前配置的默认值。同标识术语或引入的文本类型发生冲突时抛出 [IllegalArgumentException]。 */ fun build(): DeclarationDefaults { val domains = ObjectLinkedOpenHashSet() val glossary = Object2ObjectLinkedOpenHashMap() diff --git a/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt b/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt index e73537e..49b8f99 100644 --- a/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt +++ b/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt @@ -3,6 +3,6 @@ package com.modularmc.registrate.localization import com.modularmc.registrate.localization.TranslationSource.Kind import com.modularmc.registrate.util.nullness.NonNullSupplier -/** A builder declaration whose key is obtained from the bound Minecraft object during DataGen. */ +/** 构建器保存的本地化声明。数据生成时从已绑定的游戏对象读取翻译键。 */ @JvmRecord data class EntryLocalization(val key: NonNullSupplier, val declaration: NonNullSupplier, val kind: Kind) diff --git a/src/main/java/com/modularmc/registrate/localization/ImportedTranslation.kt b/src/main/java/com/modularmc/registrate/localization/ImportedTranslation.kt index 3baaff6..b0e364b 100644 --- a/src/main/java/com/modularmc/registrate/localization/ImportedTranslation.kt +++ b/src/main/java/com/modularmc/registrate/localization/ImportedTranslation.kt @@ -4,20 +4,20 @@ import java.nio.charset.StandardCharsets import java.security.MessageDigest import java.util.HexFormat -/** Identifies the source text against which a translation was reviewed. */ +/** 标识译文审校时对应的源文版本,用于判断源文是否已变更。 */ @JvmRecord data class SourceRevision(val value: String) { companion object { private val digest = ThreadLocal.withInitial { MessageDigest.getInstance("SHA-256") } private val hex = HexFormat.of() - /** Computes the SHA-256 of the UTF-8 source text. */ + /** 按 UTF-8 编码计算源文的 SHA-256 摘要。 */ @JvmStatic fun of(source: String): SourceRevision = SourceRevision(hex.formatHex(digest.get().digest(source.toByteArray(StandardCharsets.UTF_8)))) } } -/** Review state attached to a translation imported from another source. */ +/** 记录外部译文的审校状态,供数据生成时比较导入译文的优先级。 */ enum class TranslationStatus(private val priority: Int) { STALE(0), DRAFT(1), @@ -28,7 +28,7 @@ enum class TranslationStatus(private val priority: Int) { internal fun priority(locked: Boolean): Int = priority + if (locked) entries.size else 0 } -/** A translation received from another source. [location] identifies its origin in DataGen diagnostics. */ +/** 从外部导入的译文。[location] 记录来源,供数据生成时定位问题。 */ @JvmRecord data class ImportedTranslation( val key: TranslationKey, diff --git a/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt index 9757692..777f318 100644 --- a/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt +++ b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt @@ -5,7 +5,7 @@ import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTer import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap -/** A source declaration and its explicit translations, resolved against the owning mod's source locale. */ +/** 声明源文及显式提供的译文。数据生成时以所属模组的源语言解释源文。 */ @JvmRecord data class LocalizationDeclaration @JvmOverloads constructor( val source: String, @@ -16,6 +16,7 @@ data class LocalizationDeclaration @JvmOverloads constructor( val glossaryIds: List = emptyList(), val unitIds: List = emptyList(), ) { + /** 为单条本地化声明收集源文、译文及可选的术语信息。构建前须设置源文。 */ class Builder { private lateinit var source: String private var translations: Object2ObjectOpenHashMap? = null @@ -26,33 +27,43 @@ data class LocalizationDeclaration @JvmOverloads constructor( private var unitIds: List? = null private var defaults = DeclarationDefaults.EMPTY + /** 设置源语言文本,其中的占位符应和各译文对应。 */ fun source(source: String) = apply { this.source = source } + /** 设置声明专用文本类型。传入 `null` 时沿用构建时可用的默认类型。 */ fun type(type: TextType?) = apply { this.type = type } + /** 设置声明级默认值。显式字段优先,缺失字段可以回退到模组默认值。 */ fun defaults(defaults: DeclarationDefaults) = apply { this.defaults = defaults } + /** 设置指定语言的显式译文。同一语言重复设置时采用最后一次的内容。 */ fun translation(locale: MinecraftLocale, text: String) = apply { val texts = translations ?: Object2ObjectOpenHashMap(2).also { translations = it } texts[locale] = text } + /** 设置声明的领域列表。传入零个领域会清除继承的领域。 */ fun domain(vararg domains: Domain) = apply { this.domains = domains.toList() } + /** 直接指定声明使用的术语,并替换此前指定的术语标识。 */ fun glossary(vararg terms: GlossaryTerm) = apply { glossary = terms.asList() glossaryIds = emptyList() } + /** 按稳定标识引用已登记的术语,替换此前直接指定的术语。 */ fun glossaryIds(vararg ids: String) = apply { glossary = emptyList() glossaryIds = ids.asList() } + /** 指定声明使用的单位标识。派生译文时可以保留这些单位的符号。 */ fun units(vararg ids: String) = apply { unitIds = ids.asList() } + /** 仅使用此构建器的配置和默认值创建声明。尚未调用 [source] 时抛出 [UninitializedPropertyAccessException]。 */ fun build(): LocalizationDeclaration = build(DeclarationDefaults.EMPTY) + /** 创建声明,并按显式设置、声明默认值、模组默认值的顺序取各字段。尚未设置源文时抛出 [UninitializedPropertyAccessException]。 */ fun build(moduleDefaults: DeclarationDefaults): LocalizationDeclaration { val entryGlossary = if (defaults.glossary.isEmpty() && defaults.glossaryIds.isEmpty()) moduleDefaults else defaults return LocalizationDeclaration( @@ -68,9 +79,11 @@ data class LocalizationDeclaration @JvmOverloads constructor( } companion object { + /** 创建仅含源文的声明,供没有单独配置译文、术语或单位的条目使用。 */ @JvmStatic fun sourceText(source: String) = LocalizationDeclaration(source, emptyMap(), emptyList(), null, emptyList()) + /** 用源文和指定的默认元数据创建声明。目标语言可在数据生成期间由导入或派生规则提供。 */ @JvmStatic fun sourceText(source: String, defaults: DeclarationDefaults) = LocalizationDeclaration(source, emptyMap(), defaults.domains, defaults.type, defaults.glossary, defaults.glossaryIds, defaults.unitIds) diff --git a/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt b/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt index d3c18ef..0f75396 100644 --- a/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt +++ b/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization -/** Languages shipped with Minecraft 1.21.1. */ +/** Minecraft 提供的语言选项。 */ enum class MinecraftLocale { AF_ZA, AR_SA, @@ -143,5 +143,6 @@ enum class MinecraftLocale { private val code = name.lowercase() + /** 返回形如 `zh_cn` 的语言文件代码。 */ fun code(): String = code } diff --git a/src/main/java/com/modularmc/registrate/localization/TextType.kt b/src/main/java/com/modularmc/registrate/localization/TextType.kt index 4d61e84..0a1b57b 100644 --- a/src/main/java/com/modularmc/registrate/localization/TextType.kt +++ b/src/main/java/com/modularmc/registrate/localization/TextType.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization -/** A stable, extensible role for text in a mod. */ +/** 标识文本在模组中的用途,模组可以定义自己的类型。 */ @JvmRecord data class TextType(val id: String) { companion object { diff --git a/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt b/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt index 4b5ab9d..9c95490 100644 --- a/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt +++ b/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt @@ -1,5 +1,5 @@ package com.modularmc.registrate.localization -/** The literal Minecraft translation key and the namespace of the language file that owns it. */ +/** 由 Minecraft 使用的原始翻译键和负责输出它的语言文件命名空间组成。 */ @JvmRecord data class TranslationKey(val namespace: String, val value: String) diff --git a/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt b/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt index 07271f3..7f7ee43 100644 --- a/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt +++ b/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt @@ -1,8 +1,9 @@ package com.modularmc.registrate.localization -/** Identifies a translation's priority and the declaration that supplied it. */ +/** 记录译文的来源声明及其优先级,供数据生成时选择译文。 */ @JvmRecord data class TranslationSource(val kind: Kind, val location: String) { + /** 区分译文来源。数据生成时将来源优先级用于比较同一个键和语言的候选文本。 */ enum class Kind(internal val priority: Int) { FALLBACK(0), VARIANT(1), diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt b/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt index e19dd93..ef64b95 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt @@ -17,7 +17,7 @@ import org.objectweb.asm.Type import java.lang.annotation.ElementType import java.util.EnumMap -/** Reads declarations from the owning mod file's NeoForge scan data during DataGen. */ +/** 数据生成时从所属模组文件的 NeoForge 扫描结果中读取本地化声明。 */ internal object AnnotatedTranslations { private val trans = Type.getType(Trans::class.java) private val transVariants = Type.getType(TransVariants::class.java) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt index f2eabfe..50d84cb 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** Adds one translation key. [modId] may be omitted when the file declares a single mod. */ +/** 声明一个翻译键。模组文件只声明一个模组时,可以省略 [modId]。 */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) annotation class Trans(val modId: String = "", val key: String, val source: String, val namespace: String = "", val translations: Array = []) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt index cf8d6a9..821a104 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** Adds a translation for each variant. [modId] may be omitted when the file declares a single mod. */ +/** 为每个变体声明翻译键。模组文件只声明一个模组时,可以省略 [modId]。 */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) annotation class TransVariants(val modId: String = "", val keyPrefix: String, val value: Array, val namespace: String = "") diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt index 6ac0d1f..c77aff9 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt @@ -2,7 +2,7 @@ package com.modularmc.registrate.localization.annotation import com.modularmc.registrate.localization.MinecraftLocale -/** Explicit target text supplied by an annotated declaration. */ +/** 为注解声明提供指定语言的译文。 */ @Retention(AnnotationRetention.BINARY) @Target() annotation class Translation(val locale: MinecraftLocale, val text: String) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt index 38fa23e..9dff07e 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** One entry of a variant group, appended to the group's key prefix. */ +/** 变体组中的一条声明。该变体的键后缀接到组的公共前缀后。 */ @Retention(AnnotationRetention.BINARY) @Target() annotation class Variant(val id: String, val source: String, val translations: Array = []) diff --git a/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt index c472e22..347b0a5 100644 --- a/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt +++ b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt @@ -4,17 +4,21 @@ import com.modularmc.registrate.AbstractRegistrate import java.nio.file.Path -/** Requests a per-mod localization exchange document during DataGen. */ +/** 为所属模组配置数据生成时导出的本地化交换文件。 */ class LocalizationExportBuilder internal constructor(private val registrate: AbstractRegistrate<*>) { private var outputPath: Path? = null - /** Sets the exact JSON file path used for this mod's export. */ + /** 设置导出 JSON 的完整文件路径。相对路径以当前进程的工作目录为基准。 */ fun path(path: Path): LocalizationExportBuilder { outputPath = path.toAbsolutePath().normalize() return this } - /** Registers localization export after the owning mod's language declarations have been collected. */ + /** + * 登记本地化导出任务,由数据生成流程在收集所属模组的语言声明后写出文件。 + * + * @throws IllegalArgumentException 尚未设置输出路径 + */ fun build() { registrate.requestLocalizationExport(requireNotNull(outputPath) { "Set the localization export path before build" }) } diff --git a/src/main/java/com/modularmc/registrate/localization/locale/LocaleConverter.kt b/src/main/java/com/modularmc/registrate/localization/locale/LocaleConverter.kt index 81f0de3..3e9af41 100644 --- a/src/main/java/com/modularmc/registrate/localization/locale/LocaleConverter.kt +++ b/src/main/java/com/modularmc/registrate/localization/locale/LocaleConverter.kt @@ -5,13 +5,20 @@ import com.modularmc.registrate.localization.MinecraftLocale import com.modularmc.registrate.localization.TranslationKey /** - * Transforms plain text runs for a configured locale conversion during DataGen. - * The same converter may be called for several runs of one translation. Keep it deterministic. + * 供数据生成流程在派生目标语言时转换纯文本片段。 + * 同一条译文可能分多次调用转换器,结果应只取决于输入和转换上下文。 */ fun interface LocaleConverter { - /** Receives the plain run and its source, target and declaration context. Returns the converted run. */ + /** + * 转换一个纯文本片段。 + * + * @param text 待转换的文本片段 + * @param context 包含源语言、目标语言和声明信息的上下文 + * @return 转换后的文本片段 + */ fun convert(text: String, context: Context): String + /** 传给转换器的声明上下文,包含翻译键、输入和输出语言以及完整的本地化声明。 */ @JvmRecord data class Context(val key: TranslationKey, val input: MinecraftLocale, val output: MinecraftLocale, val declaration: LocalizationDeclaration) } diff --git a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt index bea8ca9..d54f7b2 100644 --- a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt +++ b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt @@ -11,13 +11,14 @@ import com.modularmc.registrate.localization.TranslationKey import com.modularmc.registrate.localization.TranslationSource.Kind import com.modularmc.registrate.localization.resolution.MinecraftTextFormat -/** Defines how DataGen derives a missing target from text resolved for the input locale. */ +/** 定义目标语言缺少译文时的派生规则。数据生成流程以输入语言已解析的文本为基础。 */ class LocaleDerivation private constructor( val input: MinecraftLocale, val output: MinecraftLocale, internal val kind: Kind, private val transform: (String, Collection, TranslationKey, LocalizationDeclaration) -> String, ) { + /** 创建纯文本转换规则。转换器会逐段执行,格式控制、占位符和单位符号由本地化流程保留。 */ constructor(input: MinecraftLocale, output: MinecraftLocale, converter: LocaleConverter) : this( input, output, @@ -35,7 +36,7 @@ class LocaleDerivation private constructor( internal val BRITISH_ENGLISH = LocaleDerivation(EN_US, EN_GB) { text, _ -> BritishEnglish.convert(text) } internal val TRADITIONAL_CHINESE = LocaleDerivation(ZH_CN, ZH_TW) { text, _ -> TraditionalChinese.convert(text) } - /** Copies the resolved input as a display fallback for a missing target. */ + /** 为目标语言配置显示回退规则。缺少译文时直接使用输入语言已解析的文本。 */ @JvmStatic fun fallback(input: MinecraftLocale, output: MinecraftLocale): LocaleDerivation = LocaleDerivation(input, output, Kind.FALLBACK) { text, _, _, _ -> text } } diff --git a/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt b/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt index 7421ead..d5f190a 100644 --- a/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt +++ b/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt @@ -25,6 +25,7 @@ internal object MinecraftTextFormat { private data class Token(val start: Int, val end: Int, val argument: Int) + /** 统计可识别的格式占位符及其次数,用于比较源文和译文引用的参数是否一致。 */ fun signature(text: String): Int2IntMap { val firstPercent = text.indexOf('%') if (firstPercent < 0) return Int2IntMaps.EMPTY_MAP @@ -48,6 +49,7 @@ internal object MinecraftTextFormat { return signature } + /** 逐段转换纯文本,保留 Minecraft 格式码、占位符及 [symbols] 指定的单位符号。 */ fun convert(text: String, symbols: Collection, convertRun: (String) -> String): String { val matcher = tokenPattern(symbols).matcher(text) if (!matcher.find()) return convertRun(text) @@ -63,6 +65,7 @@ internal object MinecraftTextFormat { return result.toString() } + /** 将可见文字变为倒置文本,同时尽量保持样式边界和不可拆分的格式标记。 */ fun upsideDown(text: String, symbols: Collection): String { val result = StringBuilder(text.length) val matcher = tokenPattern(symbols).matcher(text) @@ -76,7 +79,7 @@ internal object MinecraftTextFormat { var nextArgument = 1 do { if (matcher.start(2) >= 0) { - // Line separators and style changes delimit runs so they stay attached to the same text. + // 换行和样式切换会断开文本片段,反转时让样式留在原来的文本上。 reverseRun(text, start, matcher.start(), tokens, result) result.append(text, matcher.start(), matcher.end()) tokens.clear() diff --git a/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt index b81e3ce..e206fd7 100644 --- a/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt +++ b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt @@ -27,7 +27,7 @@ import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap import java.util.TreeMap import java.util.function.Consumer -/** Resolves the declarations for one DataGen output before the language provider writes any files. */ +/** 在语言文件写出前,为同一份数据生成输出解析本地化声明。 */ internal class TranslationRegistry(private val parent: TranslationRegistry? = null) { private val selections = Object2ObjectLinkedOpenHashMap() private val imports = ObjectArrayList() @@ -153,7 +153,7 @@ internal class TranslationRegistry(private val parent: TranslationRegistry? = nu return Selection(key, candidate).also { put(key, it) } } - /** Resolves language entries and, when requested, reports each matched import with its current status. */ + /** 解析各语言文件的条目。提供 [reportImport] 时,同时报告匹配到的外部译文及其当前状态。 */ @JvmOverloads fun resolve(reportImport: Consumer? = null): Map> = resolveAll(reportImport).files diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt index 0d81355..63155f7 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.terminology -/** A stable, extensible field used to associate terms and localization declarations. */ +/** 通过稳定标识关联术语和本地化声明。模组可以定义自己的领域。 */ @JvmRecord data class Domain(val id: String) { companion object { diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt index 6743c5e..27c051e 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt @@ -4,23 +4,34 @@ import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTer import com.modularmc.registrate.localization.terminology.Terminology.TermRelation /** - * Supplies terminology to a mod's [Terminology] from any storage format. - * Register a glossary during mod setup and keep its lookups stable throughout DataGen. - * Term IDs identify a single definition across the mod's glossaries. + * 向模组的 [Terminology] 提供术语查询,可由不同形式的存储实现。 + * 在模组初始化时注册,数据生成期间应保持查询结果稳定。 + * 同一模组的各词汇表共用术语标识,一个标识只能对应一条定义。 */ interface Glossary { - /** Looks up a term by its stable ID. Returns null when the glossary has no such term. */ + /** + * 按稳定标识查询术语。 + * + * @param id 查询的术语标识 + * @return 对应的术语,当前词汇表没有该术语时返回 `null` + */ fun find(id: String): GlossaryTerm? /** - * Finds all senses of a complete source label or alias, including those with different domains or text types. - * The query uses locale-independent lowercase. An unmatched label returns an empty iterable. + * 按完整的源语言词条或别名查询,保留不同领域和文本类型下的各个词义。 + * + * @param normalizedSource 按与语言区域无关的规则转为小写的查询词 + * @return 匹配的术语,没有匹配项时返回空集合 */ fun findBySource(normalizedSource: String): Iterable /** - * Returns terms directly related to the supplied term. `SYNONYM` results include both incoming and outgoing links. - * Implementations own the relation data and keep lookups stable throughout DataGen. + * 查询指定关系直接关联的术语。查询同义关系时同时返回正向和反向关联。 + * 关系数据由实现类提供,数据生成期间应保持查询结果稳定。 + * + * @param id 待查询的术语标识 + * @param relation 要匹配的关系类型 + * @return 与该术语直接关联的术语 */ fun findRelated(id: String, relation: TermRelation): Iterable } diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt index 6b20f65..cabcce9 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt @@ -12,8 +12,9 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.Optional -/** Terminology defined by one mod. Register it during mod setup and query it alongside declarations. */ +/** 保存单个模组定义的术语。模组初始化时注册,解析本地化声明时查询。 */ class Terminology { + /** 带有独立标识的一个术语义项。领域和文本类型用于消除歧义,译文、别名和关系供查询与数据生成使用。 */ @JvmRecord data class GlossaryTerm @JvmOverloads constructor( val id: String, @@ -30,6 +31,7 @@ class Terminology { internal fun matches(sourceText: String): Boolean = source.equals(sourceText, ignoreCase = true) || aliases.any { it.equals(sourceText, ignoreCase = true) } } + /** 定义术语之间的同义、上下位、组成部分和一般关联。 */ enum class TermRelation { SYNONYM, BROADER, @@ -39,8 +41,10 @@ class Terminology { RELATED, } + /** 记录一个单位的稳定标识、显示符号及分语言的名称和格式。 */ @JvmRecord data class MeasurementUnit @JvmOverloads constructor(val id: String, val symbol: String, val names: Map, val formats: Map = emptyMap()) { + /** 按目标语言的注册格式显示数值和单位。缺少该语言的格式时,用一个空格连接数值与符号。 */ fun format(value: Number, locale: MinecraftLocale): String = formats[locale]?.format(value, symbol) ?: "$value $symbol" } @@ -49,22 +53,27 @@ class Terminology { private val glossaries = ObjectArrayList(1).apply { add(indexedGlossary) } private val units = Object2ObjectOpenHashMap() + /** 登记供本地化声明引用的领域。 */ fun register(domain: Domain) { domains.add(domain) } + /** 将术语存入模组自带的词汇表。已有同标识术语时,同时替换旧的词形和关系索引。 */ fun register(term: GlossaryTerm) { indexedGlossary.register(term) } + /** 挂接外部词汇表。数据生成期间会用它查询术语、别名和关系。 */ fun register(glossary: Glossary) { glossaries.add(glossary) } + /** 按稳定标识登记单位。同一标识再次登记时采用新定义。 */ fun register(unit: MeasurementUnit) { units[unit.id] = unit } + /** 检查领域是否已在当前模组登记。 */ fun hasDomain(domain: Domain): Boolean = domains.contains(domain) internal fun synonyms(term: GlossaryTerm): ObjectArrayList { @@ -89,8 +98,10 @@ class Terminology { return result } + /** 按稳定标识查询术语,没有匹配的定义时返回空值。 */ fun glossary(id: String): Optional = Optional.ofNullable(findTerm(id)) + /** 按稳定标识查找显示单位,没有匹配的定义时返回空值。 */ fun unit(id: String): Optional = Optional.ofNullable(units[id]) internal fun unitSymbol(id: String): String = units.getValue(id).symbol diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/UnitFormat.kt b/src/main/java/com/modularmc/registrate/localization/terminology/UnitFormat.kt index a2b115a..535681a 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/UnitFormat.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/UnitFormat.kt @@ -4,9 +4,10 @@ import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.Locale -/** Formats a number followed by the registered unit symbol. The pattern uses DecimalFormat syntax. */ +/** 按 `DecimalFormat` 格式化数值,并在数值后拼接已登记的单位符号。 */ @JvmRecord data class UnitFormat(val numberPattern: String, val decimalSeparator: Char, val spacing: String) { + /** 使用当前小数分隔符和数字格式生成数值,再拼接设置的间距及 [symbol]。 */ fun format(value: Number, symbol: String): String { val symbols = DecimalFormatSymbols.getInstance(Locale.ROOT).apply { decimalSeparator = this@UnitFormat.decimalSeparator } return DecimalFormat(numberPattern, symbols).format(value) + spacing + symbol diff --git a/src/main/java/com/modularmc/registrate/localization/text/ComponentUtils.kt b/src/main/java/com/modularmc/registrate/localization/text/ComponentUtils.kt new file mode 100644 index 0000000..668224f --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/text/ComponentUtils.kt @@ -0,0 +1,224 @@ +package com.modularmc.registrate.localization.text + +import com.modularmc.mmclutils.utils.ColorUtils +import com.modularmc.mmclutils.utils.NumberUtils + +import net.minecraft.ChatFormatting +import net.minecraft.network.chat.Component +import net.minecraft.network.chat.MutableComponent +import net.minecraft.network.chat.Style +import net.minecraft.network.chat.contents.PlainTextContents +import net.minecraft.util.Util +import net.minecraft.world.level.block.state.properties.Property + +import it.unimi.dsi.fastutil.objects.ObjectArrayList + +import java.util.function.UnaryOperator +import java.util.stream.Collector +import java.util.stream.Collectors + +/** 构造和组合原版文本组件,保留子组件的翻译键和样式。 */ +object ComponentUtils { + /** + * 将方块状态属性名与序列化后的值组成一行。布尔值为真时用绿色,为假时用红色。 + * + * @param property 要显示的方块状态属性 + * @param value 该属性的值 + * @return 包含属性名和属性值的组件 + */ + @JvmStatic + fun propertyText(property: Property<*>, value: Comparable<*>): MutableComponent { + val name = Component.literal(Util.getPropertyName(property, value)) + if (value is Boolean) name.withStyle(if (value) ChatFormatting.GREEN else ChatFormatting.RED) + return Component.literal(property.name).append(": ").append(name) + } + + /** 将长整数按紧凑数值格式封装为字面组件。 */ + @JvmStatic + fun numberText(value: Long): MutableComponent = Component.literal(NumberUtils.format(value)) + + /** 将浮点数按紧凑数值格式封装为字面组件,保留非有限值的标准文本。 */ + @JvmStatic + fun numberText(value: Double): MutableComponent = Component.literal(NumberUtils.format(value)) + + /** + * 用翻译键显示百分数,数值最多保留两位小数,百分号由译文提供。 + * + * @param translationKey 用于显示百分数的翻译键 + * @param percent 已按百分数表示的数值 + * @return 以格式化数值为参数的翻译组件 + */ + @JvmStatic + fun percentText(translationKey: String, percent: Double): MutableComponent = Component.translatable(translationKey, NumberUtils.formatTwoDecimals(percent)) + + /** 创建一个可继续追加的列表,首行为给定的字面文本。 */ + @JvmStatic + fun literalLine(text: String): MutableList = ObjectArrayList(1).apply { add(Component.literal(text)) } + + /** 将长整数的十进制文本放入单行可修改列表。 */ + @JvmStatic + fun literalLine(value: Long): MutableList = literalLine(value.toString()) + + /** 将浮点数的标准文本放入单行可修改列表。 */ + @JvmStatic + fun literalLine(value: Double): MutableList = literalLine(value.toString()) + + /** 按当前语言解析各行,用换行符拼接为纯文本。 */ + @JvmStatic + fun plainText(lines: Iterable): String = lines.joinToString("\n") { it.string } + + /** + * 从单行文本读取整数。空列表视为零。 + * + * @throws NumberFormatException 含多行、文本无法解析为整数或数值超出整数范围 + */ + @JvmStatic + fun parseInt(lines: List): Int = if (lines.isEmpty()) 0 else singleLineText(lines).toInt() + + /** + * 从单行文本读取浮点数。空列表视为零。 + * + * @throws NumberFormatException 含多行或文本无法解析为浮点数 + */ + @JvmStatic + fun parseDouble(lines: List): Double = if (lines.isEmpty()) 0.0 else singleLineText(lines).toDouble() + + private fun singleLineText(lines: List): String { + if (lines.size != 1) throw NumberFormatException("Expected a single numeric line") + return lines.first().string + } + + /** + * 将首行接到目标的末行,其余各行作为新行加入。目标为空时先创建首行。 + * + * @param target 就地更新的目标列表 + * @param lines 来自独立列表的待追加行 + */ + @JvmStatic + fun appendLines(target: MutableList, lines: List) { + val iterator = lines.iterator() + if (!iterator.hasNext()) return + + val lastLine = target.lastOrNull() ?: Component.empty().also { target.add(it) } + lastLine.append(iterator.next()) + while (iterator.hasNext()) target.add(Component.empty().append(iterator.next())) + } + + /** + * 将追加项接到目标组件上。两者都有自身内容或子组件时,在中间插入分隔符。 + * 追加项为空时直接返回目标组件。 + */ + @JvmStatic + fun appendSeparated(target: MutableComponent, addition: Component, separator: Component): MutableComponent { + if (!addition.hasContent()) return target + if (target.hasContent()) target.append(separator) + return target.append(addition) + } + + private fun Component.hasContent(): Boolean = contents !== PlainTextContents.EMPTY || siblings.isNotEmpty() + + /** 给列表条目加引号后生成预览。超过五项时保留首尾各两项,中间显示省略号。 */ + @JvmStatic + fun previewList(entries: List, entryStyle: Style): MutableComponent { + val preview = ObjectArrayList(minOf(entries.size, 5)) + if (entries.size <= 5) { + entries.mapTo(preview) { quoted(it, entryStyle) } + } else { + preview.add(quoted(entries.first(), entryStyle)) + preview.add(quoted(entries[1], entryStyle)) + preview.add(Component.literal("…")) + preview.add(quoted(entries[entries.lastIndex - 1], entryStyle)) + preview.add(quoted(entries.last(), entryStyle)) + } + return Component.literal("[").append(join(preview, Component.literal(", "))).append("]") + } + + private fun quoted(text: String, style: Style): MutableComponent = Component.literal("\"$text\"").setStyle(style) + + /** 按遍历顺序拼接组件,在相邻项之间插入分隔符,并保留各子组件的翻译键和样式。 */ + @JvmStatic + fun join(components: Iterable, separator: Component): MutableComponent { + val result = Component.empty() + val iterator = components.iterator() + if (iterator.hasNext()) result.append(iterator.next()) + while (iterator.hasNext()) result.append(separator).append(iterator.next()) + return result + } + + /** 创建与 [join] 一致的流收集器,按流的遍历顺序拼接组件。 */ + @JvmStatic + fun joining(separator: Component): Collector { + val parts = Collectors.toCollection { ObjectArrayList() } + return Collectors.collectingAndThen(parts) { join(it, separator) } + } + + /** + * 按游戏刻从色板中循环选色,返回只修改文本颜色的样式变换。 + * + * @param tick 调用方提供的当前游戏刻 + * @param ticksPerColor 每种颜色持续的游戏刻数,至少为一 + * @param colors 按使用顺序排列的色板,至少包含一种颜色 + */ + @JvmStatic + fun cyclingColor(tick: Long, ticksPerColor: Int, vararg colors: Int): UnaryOperator