diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d87b2d..726217f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1,2 @@ -# ChangeLog- no changes +# ChangeLog +- no changes diff --git a/README.md b/README.md index 7e09b55..5fb486d 100644 --- a/README.md +++ b/README.md @@ -1 +1,17 @@ -# ModularMCLib-Template \ No newline at end of file +# ModularMCLib Utils + +面向 Minecraft 26.1.2、NeoForge 26.1.2.126 与 Java 25 的通用工具库。模组标识为 `mmclutils`。 + +## 安装与构建 + +将发布的完整 JAR 放入客户端或专用服的 `mods` 目录。 + +在仓库根目录运行 Gradle Wrapper,产物位于 `build/libs/`。 + +```powershell +.\gradlew.bat build +``` + +## 许可 + +本项目采用 GNU AGPL 3.0。 [许可证](src/main/resources/META-INF/licenses/AGPL-3.0.txt) diff --git a/build.gradle b/build.gradle index 79ecb17..d06d878 100644 --- a/build.gradle +++ b/build.gradle @@ -1,14 +1,14 @@ plugins { id 'java-library' - id 'org.jetbrains.kotlin.jvm' id 'eclipse' id 'idea' id 'maven-publish' - id 'jacoco' alias libs.plugins.modDevGradle //alias libs.plugins.shadow alias libs.plugins.spotless alias libs.plugins.lombok + alias libs.plugins.kotlin.jvm + alias libs.plugins.kotlin.lombok } group = maven_group @@ -32,11 +32,6 @@ sourceSets { runtimeClasspath += main.output + main.runtimeClasspath } - test { - compileClasspath += main.output + main.compileClasspath - runtimeClasspath += main.output + main.runtimeClasspath - } - extra { compileClasspath += main.output runtimeClasspath += main.output + main.runtimeClasspath @@ -82,41 +77,9 @@ tasks.withType(JavaCompile).configureEach { } tasks.withType(Test).configureEach { - // Test sources are NeoForge GameTests and are executed by runGameTestServer, not JUnit. failOnNoDiscoveredTests = false } lombok { version = "1.18.38" } - -jacoco { - applyTo runGameTestServer -} - -jacocoTestReport { - doFirst { - try { - runGameTestServer.exec() - } catch (RuntimeException ignored) {} - } - doLast { - println "Coverage report location:" - println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('index.html')).get()}" - println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml')).get()}" - } - executionData runGameTestServer - sourceSets sourceSets.test - reports { - csv.required = false - xml.required = true - html.outputLocation = layout.buildDirectory.dir('coverage') - xml.outputLocation = layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml')) - } - afterEvaluate { - classDirectories.setFrom(files(classDirectories.files.collect { - fileTree(dir: it, exclude: '**/client/**') - fileTree(dir: it, exclude: '**/mixins/**') - })) - } -} diff --git a/dependencies.gradle b/dependencies.gradle index 374cb52..662eb14 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,7 +1,13 @@ dependencies { compileOnly(libs.jetbrains.annotations) + compileOnly(libs.jspecify) - testImplementation(libs.testframework.get()) + // 与 Minecraft 共用运行库,供使用原始类型集合的公共接口声明依赖。 + api(libs.fastutil) + + jarJar(api(libs.kotlin.stdlib.get())) { + exclude group: 'org.jetbrains', module: 'annotations' + } // Runtime Recipe Viewers - uncomment whichever one you want to use // diff --git a/gradle.properties b/gradle.properties index e6e567a..5ee6016 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,11 +4,11 @@ org.gradle.parallel = true org.gradle.caching = true # Mod Info -mod_id = template -mod_name = Template +mod_id = mmclutils +mod_name = ModularMCLibUtils mod_version = 0.0.3 mod_description = mod_license = GNU AGPL 3.0 -mod_url = https://github.com/ModularMCLib/SyncedData-Lib/ -mod_issue_tracker = https://github.com/ModularMCLib/SyncedData-Lib/issues/ -maven_group = com.modularmc.synceddata +mod_url = https://github.com/ModularMCLib/ModularMCLib-Utils/ +mod_issue_tracker = https://github.com/ModularMCLib/ModularMCLib-Utils/issues/ +maven_group = com.modularmc.mmclutils diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c819654..95277ed 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,23 +1,33 @@ [versions] minecraft = "26.1.2" -neoForge = "26.1.2.41-beta" +neoForge = "26.1.2.126" +lombok = "9.8.2" loader = "4" -spotless = "8.4.0" -modDevGradle = "2.0.141" -lombok = "9.5.0" +shadow = "9.6.1" +spotless = "8.11.0" +modDevGradle = "2.0.148" +kotlin = "2.4.21" jetbrains-annotations = "26.1.0" -renderNurse = "0.0.14" +jspecify = "1.0.0" +fastutil = "8.5.18" +renderNurse = "0.0.26" mixin = "0.8.7" [libraries] minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" } neoForge = { module = "net.neoforged:neoforge", version.ref = "neoForge" } testframework = { module = "net.neoforged:testframework", version.ref = "neoForge" } -jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } +kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } renderNurse = { module = "net.neoforged:render-nurse", version.ref = "renderNurse" } mixin = { module = "org.spongepowered:mixin", version.ref = "mixin" } +jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } +jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" } +fastutil = { module = "it.unimi.dsi:fastutil", version.ref = "fastutil" } [plugins] modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGradle" } +shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } -lombok = { id = "io.freefair.lombok", version.ref = "lombok" } \ No newline at end of file +lombok = { id = "io.freefair.lombok", version.ref = "lombok" } +kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } +kotlin-lombok = { id = "org.jetbrains.kotlin.plugin.lombok", version.ref = "kotlin" } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index e09356e..cd13acd 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -12,7 +12,7 @@ java { withSourcesJar() } -// Use delombok'd files for sources +// 将 Lombok 生成的成员一并纳入源码包。 sourcesJar { exclude { sourceSets.main.allSource.contains it.file @@ -28,7 +28,6 @@ afterEvaluate { tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { destinationDirectory = file('build/libs/') manifest.attributes([ - 'MixinConfigs': "synceddata.mixins.json", 'Specification-Title': project.name, 'Specification-Version': mod_version, 'Specification-Vendor': 'ModularMCLib Team', diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle index 630b42c..2c0af81 100644 --- a/gradle/scripts/moddevgradle.gradle +++ b/gradle/scripts/moddevgradle.gradle @@ -24,7 +24,6 @@ neoForge { "${mod_id}" { sourceSet(sourceSets.main) sourceSet(sourceSets.client) - sourceSet(sourceSets.test) sourceSet(sourceSets.extra) sourceSet(sourceSets.clientExtra) } @@ -38,7 +37,6 @@ neoForge { gameDirectory.set(file('run/client')) - systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id) } server { @@ -48,60 +46,22 @@ neoForge { gameDirectory.set(file('run/server')) programArguments.addAll('--nogui', '--world', 'world-extra') - systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id) } - // This run config launches GameTestServer and runs all registered gametests, then exits. - // By default, the server will crash when no gametests are provided. - // The gametest system is also enabled by default for other run configs under the /test command. + // 让持续集成使用原版自带用例启动服务器、推进 Tick 并退出。 gameTestServer { type = "gameTestServer" - sourceSet = sourceSets.test + sourceSet = sourceSets.extra ideName = "Game Tests" gameDirectory.set(file('run/gametest/server')) - systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id) - environment('TEST', 'true') - } - - gameTestClient { - client() - sourceSet = sourceSets.test - ideName = "Game Tests (Client)" - - gameDirectory.set(file('run/gametest/client')) - systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id) - environment('TEST', 'true') - } - - data { - clientData() - serverData() - sourceSet = sourceSets.main - ideName = "Data Generation" - - gameDirectory.set(file('run/data')) - // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - programArguments.addAll('--mod', project.mod_id) - programArguments.addAll('--all') - programArguments.addAll('--output', file('src/generated/resources/').getAbsolutePath()) - programArguments.addAll('--existing', file('src/main/resources/').getAbsolutePath()) + programArguments.addAll('--tests', 'minecraft:always_pass') } // applies to all the run configs above configureEach { - // Recommended logging data for a userdev environment - // The markers can be added/remove as needed separated by commas. - // "SCAN": For mods scan. - // "REGISTRIES": For firing of registry events. - // "REGISTRYDUMP": For getting the contents of all registries. systemProperty 'forge.logging.markers', 'REGISTRIES' - // Enable assertions for our classes in dev environment jvmArgument('-ea:com.modularmc.template...') - - // Recommended logging level for the console - // You can set various levels here. - // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels logLevel = org.slf4j.event.Level.INFO } } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index f8e1ee3..51cbd2a 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1a70468..04d7959 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,9 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip networkTimeout=10000 +retries=0 +retryBackOffMs=500 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index adff685..249efbb 100644 --- a/gradlew +++ b/gradlew @@ -20,7 +20,7 @@ ############################################################################## # -# Gradle start up script for POSIX generated by Gradle. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -29,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -57,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. diff --git a/gradlew.bat b/gradlew.bat index c4bdd3a..3185a43 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -19,12 +19,39 @@ @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @@ -45,13 +72,14 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -59,35 +87,26 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :execute @rem Setup the command line -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle index 5c1624c..3253339 100644 --- a/settings.gradle +++ b/settings.gradle @@ -5,13 +5,10 @@ pluginManagement { maven { url = 'https://maven.neoforged.net/releases' } maven { url = "https://maven.quiltmc.org/repository/release" } } - plugins { - id 'org.jetbrains.kotlin.jvm' version '2.3.20' - } } plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' + id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' } dependencyResolutionManagement { diff --git a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java new file mode 100644 index 0000000..1d087a4 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java @@ -0,0 +1,108 @@ +package com.modularmc.mmclutils; + +import com.modularmc.mmclutils.api.input.SyncedKeyMappings; +import com.modularmc.mmclutils.client.ModularMCLibUtilsClient; + +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModList; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.fml.loading.FMLLoader; +import net.neoforged.fml.loading.FMLPaths; +import net.neoforged.neoforge.data.loading.DatagenModLoader; +import net.neoforged.neoforge.server.ServerLifecycleHooks; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jspecify.annotations.Nullable; + +import java.nio.file.Path; + +/** 注册双端入口,并提供模组标识、服务器访问和运行环境查询。 */ +@Mod(ModularMCLibUtils.MOD_ID) +public class ModularMCLibUtils { + + /** 该模组在加载器和资源标识中使用的命名空间。 */ + public static final String MOD_ID = "mmclutils"; + /** 面向加载器显示的模组名称。 */ + public static final String MOD_NAME = "ModularMCLib Utils"; + /** 用于库自身运行日志的记录器。 */ + public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); + + /** + * 登记双端共用的模组总线监听器。 + * + * @param modBus 当前模组的事件总线 + */ + public ModularMCLibUtils(IEventBus modBus) { + SyncedKeyMappings.init(modBus); + } + + /** + * 使用库的命名空间构造资源标识。 + * + * @param path 标识路径 + * @return 属于 {@link #MOD_ID} 的标识 + */ + public static Identifier id(String path) { + return Identifier.fromNamespaceAndPath(MOD_ID, path); + } + + /** 返回当前专用服或本地集成服。服务器尚未启动或已停止时返回空值。 */ + public static @Nullable MinecraftServer getServer() { + return ServerLifecycleHooks.getCurrentServer(); + } + + /** + * 在所属服务器主线程执行命令,并抑制命令反馈。 + * + * @param server 要执行命令的服务器 + * @param command 不带斜杠前缀的命令文本 + */ + public static void runCommandSilent(MinecraftServer server, String command) { + server.getCommands().performPrefixedCommand(server.createCommandSourceStack().withSuppressedOutput(), command); + } + + /** 返回当前游戏实例目录。 */ + public static Path getGameDir() { + return FMLPaths.GAMEDIR.get(); + } + + /** 判断当前运行是否为生产环境。 */ + public static boolean isProd() { + return FMLEnvironment.isProduction(); + } + + /** 判断当前运行是否为开发环境。 */ + public static boolean isDev() { + return !isProd(); + } + + /** 判断加载器是否正在运行数据生成。 */ + public static boolean isDataGen() { + return DatagenModLoader.isRunningDataGen(); + } + + /** + * 判断模组是否已加载。在模组列表尚未创建的加载早期使用加载列表查询。 + * + * @param modId 要查询的命名空间 + * @return 存在对应模组时为 {@code true} + */ + public static boolean isModLoaded(String modId) { + ModList mods = ModList.get(); + return mods == null ? FMLLoader.getCurrent().getLoadingModList().getModFileById(modId) != null : mods.isLoaded(modId); + } + + /** 判断物理运行端。集成服务器所在进程同样返回真。 */ + public static boolean isClientSide() { + return FMLEnvironment.getDist().isClient(); + } + + /** 判断当前线程是否为物理客户端主线程。专用服务器上始终返回假。 */ + public static boolean isClientThread() { + return isClientSide() && ModularMCLibUtilsClient.isClientThread(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityIndex.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityIndex.java new file mode 100644 index 0000000..b949c20 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityIndex.java @@ -0,0 +1,149 @@ +package com.modularmc.mmclutils.api.blockentity; + +import com.modularmc.mmclutils.api.level.BlockIndex; +import com.modularmc.mmclutils.api.level.BlockRange; +import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; + +import org.jspecify.annotations.Nullable; + +import java.util.Collection; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * 按类型维护方块实体索引。区块放入、替换、移除方块实体以及区块卸载时会自动更新。 + * 必须在模组加载阶段创建(声明成静态常量,并在模组构造时触发所在类初始化),维度开始加载方块实体后再创建会抛异常。功能: + * + * + * @param 收录的方块实体类型或由方块实体实现的接口 + */ +public final class BlockEntityIndex { + + private final TypedSink sink; + + private BlockEntityIndex(TypedSink sink) { + this.sink = sink; + } + + /** 为指定类或接口建立索引,兼容实现该类型的方块实体。 */ + public static BlockEntityIndex create(Class type) { + return create(type, null); + } + + /** + * 在模组加载阶段创建一个按类型自动登记的索引。 + * + * @param 收录的方块实体类型或接口 + * @param type 用于筛选方块实体的运行时类型 + * @param admit 只在方块实体登记时执行的附加条件,为空时接纳全部对应类型 + * @return 由加载区块维护的索引 + * @throws IllegalStateException 已开始跟踪方块实体 + */ + public static BlockEntityIndex create(Class type, @Nullable Predicate admit) { + return new BlockEntityIndex<>(BlockEntityTracking.TRACKER.register(new TypedSink<>(type, admit))); + } + + /** 返回包含所有已登记原版方块实体的共享索引。 */ + public static BlockEntityIndex all() { + return All.INDEX; + } + + private static final class All { + + static final BlockEntityIndex INDEX = create(BlockEntity.class); + } + + TypedSink sink() { + return sink; + } + + private @Nullable BlockIndex index(Level level) { + return sink.index((SlotHolder) level); + } + + /** 向集合追加范围内通过筛选的方块实体。筛选可为空,返回集合实际增加的数量。 */ + public int query(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate filter, Collection out) { + BlockIndex index = index(level); + return index == null ? 0 : index.query(x, y, z, range, filter, out); + } + + /** 使用方块位置作为查询中心,并将结果加入调用方提供的集合。 */ + public int query(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter, Collection out) { + return query(level, center.getX(), center.getY(), center.getZ(), range, filter, out); + } + + /** 在世界线程访问范围内的匹配实体。回调不应修改正在遍历的索引。 */ + public void forEach(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate filter, Consumer action) { + BlockIndex index = index(level); + if (index != null) index.query(x, y, z, range, filter, action); + } + + /** 以方块位置作为中心连续处理匹配值。 */ + public void forEach(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter, Consumer action) { + forEach(level, center.getX(), center.getY(), center.getZ(), range, filter, action); + } + + /** 查找范围内任一符合条件的实体,未命中时返回空值。 */ + public @Nullable T findAny(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate filter) { + BlockIndex index = index(level); + return index == null ? null : index.findAny(x, y, z, range, filter); + } + + /** 以方块位置为中心查找任一匹配实体。 */ + public @Nullable T findAny(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter) { + return findAny(level, center.getX(), center.getY(), center.getZ(), range, filter); + } + + /** 按平方欧氏距离查找最近实体,未命中时返回空值。 */ + public @Nullable T findNearest(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate filter) { + BlockIndex index = index(level); + return index == null ? null : index.findNearest(x, y, z, range, filter); + } + + /** 以方块位置为中心查找最近的匹配实体。 */ + public @Nullable T findNearest(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter) { + return findNearest(level, center.getX(), center.getY(), center.getZ(), range, filter); + } + + /** 在当前维度的全部已索引实体中查找任意匹配项。 */ + public @Nullable T findAny(Level level, Predicate filter) { + BlockIndex index = index(level); + return index == null ? null : index.findAny(filter); + } + + /** 遍历该维度已索引的实体,回调中不要修改索引。 */ + public void forEach(Level level, Consumer action) { + BlockIndex index = index(level); + if (index != null) index.forEach(action); + } + + /** 按位置查询当前索引中的实体。条目缺失时返回空值。 */ + public @Nullable T get(Level level, BlockPos pos) { + BlockIndex index = index(level); + return index == null ? null : index.get(pos); + } + + /** 读取此维度内保存的条目总数。 */ + public int size(Level level) { + BlockIndex index = index(level); + return index == null ? 0 : index.size(); + } + + /** 读取本维度索引的修改版本,索引尚未创建时返回零。 */ + public int version(Level level) { + BlockIndex index = index(level); + return index == null ? 0 : index.version(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityTracking.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityTracking.java new file mode 100644 index 0000000..a4bec78 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityTracking.java @@ -0,0 +1,93 @@ +package com.modularmc.mmclutils.api.blockentity; + +import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.chunk.LevelChunk; + +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; + +/** 维护方块实体与区块可见性变化对应的空间索引状态。 */ +@ApiStatus.Internal +public final class BlockEntityTracking { + + static final Tracker TRACKER = new Tracker<>(new Tracker.Access<>() { + + @Override + public @Nullable SlotHolder holder(BlockEntity be) { + return be.getLevel() instanceof SlotHolder holder ? holder : null; + } + + @Override + public BlockPos pos(BlockEntity be) { + return be.getBlockPos(); + } + + @Override + public boolean live(BlockEntity be) { + return !be.isRemoved(); + } + + @Override + public int probedMask(BlockEntity be) { + return ((TrackedBlockEntity) be).mmclutils$probedMask(); + } + + @Override + public void setProbedMask(BlockEntity be, int mask) { + ((TrackedBlockEntity) be).mmclutils$setProbedMask(mask); + } + }); + + private BlockEntityTracking() {} + + /** 在实体加入其所在区块后登记可探测索引。 */ + public static void added(BlockEntity be) { + TRACKER.added(be); + } + + /** 在实体移除或替换前撤销其索引登记。 */ + public static void removed(BlockEntity be) { + TRACKER.removed(be); + } + + /** + * 切换整个区块在空间索引中的可见性,并同步处理当前保存的方块实体。 + * + * @param chunk 要更新的区块 + * @param visible 区块应参与索引查询时为 {@code true} + */ + public static void setVisible(LevelChunk chunk, boolean visible) { + TrackedChunk tracked = (TrackedChunk) chunk; + if (tracked.mmclutils$hidden() != visible) return; + tracked.mmclutils$setHidden(!visible); + for (BlockEntity be : chunk.getBlockEntities().values()) { + if (visible) TRACKER.added(be); + else TRACKER.removed(be); + } + } + + /** 方块实体在探测索引中使用的候选位标记。 */ + @ApiStatus.Internal + public interface TrackedBlockEntity { + + /** 返回已通过探测并登记的索引位掩码。 */ + int mmclutils$probedMask(); + + /** 将索引登记位掩码替换为指定值。 */ + void mmclutils$setProbedMask(int mask); + } + + /** 区块从可见列表移除时用于暂停其中的方块实体登记。 */ + @ApiStatus.Internal + public interface TrackedChunk { + + /** 查询区块当前是否已从索引隐藏。 */ + boolean mmclutils$hidden(); + + /** 记录显隐切换,由索引同步方块实体。 */ + void mmclutils$setHidden(boolean hidden); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedBlockEntityIndex.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedBlockEntityIndex.java new file mode 100644 index 0000000..a2643fc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedBlockEntityIndex.java @@ -0,0 +1,106 @@ +package com.modularmc.mmclutils.api.blockentity; + +import com.modularmc.mmclutils.api.level.BlockRange; +import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; + +import org.jspecify.annotations.Nullable; + +import java.util.Collection; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * 按能力自动维护的方块实体索引:分类器按类把方块实体分为不收录、候选(确定提供)、待探测(可能提供)三种, + * 待探测的不另外存放,查询第一次覆盖到所在区段时从 {@link BlockEntityIndex#all()} 取出来用探测条件判一次,结果按实例记在方块实体上, + * 之后只走候选。适合能力挂在任意方块实体上、逐个判断很贵的查找;能力会随时变化的,查询结果使用前仍要再取一次能力。 + * 创建时机要求同 {@link BlockEntityIndex},最多 32 个。功能: + *
    + *
  • {@link #create(Function, Predicate)}:分类器每个类只调用一次,返回 null + * 视为不收录;{@link #create(Function, Predicate, Predicate)}:另在登记时判一次条件
  • + *
  • {@link #query}/{@link #forEach}/{@link #findAny}:先探测范围内还没探测过的方块实体,再按 {@link BlockRange} 查候选
  • + *
  • {@link #candidateCount}/{@link #sweptSectionCount}:某维度候选数与已扫过的区段数
  • + *
+ */ +public final class ProbedBlockEntityIndex { + + /** 按方块实体类型为自动索引选择的处理方式。 */ + public enum Kind { + /** 不把此类型登记到索引。 */ + NONE, + /** 登记为可直接参与空间查询的候选。 */ + CANDIDATE, + /** 仅在查询覆盖所在区段时按需执行探测条件。 */ + PROBE + } + + private final ProbedSink sink; + + private ProbedBlockEntityIndex(ProbedSink sink) { + this.sink = sink; + } + + /** + * 创建按类型分类并按需探测的方块实体索引。 + * + * @param classifier 将方块实体类型分类为不收录、候选或按需探测 + * @param probe 匹配查询触达的待探测实体时执行的能力检查 + * @return 新的索引,登记在创建后出现的索引条目上 + */ + public static ProbedBlockEntityIndex create(Function, Kind> classifier, Predicate probe) { + return create(classifier, probe, null); + } + + /** + * 创建具有额外登记过滤条件的按需探测索引。 + * + * @param classifier 将方块实体类型分类为不收录、候选或按需探测 + * @param probe 查询触达待探测实体时的能力检查 + * @param admit 登记或实体状态变化时的候选过滤条件,可以为空 + * @return 新的按需探测索引 + */ + public static ProbedBlockEntityIndex create(Function, Kind> classifier, Predicate probe, + @Nullable Predicate admit) { + Tracker tracker = BlockEntityTracking.TRACKER; + TypedSink all = BlockEntityIndex.all().sink(); + return new ProbedBlockEntityIndex(tracker.register(new ProbedSink<>(tracker, all, classifier, probe, admit))); + } + + /** + * 在指定范围查找候选,并把匹配项追加至输出集合。 + * + * @param level 要查询的维度 + * @param center 范围中心 + * @param range 球形或长方体范围 + * @param filter 可选的最终结果过滤条件 + * @param out 接收匹配方块实体的集合 + * @return 追加到集合中的条目数 + */ + public int query(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter, Collection out) { + return sink.query((SlotHolder) level, center.getX(), center.getY(), center.getZ(), range, filter, out); + } + + /** 对范围内匹配的方块实体依次执行操作。 */ + public void forEach(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter, Consumer action) { + sink.forEach((SlotHolder) level, center.getX(), center.getY(), center.getZ(), range, filter, action); + } + + /** 返回范围内第一个满足过滤条件的方块实体,没有匹配项时返回空值。 */ + public @Nullable BlockEntity findAny(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter) { + return sink.findAny((SlotHolder) level, center.getX(), center.getY(), center.getZ(), range, filter); + } + + /** 返回此维度当前已登记的候选实体数量。 */ + public int candidateCount(Level level) { + return sink.candidateCount((SlotHolder) level); + } + + /** 返回此维度已执行过按需探测的区段数量。 */ + public int sweptSectionCount(Level level) { + return sink.sweptSectionCount((SlotHolder) level); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedSink.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedSink.java new file mode 100644 index 0000000..0c2b9d6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedSink.java @@ -0,0 +1,180 @@ +package com.modularmc.mmclutils.api.blockentity; + +import com.modularmc.mmclutils.api.level.BlockIndex; +import com.modularmc.mmclutils.api.level.BlockRange; +import com.modularmc.mmclutils.api.level.LevelStore; +import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; + +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * 按能力收录对象的自动索引:类确定提供的直接进候选树;类可能提供的不另存,查询第一次覆盖到某个 16³ 区段时,从共用的全量索引里取出 + * 区段内还没被本索引探测过的对象探测一次,通过的进候选树,区段记为已扫过;之后落进已扫过区段的对象记进新增树,被查询覆盖时再探测。功能: + *
    + *
  • {@link #accepts}:按类分为不收录、候选、待探测三种,每个类只判一次;同一分发器下最多 32 个本类索引,每个占对象上探测标记的一位
  • + *
  • {@link #added}:候选类登记时判一次条件后进候选树;待探测类只有落进已扫过的区段时才记进新增树,其余不占任何存储
  • + *
  • {@link #removed}:从候选树和新增树注销这个对象本身,并清掉它的探测标记;已扫过的区段保持有效
  • + *
  • {@link #forEach}/{@link #findAny}/{@link #query}:先扫范围内未扫过的区段、探测范围内的新增对象(已失效的不探测),再查候选树; + * 范围覆盖的区段超过 {@link #MAX_SECTIONS} 个时直接逐个检查范围内的对象,不记区段;探测中再次查询也安全
  • + *
  • {@link #candidateCount}/{@link #sweptSectionCount}/{@link #freshCount}:某维度候选数、已扫过的区段数与待探测的新增数
  • + *
+ */ +final class ProbedSink extends Tracker.Sink { + + static final int MAX_SECTIONS = 4096; + + static final class State { + + final BlockIndex candidates = new BlockIndex<>(); + final BlockIndex fresh = new BlockIndex<>(); + final LongOpenHashSet swept = new LongOpenHashSet(); + final ArrayList scratch = new ArrayList<>(); + int depth; + } + + private final ClassValue kinds; + private final Predicate probe; + private final @Nullable Predicate admit; + private final Tracker.Access access; + private final TypedSink all; + private final int bit; + private final LevelStore> store = LevelStore.create(State::new); + + ProbedSink(Tracker tracker, TypedSink all, Function, ProbedBlockEntityIndex.Kind> classifier, + Predicate probe, @Nullable Predicate admit) { + this.bit = tracker.allocateProbeBit(); + this.access = tracker.access(); + this.all = all; + this.probe = probe; + this.admit = admit; + this.kinds = new ClassValue<>() { + + @Override + protected ProbedBlockEntityIndex.Kind computeValue(Class type) { + ProbedBlockEntityIndex.Kind kind = classifier.apply(type); + return kind == null ? ProbedBlockEntityIndex.Kind.NONE : kind; + } + }; + } + + @Override + boolean accepts(Class type) { + return kinds.get(type) != ProbedBlockEntityIndex.Kind.NONE; + } + + @Override + void added(SlotHolder holder, E e, BlockPos pos) { + if (kinds.get(e.getClass()) == ProbedBlockEntityIndex.Kind.CANDIDATE) { + if (admit != null && !admit.test(e)) return; + store.forHolder(holder).candidates.put(pos, e); + } else { + State state = store.forHolderIfPresent(holder); + if (state != null && state.swept.contains(SectionPos.asLong(pos))) state.fresh.put(pos, e); + } + } + + @Override + void removed(SlotHolder holder, E e, BlockPos pos) { + int mask = access.probedMask(e); + if ((mask & bit) != 0) access.setProbedMask(e, mask & ~bit); + State state = store.forHolderIfPresent(holder); + if (state == null) return; + state.candidates.remove(pos, e); + state.fresh.remove(pos, e); + } + + void forEach(SlotHolder holder, int x, int y, int z, BlockRange range, @Nullable Predicate filter, Consumer action) { + State state = prepare(holder, x, y, z, range); + if (state != null && !state.candidates.isEmpty()) state.candidates.query(x, y, z, range, filter, action); + } + + int query(SlotHolder holder, int x, int y, int z, BlockRange range, @Nullable Predicate filter, Collection out) { + State state = prepare(holder, x, y, z, range); + return state == null || state.candidates.isEmpty() ? 0 : state.candidates.query(x, y, z, range, filter, out); + } + + @Nullable + E findAny(SlotHolder holder, int x, int y, int z, BlockRange range, @Nullable Predicate filter) { + State state = prepare(holder, x, y, z, range); + return state == null || state.candidates.isEmpty() ? null : state.candidates.findAny(x, y, z, range, filter); + } + + int candidateCount(SlotHolder holder) { + State state = store.forHolderIfPresent(holder); + return state == null ? 0 : state.candidates.size(); + } + + int sweptSectionCount(SlotHolder holder) { + State state = store.forHolderIfPresent(holder); + return state == null ? 0 : state.swept.size(); + } + + int freshCount(SlotHolder holder) { + State state = store.forHolderIfPresent(holder); + return state == null ? 0 : state.fresh.size(); + } + + @Nullable + private State prepare(SlotHolder holder, int x, int y, int z, BlockRange range) { + BlockIndex source = all.index(holder); + if (source == null || source.isEmpty() || range.isEmpty()) return store.forHolderIfPresent(holder); + State state = store.forHolder(holder); + long minX = Math.max((long) x - range.radiusX(), BlockIndex.MIN_XZ), maxX = Math.min((long) x + range.radiusX(), BlockIndex.MAX_XZ); + long minY = Math.max((long) y - range.radiusY(), BlockIndex.MIN_Y), maxY = Math.min((long) y + range.radiusY(), BlockIndex.MAX_Y); + long minZ = Math.max((long) z - range.radiusZ(), BlockIndex.MIN_XZ), maxZ = Math.min((long) z + range.radiusZ(), BlockIndex.MAX_XZ); + if (minX > maxX || minY > maxY || minZ > maxZ) return state; + int sx0 = (int) minX >> 4, sx1 = (int) maxX >> 4, sy0 = (int) minY >> 4, sy1 = (int) maxY >> 4, sz0 = (int) minZ >> 4, sz1 = (int) maxZ >> 4; + long sections = (long) (sx1 - sx0 + 1) * (sy1 - sy0 + 1) * (sz1 - sz0 + 1); + if (sections > MAX_SECTIONS) { + sweep(state, source, x, y, z, range, Integer.MIN_VALUE, 0, 0); + return state; + } + for (int sx = sx0; sx <= sx1; sx++) { + for (int sz = sz0; sz <= sz1; sz++) { + for (int sy = sy0; sy <= sy1; sy++) { + if (!state.swept.add(SectionPos.asLong(sx, sy, sz))) continue; + sweep(state, source, (sx << 4) + 8, (sy << 4) + 8, (sz << 4) + 8, BlockRange.box(8), sx, sy, sz); + } + } + } + if (!state.fresh.isEmpty()) sweep(state, state.fresh, x, y, z, range, Integer.MIN_VALUE, 0, 0); + return state; + } + + private void sweep(State state, BlockIndex source, int x, int y, int z, BlockRange range, int sx, int sy, int sz) { + boolean section = sx != Integer.MIN_VALUE; + List found = state.depth == 0 ? state.scratch : new ArrayList<>(); + found.clear(); + source.query(x, y, z, range, null, found); + if (found.isEmpty()) return; + state.depth++; + try { + for (int i = 0, n = found.size(); i < n; i++) { + E e = found.get(i); + if (kinds.get(e.getClass()) != ProbedBlockEntityIndex.Kind.PROBE) continue; + BlockPos pos = access.pos(e); + if (section && ((pos.getX() >> 4) != sx || (pos.getY() >> 4) != sy || (pos.getZ() >> 4) != sz)) continue; + int mask = access.probedMask(e); + if ((mask & bit) != 0) continue; + access.setProbedMask(e, mask | bit); + if (!section && !state.fresh.isEmpty()) state.fresh.remove(pos, e); + if (admit != null && !admit.test(e)) continue; + if (access.live(e) && probe.test(e)) state.candidates.put(pos, e); + } + } finally { + state.depth--; + found.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/Tracker.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/Tracker.java new file mode 100644 index 0000000..be01b8c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/Tracker.java @@ -0,0 +1,113 @@ +package com.modularmc.mmclutils.api.blockentity; + +import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder; + +import net.minecraft.core.BlockPos; + +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * 把带坐标对象的登记、注销分发给关心它的索引:按对象的运行时类缓存一次关心它的索引列表,没有索引关心的类只做一次缓存查找。功能: + *
    + *
  • {@link #register}:登记一个索引;第一次分发之后再登记会抛 {@link IllegalStateException},保证类缓存与已登记的对象一致
  • + *
  • {@link #added}/{@link #removed}:把对象交给按类缓存的索引,对象不在任何维度时忽略
  • + *
  • {@link #started}:是否已经分发过;{@link #allocateProbeBit}:给按能力收录的索引分配对象探测标记里的一位,最多 32 位
  • + *
+ */ +final class Tracker { + + interface Access { + + @Nullable + SlotHolder holder(E e); + + BlockPos pos(E e); + + boolean live(E e); + + int probedMask(E e); + + void setProbedMask(E e, int mask); + } + + abstract static class Sink { + + abstract boolean accepts(Class type); + + abstract void added(SlotHolder holder, E e, BlockPos pos); + + abstract void removed(SlotHolder holder, E e, BlockPos pos); + } + + private final Access access; + private final List> sinks = new CopyOnWriteArrayList<>(); + private final ClassValue[]> byClass = new ClassValue<>() { + + @Override + @SuppressWarnings("unchecked") + protected Sink[] computeValue(Class type) { + List> list = new ArrayList<>(); + for (Sink sink : sinks) { + if (sink.accepts(type)) list.add(sink); + } + return list.toArray(new Sink[0]); + } + }; + private volatile boolean started; + private int probeBits; + + Tracker(Access access) { + this.access = access; + } + + Access access() { + return access; + } + + synchronized > S register(S sink) { + if (started) { + throw new IllegalStateException("block entity indexes must be created during mod loading, before any level loads block entities"); + } + sinks.add(sink); + return sink; + } + + synchronized int allocateProbeBit() { + if (probeBits >= 32) throw new IllegalStateException("too many probed indexes (max 32)"); + return 1 << probeBits++; + } + + boolean started() { + return started; + } + + private void start() { + synchronized (this) { + started = true; + } + } + + void added(E e) { + if (!started) start(); + Sink[] targets = byClass.get(e.getClass()); + if (targets.length == 0) return; + SlotHolder holder = access.holder(e); + if (holder == null) return; + BlockPos pos = access.pos(e); + for (Sink sink : targets) sink.added(holder, e, pos); + } + + void removed(E e) { + if (!started) start(); + Sink[] targets = byClass.get(e.getClass()); + if (targets.length == 0) return; + SlotHolder holder = access.holder(e); + if (holder == null) return; + BlockPos pos = access.pos(e); + for (Sink sink : targets) sink.removed(holder, e, pos); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/TypedSink.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/TypedSink.java new file mode 100644 index 0000000..dd692f0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/TypedSink.java @@ -0,0 +1,55 @@ +package com.modularmc.mmclutils.api.blockentity; + +import com.modularmc.mmclutils.api.level.BlockIndex; +import com.modularmc.mmclutils.api.level.LevelStore; +import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder; + +import net.minecraft.core.BlockPos; + +import org.jspecify.annotations.Nullable; + +import java.util.function.Predicate; + +/** + * 按类型收录对象的自动索引:对象的运行时类是 {@code type} 的子类型、且登记时通过 {@code admit} 的对象进入所在维度的 {@link BlockIndex}。功能: + *
    + *
  • {@link #accepts}:按类判断是否关心,供 {@link Tracker} 缓存
  • + *
  • {@link #added}:登记时判一次 {@code admit},通过就放进该维度的索引,同一坐标已有对象时替换
  • + *
  • {@link #removed}:只有该坐标登记的正是这个对象时才注销
  • + *
  • {@link #index}:取某维度的索引,没有登记过时返回 null
  • + *
+ */ +final class TypedSink extends Tracker.Sink { + + private final Class type; + private final @Nullable Predicate admit; + private final LevelStore> store = LevelStore.create(BlockIndex::new); + + TypedSink(Class type, @Nullable Predicate admit) { + this.type = type; + this.admit = admit; + } + + @Override + boolean accepts(Class c) { + return type.isAssignableFrom(c); + } + + @Override + void added(SlotHolder holder, E e, BlockPos pos) { + T t = type.cast(e); + if (admit != null && !admit.test(t)) return; + store.forHolder(holder).put(pos, t); + } + + @Override + void removed(SlotHolder holder, E e, BlockPos pos) { + BlockIndex index = store.forHolderIfPresent(holder); + if (index != null) index.remove(pos, type.cast(e)); + } + + @Nullable + BlockIndex index(SlotHolder holder) { + return store.forHolderIfPresent(holder); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/capability/AdjacentBlockCapabilityCache.java b/src/main/java/com/modularmc/mmclutils/api/capability/AdjacentBlockCapabilityCache.java new file mode 100644 index 0000000..c8dba88 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/capability/AdjacentBlockCapabilityCache.java @@ -0,0 +1,103 @@ +package com.modularmc.mmclutils.api.capability; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; +import net.neoforged.neoforge.capabilities.BlockCapability; +import net.neoforged.neoforge.capabilities.BlockCapabilityCache; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectList; +import it.unimi.dsi.fastutil.objects.ObjectLists; +import org.jspecify.annotations.Nullable; + +import java.util.EnumMap; +import java.util.function.BooleanSupplier; + +/** + * 为固定原点周围的六个方块保留 NeoForge 能力缓存。 + * + * @param 能力类型 + */ +public final class AdjacentBlockCapabilityCache { + + private final BlockCapability capability; + private final ServerLevel level; + private final BlockPos origin; + private final BooleanSupplier isValid; + private final EnumMap> caches = new EnumMap<>(Direction.class); + + /** + * 按需建立各方向缓存。失效监听器随所属对象的有效期释放。 + * + * @param capability 查询的方块能力 + * @param level 目标方块所在的服务端维度 + * @param origin 查询原点 + * @param isValid 所属对象的存活判定 + */ + public AdjacentBlockCapabilityCache( + BlockCapability capability, + ServerLevel level, + BlockPos origin, + BooleanSupplier isValid) { + this.capability = capability; + this.level = level; + this.origin = origin.immutable(); + this.isValid = isValid; + } + + /** + * 查询邻接方块朝向原点的面所提供的能力。 + * + * @param side 从原点指向目标的方向 + * @return 当前能力,目标未暴露该能力时返回 {@code null} + */ + @Nullable + public T get(Direction side) { + return this.caches.computeIfAbsent(side, this::createCache).getCapability(); + } + + /** + * 按传入的方向顺序查询能力。 + * + * @param sides 参与查询的方向 + * @return 当前已暴露能力的不可变列表 + */ + public ObjectList getAll(Iterable sides) { + ObjectList resolved = new ObjectArrayList<>(); + for (Direction side : sides) { + T value = get(side); + if (value != null) { + resolved.add(value); + } + } + return resolved.isEmpty() ? ObjectList.of() : ObjectLists.unmodifiable(resolved); + } + + /** + * 查询能力并保留每项对应的方向。 + * + * @param sides 参与查询的方向 + * @return 按枚举顺序返回方向与能力的独立映射,修改结果不会影响缓存 + */ + public EnumMap getAllBySide(Iterable sides) { + EnumMap resolved = new EnumMap<>(Direction.class); + for (Direction side : sides) { + T value = get(side); + if (value != null) { + resolved.put(side, value); + } + } + return resolved; + } + + private BlockCapabilityCache createCache(Direction side) { + return BlockCapabilityCache.create( + this.capability, + this.level, + this.origin.relative(side), + side.getOpposite(), + this.isValid, + () -> {}); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/CyclicIterator.java b/src/main/java/com/modularmc/mmclutils/api/collection/CyclicIterator.java new file mode 100644 index 0000000..4c635ef --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/CyclicIterator.java @@ -0,0 +1,47 @@ +package com.modularmc.mmclutils.api.collection; + +import java.util.Iterator; + +/** 依次遍历非空元素集合,到达末尾后从头继续。 */ +public final class CyclicIterator implements Iterable, Iterator { + + /** 供空遍历共用的实例。泛型调用使用 {@link #empty()}。 */ + public static final CyclicIterator EMPTY = new CyclicIterator(new Object[0]); + + /** 取得可用作任意元素类型的空迭代器。 */ + public static CyclicIterator empty() { + return EMPTY; + } + + /** 保留的原始数组引用,迭代器直接读取此数组中的元素。 */ + public final T[] array; + /** 一次遍历所包含的元素数。 */ + public final int size; + private int index; + private int remaining; + + /** 包装数组。每次调用 {@link #iterator()} 重置剩余次数,沿用上次停下的数组位置。 */ + public CyclicIterator(T[] array) { + this.array = array; + this.size = this.array.length; + } + + @Override + public Iterator iterator() { + remaining = size; + return this; + } + + @Override + public boolean hasNext() { + return remaining > 0; + } + + @Override + public T next() { + if (index == size) index = 0; + T element = array[index++]; + remaining--; + return element; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/IntrusiveDeque.java b/src/main/java/com/modularmc/mmclutils/api/collection/IntrusiveDeque.java new file mode 100644 index 0000000..0bd4150 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/IntrusiveDeque.java @@ -0,0 +1,272 @@ +package com.modularmc.mmclutils.api.collection; + +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; + +/** 将链接字段保存在节点上,提供常数时间的队头和队尾操作。 */ +public class IntrusiveDeque> implements Iterable { + + /** 由队列链接操作维护的首节点,空队列时为空值。 */ + protected T first; + /** 由队列链接操作维护的尾节点,空队列时为空值。 */ + protected T last; + /** 当前链接在此队列上的节点数。 */ + protected int size; + + /** 判断队列是否没有链接节点。 */ + public boolean isEmpty() { + return first == null; + } + + /** 取得当前节点数,时间复杂度为常数。 */ + public int size() { + return size; + } + + /** 读取首节点,空队列时返回空值。 */ + public T peekFirst() { + return first; + } + + /** 读取尾节点,空队列时返回空值。 */ + public T peekLast() { + return last; + } + + /** 在队尾链接一个游离节点。调用方须保证该节点未加入任何队列。 */ + public void addLast(T node) { + final T l = last; + if (l == null) { + first = node; + } else { + l.setNext(node); + node.setPrev(l); + } + last = node; + size++; + } + + /** 在队首链接一个游离节点。调用方须保证该节点未加入任何队列。 */ + public void addFirst(T node) { + final T f = first; + if (f == null) { + last = node; + } else { + f.setPrev(node); + node.setNext(f); + } + first = node; + size++; + } + + /** 直接移除且清除已有节点的链接。传入的节点须已属于此队列。 */ + public void unlink(T node) { + final T prev = node.getPrev(); + final T next = node.getNext(); + if (prev == null) { + first = next; + } else { + prev.setNext(next); + node.setPrev(null); + } + if (next == null) { + last = prev; + } else { + next.setPrev(prev); + node.setNext(null); + } + size--; + } + + /** 若节点已在此队列中则移除。请勿传入属于其他队列的节点。 */ + public boolean remove(T node) { + if (node.getPrev() != null || node.getNext() != null || node == first) { + unlink(node); + return true; + } + return false; + } + + /** 取出首节点并清理其链接,空队列时返回空值。 */ + public T pollFirst() { + final T f = first; + if (f == null) return null; + unlink(f); + return f; + } + + /** 取出尾节点并清理其链接,空队列时返回空值。 */ + public T pollLast() { + final T l = last; + if (l == null) return null; + unlink(l); + return l; + } + + /** 取出首节点。空队列时抛出 {@link NoSuchElementException}。 */ + public T removeFirst() { + final T f = pollFirst(); + if (f == null) throw new NoSuchElementException(); + return f; + } + + /** 取出尾节点。空队列时抛出 {@link NoSuchElementException}。 */ + public T removeLast() { + final T l = pollLast(); + if (l == null) throw new NoSuchElementException(); + return l; + } + + /** 将另一个队列拼到尾端并清空对方队列。时间复杂度为常数。 */ + public void merge(IntrusiveDeque other) { + if (other.first == null || other == this) return; + final T otherFirst = other.first; + final T otherLast = other.last; + if (last == null) { + first = otherFirst; + } else { + last.setNext(otherFirst); + otherFirst.setPrev(last); + } + last = otherLast; + size += other.size; + other.first = null; + other.last = null; + other.size = 0; + } + + /** 断开队列中所有节点的前后链接。被清出的节点可以加入另一条队列。 */ + public void clear() { + for (T node = first; node != null;) { + T next = node.getNext(); + node.setPrev(null); + node.setNext(null); + node = next; + } + first = null; + last = null; + size = 0; + } + + @Override + public Iterator iterator() { + return new QueueIterator(); + } + + /** 按节点身份线性查找。可用于调用者没有节点所属队列信息的情况。 */ + public boolean contains(T node) { + for (T n = first; n != null; n = n.getNext()) { + if (n == node) return true; + } + return false; + } + + /** 按队头到队尾的顺序复制节点引用。 */ + public Object[] toArray() { + Object[] arr = new Object[size]; + int i = 0; + for (T n = first; n != null; n = n.getNext()) { + arr[i++] = n; + } + return arr; + } + + @Override + public void forEach(Consumer action) { + for (T n = first; n != null; n = n.getNext()) { + action.accept(n); + } + } + + @Override + public Spliterator spliterator() { + return Spliterators.spliterator(iterator(), size, Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL); + } + + private final class QueueIterator implements Iterator { + + private T nextNode = first; + private T currentNode; + + @Override + public boolean hasNext() { + return nextNode != null; + } + + @Override + public T next() { + var nextNode = this.nextNode; + if (nextNode == null) throw new NoSuchElementException(); + this.currentNode = nextNode; + this.nextNode = nextNode.getNext(); + return nextNode; + } + + @Override + public void remove() { + var currentNode = this.currentNode; + if (currentNode == null) throw new IllegalStateException(); + IntrusiveDeque.this.unlink(currentNode); + this.currentNode = null; + } + + @Override + public void forEachRemaining(Consumer action) { + while (hasNext()) action.accept(next()); + } + } + + /** + * 为侵入式双端队列提供前后节点链接。 + * 实现对象同一时刻只能加入一条链,链接初始为空且由所属队列维护。 + * + * @param 实际节点类型 + */ + public interface LinkNode> { + + /** 返回当前节点的前驱,作为队首时返回空值。 */ + T getPrev(); + + /** 更新前驱链接,由所属队列调用。 */ + void setPrev(T prev); + + /** 返回当前节点的后继,作为队尾时返回空值。 */ + T getNext(); + + /** 更新后继链接,由所属队列调用。 */ + void setNext(T next); + } + + /** 直接保存前后链接的节点基类。链接只能由所属队列维护。 */ + public abstract static class AbstractLinkNode> implements LinkNode { + + /** 前驱节点,游离或在队首时为空值。 */ + protected T prev; + + /** 后继节点,游离或在队尾时为空值。 */ + protected T next; + + @Override + public T getPrev() { + return prev; + } + + @Override + public void setPrev(T prev) { + this.prev = prev; + } + + @Override + public T getNext() { + return next; + } + + @Override + public void setNext(T next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/ByteCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ByteCache.java new file mode 100644 index 0000000..e451d49 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ByteCache.java @@ -0,0 +1,180 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.bytes.Byte2ObjectFunction; + +/** + * 使用原始类型 {@code byte} 作为键,强引用缓存值,直到缓存条目被清除。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * + * @param 缓存值类型 + */ +public final class ByteCache extends SegmentedCache> { + + private final Byte2ObjectFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public ByteCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public ByteCache(Byte2ObjectFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public ByteCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public ByteCache(int concurrencyLevel, Byte2ObjectFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final byte k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final byte k, Byte2ObjectFunction createFunction) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final byte k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 只在没有有效值时写入,返回最终关联的值。 */ + public V putIfAbsent(final byte k, final V v) { + int mix = HashCommon.mix(k); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + static final class Segment extends HashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return node.key; + } + + /** 在写锁内合并并发变更。 */ + private V getCache(final byte k, final int mix, Byte2ObjectFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.get(k); + stamp = writeLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, table[index]); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final byte k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private V put(final byte k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final byte key; + private final V value; + private volatile Node next; + + private Node(byte key, V value, Node next) { + this.key = key; + this.value = value; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/CacheReferenceQueue.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CacheReferenceQueue.java new file mode 100644 index 0000000..8ea7a1b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CacheReferenceQueue.java @@ -0,0 +1,46 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.lang.ref.WeakReference; +import java.util.concurrent.ConcurrentLinkedDeque; + +/** 集中清理由引用队列报告的失效项,避免为每个弱引用缓存启动线程。 */ +final class CacheReferenceQueue { + + private CacheReferenceQueue() {} + + private static final long INTERVAL_MS = 500L; + + private static final ConcurrentLinkedDeque>> CACHES = new ConcurrentLinkedDeque<>(); + + static { + Thread thread = new Thread(() -> { + while (true) { + try { + Thread.sleep(INTERVAL_MS); + } catch (InterruptedException e) { + return; + } + sweep(); + } + }, "mmclutils-cache-drainer"); + thread.setDaemon(true); + thread.setPriority(Thread.MIN_PRIORITY); + thread.start(); + } + + public static void add(WeakSegmentedCache cache) { + CACHES.offerLast(new WeakReference<>(cache)); + } + + private static void sweep() { + var it = CACHES.iterator(); + while (it.hasNext()) { + WeakSegmentedCache cache = it.next().get(); + if (cache == null) { + it.remove(); + } else { + cache.drainCollected(); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/ChainNode.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ChainNode.java new file mode 100644 index 0000000..5989c4c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ChainNode.java @@ -0,0 +1,9 @@ +package com.modularmc.mmclutils.api.collection.cache; + +/** 分段哈希表的链式节点。重排时只修改后继引用。 */ +interface ChainNode> { + + N getNext(); + + void setNext(N next); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/ConcurrentWeakIdentityHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ConcurrentWeakIdentityHashMap.java new file mode 100644 index 0000000..96368be --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ConcurrentWeakIdentityHashMap.java @@ -0,0 +1,257 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.io.Serial; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * 支持并发访问的弱键映射。按对象身份比较键,键被回收后由后续访问清理对应的映射。 + * 值由映射强引用。值若持有其键,键会随值保持可达。 + * + * @param 非空键的类型 + * @param 非空值的类型 + */ +@NullMarked +public class ConcurrentWeakIdentityHashMap extends AbstractMap implements ConcurrentMap { + + private final ConcurrentMap, V> map; + private final ReferenceQueue queue = new ReferenceQueue<>(); + private transient @Nullable Set> entrySet; + + /** + * 按预计元素数量创建空映射。 + * + * @param initialCapacity 预计同时保存的键数量,须为非负数 + * @throws IllegalArgumentException 初始容量为负数 + */ + public ConcurrentWeakIdentityHashMap(int initialCapacity) { + this.map = new ConcurrentHashMap<>(initialCapacity); + } + + /** 使用并发映射的默认初始容量。 */ + public ConcurrentWeakIdentityHashMap() { + this.map = new ConcurrentHashMap<>(); + } + + @Override + public @Nullable V get(Object key) { + purgeKeys(); + return map.get(new Key<>(key, null)); + } + + @Override + public @Nullable V put(K key, V value) { + purgeKeys(); + return map.put(new Key<>(key, queue), value); + } + + @Override + public int size() { + purgeKeys(); + return map.size(); + } + + @SuppressWarnings({ "ReassignedVariable", "SuspiciousMethodCalls" }) + private void purgeKeys() { + Reference reference; + while ((reference = queue.poll()) != null) { + map.remove(reference); + } + } + + @Override + public Set> entrySet() { + Set> entrySet = this.entrySet; + return entrySet == null ? this.entrySet = new EntrySet() : entrySet; + } + + @Override + public @Nullable V putIfAbsent(K key, V value) { + purgeKeys(); + return map.putIfAbsent(new Key<>(key, queue), value); + } + + @Override + public @Nullable V remove(Object key) { + return map.remove(new Key<>(key, null)); + } + + @Override + public boolean remove(Object key, Object value) { + purgeKeys(); + return map.remove(new Key<>(key, null), value); + } + + @Override + public boolean replace(K key, V oldValue, V newValue) { + purgeKeys(); + return map.replace(new Key<>(key, null), oldValue, newValue); + } + + @Override + public @Nullable V replace(K key, V value) { + purgeKeys(); + return map.replace(new Key<>(key, null), value); + } + + @Override + public boolean containsKey(Object key) { + purgeKeys(); + return map.containsKey(new Key<>(key, null)); + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public void clear() { + while (queue.poll() != null); + map.clear(); + } + + @Override + public boolean containsValue(Object value) { + purgeKeys(); + return map.containsValue(value); + } + + private static class Key extends WeakReference { + + private final int hash; + + Key(T t, @Nullable ReferenceQueue queue) { + super(t, queue); + if (t == null) { + throw new NullPointerException("key"); + } + hash = System.identityHashCode(t); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + T value = get(); + return value != null && obj instanceof Key key && key.get() == value; + } + + @Override + public int hashCode() { + return hash; + } + } + + private class Iter implements Iterator> { + + private final Iterator, V>> it; + private Map.@Nullable Entry nextValue; + private @Nullable K lastKey; + + Iter(Iterator, V>> it) { + this.it = it; + } + + @Override + public boolean hasNext() { + if (nextValue != null) { + return true; + } + while (it.hasNext()) { + Map.Entry, V> entry = it.next(); + K key = entry.getKey().get(); + if (key != null) { + nextValue = new Entry(key, entry.getValue()); + return true; + } else { + it.remove(); + } + } + return false; + } + + @Override + public Map.Entry next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + Map.Entry entry = nextValue; + nextValue = null; + lastKey = entry.getKey(); + return entry; + } + + @Override + public void remove() { + if (lastKey == null) throw new IllegalStateException(); + ConcurrentWeakIdentityHashMap.this.remove(lastKey); + lastKey = null; + } + } + + private class EntrySet extends AbstractSet> { + + @Override + public Iterator> iterator() { + return new Iter(map.entrySet().iterator()); + } + + @Override + public int size() { + return ConcurrentWeakIdentityHashMap.this.size(); + } + + @Override + public void clear() { + ConcurrentWeakIdentityHashMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) { + return false; + } + return e.getValue() != null && ConcurrentWeakIdentityHashMap.this.get(e.getKey()) == e.getValue(); + } + + @Override + public boolean remove(Object o) { + if (!(o instanceof Map.Entry e)) { + return false; + } + return ConcurrentWeakIdentityHashMap.this.remove(e.getKey(), e.getValue()); + } + } + + private class Entry extends AbstractMap.SimpleEntry { + + @Serial + private static final long serialVersionUID = 1L; + + Entry(K key, V value) { + super(key, value); + } + + @Override + public V setValue(V value) { + ConcurrentWeakIdentityHashMap.this.put(getKey(), value); + return super.setValue(value); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Map.Entry e) { + return getKey() == e.getKey() && getValue() == e.getValue(); + } + return false; + } + + @Override + public int hashCode() { + return System.identityHashCode(getKey()) ^ System.identityHashCode(getValue()); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashCache.java new file mode 100644 index 0000000..ace3028 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashCache.java @@ -0,0 +1,218 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 按指定的哈希与相等策略保存强引用值。计算在分段锁外执行。 + * + * @param 缓存键类型 + * @param 缓存值类型 + */ +public final class CustomHashCache extends SegmentedCache> implements LoadingCache { + + private final Hash.Strategy strategy; + private final Function createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public CustomHashCache(Hash.Strategy strategy) { + this(strategy, SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public CustomHashCache(Hash.Strategy strategy, Function createFunction) { + this(strategy, SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 使用二的幂次容量和位掩码定位。 */ + public CustomHashCache(Hash.Strategy strategy, int concurrencyLevel) { + this(strategy, concurrencyLevel, null); + } + + /** 使用二的幂次容量和位掩码定位。 */ + public CustomHashCache(Hash.Strategy strategy, int concurrencyLevel, Function createFunction) { + super(concurrencyLevel, i -> new Segment<>(strategy)); + this.strategy = strategy; + this.createFunction = createFunction; + } + + @Override + public Function createFunction() { + return createFunction; + } + + @Override + public V getCache(final K k, Function createFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCache(K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction); + } + + @Override + public V getIfPresent(final K k) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getIfAbsent(k, hash, mix); + } + + @Override + public V putIfAbsent(final K k, final V v) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).put(k, v, hash, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + final static class Segment extends HashSegment> { + + private final Hash.Strategy strategy; + + private Segment(Hash.Strategy strategy) { + this.strategy = strategy; + } + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return node.hash; + } + + /** 在写锁内合并并发变更。 */ + private V getCache(final K k, final int hash, int mix, + Function createFunction, UnaryOperator keyMappingFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) { + return curr.value; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var mapped = keyMappingFunction.apply(k); + final var v = createFunction.apply(mapped); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = table[index]; + while (curr != null) { + if (curr.hash == hash && (mapped == curr.key || strategy.equals(mapped, curr.key))) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(mapped, v, hash, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final K k, final int hash, int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) { + return curr.value; + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private V put(final K k, final V v, final int hash, int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, hash, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final K key; + private final V value; + private final int hash; + private volatile Node next; + + private Node(K key, V value, int hash, Node next) { + this.key = key; + this.value = value; + this.hash = hash; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashInterner.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashInterner.java new file mode 100644 index 0000000..8d5311e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashInterner.java @@ -0,0 +1,181 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.UnaryOperator; + +/** + * 按调用方提供的哈希与相等策略驻留对象。驻留条目由该实例强引用。 + * + * @param 驻留对象类型 + */ +public final class CustomHashInterner extends SegmentedCache> implements Interner { + + private final Hash.Strategy strategy; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public CustomHashInterner(Hash.Strategy strategy) { + this(SegmentedCache.DEFAULT_CONCURRENCY, strategy); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public CustomHashInterner(int concurrencyLevel, Hash.Strategy strategy) { + super(concurrencyLevel, i -> new Segment<>(strategy)); + this.strategy = strategy; + } + + @Override + public T intern(final T sample) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).intern(sample, hash, mix, Interner.identityMappingFunction()); + } + + @Override + public T intern(T sample, UnaryOperator mappingFunction) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).intern(sample, hash, mix, mappingFunction); + } + + @Override + public boolean isPresent(final T sample) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).contains(sample, hash, mix); + } + + @Override + public boolean addIfAbsent(final T sample) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).add(sample, hash, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + final static class Segment extends HashSegment> { + + private final Hash.Strategy strategy; + + private Segment(Hash.Strategy strategy) { + this.strategy = strategy; + } + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return node.hash; + } + + /** 在写锁内合并并发变更。 */ + private T intern(final T k, final int hash, int mix, UnaryOperator mappingFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + var key = curr.key; + if (curr.hash == hash && (key == k || strategy.equals(k, key))) { + return key; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + final T v = mappingFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + var key = curr.key; + if (curr.hash == hash && (key == v || strategy.equals(v, key))) { + return key; + } + curr = curr.next; + } + table[index] = new Node<>(v, hash, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + private boolean contains(final T k, final int hash, int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.hash == hash && (curr.key == k || strategy.equals(k, curr.key))) { + return true; + } + curr = curr.next; + } + return false; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private boolean add(final T k, final int hash, int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (curr.hash == hash && (curr.key == k || strategy.equals(k, curr.key))) { + return false; + } + curr = curr.next; + } + table[index] = new Node<>(k, hash, node); + if (++size > maxFill) { + resize(); + } + return true; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final T key; + private final int hash; + private volatile Node next; + + private Node(T key, int hash, Node next) { + this.key = key; + this.hash = hash; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/DoubleCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/DoubleCache.java new file mode 100644 index 0000000..2d81d63 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/DoubleCache.java @@ -0,0 +1,182 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.DoubleFunction; + +/** + * 使用原始类型 {@code double} 作为键,强引用缓存值,直到缓存条目被清除。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * 浮点键区分正负零,同一类型的 NaN 使用相同的键。 + * + * @param 缓存值类型 + */ +public final class DoubleCache extends SegmentedCache> { + + private final DoubleFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public DoubleCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public DoubleCache(DoubleFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public DoubleCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public DoubleCache(int concurrencyLevel, DoubleFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final double k) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final double k, DoubleFunction createFunction) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final double k) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 只在没有有效值时写入,返回最终关联的值。 */ + public V putIfAbsent(final double k, final V v) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + static final class Segment extends HashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return Long.hashCode(Double.doubleToLongBits(node.key)); + } + + /** 在写锁内合并并发变更。 */ + private V getCache(final double k, final int mix, DoubleFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + return curr.value; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, table[index]); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final double k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + return curr.value; + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private V put(final double k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final double key; + private final V value; + private volatile Node next; + + private Node(double key, V value, Node next) { + this.key = key; + this.value = value; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/FloatCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/FloatCache.java new file mode 100644 index 0000000..00ba8ff --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/FloatCache.java @@ -0,0 +1,181 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.floats.Float2ObjectFunction; + +/** + * 使用原始类型 {@code float} 作为键,强引用缓存值,直到缓存条目被清除。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * 浮点键区分正负零,同一类型的 NaN 使用相同的键。 + * + * @param 缓存值类型 + */ +public final class FloatCache extends SegmentedCache> { + + private final Float2ObjectFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public FloatCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public FloatCache(Float2ObjectFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public FloatCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public FloatCache(int concurrencyLevel, Float2ObjectFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final float k) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final float k, Float2ObjectFunction createFunction) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final float k) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 只在没有有效值时写入,返回最终关联的值。 */ + public V putIfAbsent(final float k, final V v) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + static final class Segment extends HashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return Float.floatToIntBits(node.key); + } + + /** 在写锁内合并并发变更。 */ + private V getCache(final float k, final int mix, Float2ObjectFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + return curr.value; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.get(k); + stamp = writeLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, table[index]); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final float k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + return curr.value; + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private V put(final float k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final float key; + private final V value; + private volatile Node next; + + private Node(float key, V value, Node next) { + this.key = key; + this.value = value; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashCache.java new file mode 100644 index 0000000..499bf81 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashCache.java @@ -0,0 +1,90 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 按键的值相等性保存强引用值。计算依赖同一缓存内的其他键时使用递归加载入口。 + * + * @param 缓存键类型 + * @param 缓存值类型 + */ +public final class HashCache implements LoadingCache { + + private final ConcurrentHashMap map; + private final Function createFunction; + + /** 使用键的相等性创建无默认加载器的缓存。缺失值可由调用处提供加载函数。 */ + public HashCache() { + this(null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public HashCache(Function createFunction) { + this.map = new ConcurrentHashMap<>(); + this.createFunction = createFunction; + } + + @Override + public Function createFunction() { + return createFunction; + } + + @Override + public V getCache(final K k, Function createFunction) { + return map.computeIfAbsent(k, createFunction); + } + + @Override + public V getCache(final K k, Function createFunction, UnaryOperator keyMappingFunction) { + V v = map.get(k); + if (v != null) { + return v; + } + K mapped = keyMappingFunction.apply(k); + v = createFunction.apply(mapped); + V prev = map.putIfAbsent(mapped, v); + return prev == null ? v : prev; + } + + @Override + public V getCacheRecursive(final K k, Function createFunction) { + V v = map.get(k); + if (v != null) { + return v; + } + + v = createFunction.apply(k); + V prev = map.putIfAbsent(k, v); + return prev == null ? v : prev; + } + + @Override + public V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction) { + V v = map.get(k); + if (v != null) { + return v; + } + K mapped = keyMappingFunction.apply(k); + v = createFunction.apply(mapped); + V prev = map.putIfAbsent(mapped, v); + return prev == null ? v : prev; + } + + @Override + public V getIfPresent(final K k) { + return map.get(k); + } + + @Override + public V putIfAbsent(final K k, final V v) { + V prev = map.putIfAbsent(k, v); + return prev == null ? v : prev; + } + + @Override + public void clear() { + map.clear(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashInterner.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashInterner.java new file mode 100644 index 0000000..20b99ec --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashInterner.java @@ -0,0 +1,52 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 按值相等性驻留对象。驻留条目由该实例强引用。 + * + * @param 驻留对象类型 + */ +public final class HashInterner implements Interner { + + private final ConcurrentHashMap map; + private final Function function = Function.identity(); + + /** 按值的相等性创建驻留表,已登记者保留强引用。 */ + public HashInterner() { + this.map = new ConcurrentHashMap<>(); + } + + @Override + public T intern(final T sample) { + return map.computeIfAbsent(sample, function); + } + + @Override + public T intern(T sample, UnaryOperator mappingFunction) { + var v = map.get(sample); + if (v != null) { + return v; + } + v = mappingFunction.apply(sample); + var prev = map.putIfAbsent(v, v); + return prev == null ? v : prev; + } + + @Override + public boolean isPresent(final T sample) { + return map.containsKey(sample); + } + + @Override + public boolean addIfAbsent(final T sample) { + return map.putIfAbsent(sample, sample) == null; + } + + @Override + public void clear() { + map.clear(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashSegment.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashSegment.java new file mode 100644 index 0000000..a7280bc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashSegment.java @@ -0,0 +1,91 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.Arrays; +import java.util.concurrent.locks.StampedLock; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; + +/** 分段缓存中的拉链哈希表,读写由此分段自己的锁保护。 */ +abstract class HashSegment> extends StampedLock { + + protected volatile N[] table; + protected volatile int mask; + protected volatile int size; + protected volatile int maxFill; + + protected HashSegment() { + int n = arraySize(Hash.DEFAULT_INITIAL_SIZE, Hash.DEFAULT_LOAD_FACTOR); + this.table = newArray(n); + this.mask = n - 1; + this.maxFill = (int) (n * Hash.DEFAULT_LOAD_FACTOR); + } + + protected abstract int nodeHash(N node); + + protected abstract N[] newArray(int capacity); + + /** 在写锁内合并并发变更。 */ + protected final void resize() { + N[] oldTab = this.table; + int oldCap = oldTab.length; + int newCap = oldCap << 1; + N[] newTab = newArray(newCap); + int newMask = newCap - 1; + for (int i = 0; i < oldCap; ++i) { + N e; + if ((e = oldTab[i]) != null) { + oldTab[i] = null; + if (e.getNext() == null) { + newTab[HashCommon.mix(nodeHash(e)) & newMask] = e; + } else { + N loHead = null, loTail = null; + N hiHead = null, hiTail = null; + N next; + do { + next = e.getNext(); + if ((HashCommon.mix(nodeHash(e)) & oldCap) == 0) { + if (loTail == null) + loHead = e; + else + loTail.setNext(e); + loTail = e; + } else { + if (hiTail == null) + hiHead = e; + else + hiTail.setNext(e); + hiTail = e; + } + } while ((e = next) != null); + if (loTail != null) { + loTail.setNext(null); + newTab[HashCommon.mix(nodeHash(loHead)) & newMask] = loHead; + } + if (hiTail != null) { + hiTail.setNext(null); + newTab[HashCommon.mix(nodeHash(hiHead)) & newMask] = hiHead; + } + } + } + } + this.table = newTab; + this.mask = newMask; + this.maxFill = (int) (newCap * Hash.DEFAULT_LOAD_FACTOR); + } + + /** 在写锁内合并并发变更。 */ + protected void clear() { + long stamp = writeLock(); + try { + if (size != 0) { + size = 0; + Arrays.fill(table, null); + } + } finally { + unlockWrite(stamp); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/IdentityHashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/IdentityHashCache.java new file mode 100644 index 0000000..56fcbed --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/IdentityHashCache.java @@ -0,0 +1,207 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 按键的引用身份保存强引用值。计算在分段锁外执行。 + * + * @param 缓存键类型 + * @param 缓存值类型 + */ +public final class IdentityHashCache extends SegmentedCache> implements LoadingCache { + + private final Function createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public IdentityHashCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public IdentityHashCache(Function createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public IdentityHashCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public IdentityHashCache(int concurrencyLevel, Function createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + this.createFunction = createFunction; + } + + @Override + public Function createFunction() { + return createFunction; + } + + @Override + public V getCache(final K k, Function createFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCache(K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, keyMappingFunction); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, keyMappingFunction); + } + + @Override + public V getIfPresent(final K k) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getIfAbsent(k, mix); + } + + @Override + public V putIfAbsent(final K k, final V v) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).put(k, v, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + final static class Segment extends HashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return System.identityHashCode(node.key); + } + + /** 在写锁内合并并发变更。 */ + private V getCache(final K k, final int mix, Function createFunction, UnaryOperator keyMappingFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var mapped = keyMappingFunction.apply(k); + final var v = createFunction.apply(mapped); + stamp = writeLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.key == mapped) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(mapped, v, table[index]); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final K k, final int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private V put(final K k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final K key; + private final V value; + private volatile Node next; + + private Node(K key, V value, Node next) { + this.key = key; + this.value = value; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/IntCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/IntCache.java new file mode 100644 index 0000000..63c56ac --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/IntCache.java @@ -0,0 +1,181 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.IntFunction; + +/** + * 使用原始类型 {@code int} 作为键,强引用缓存值,直到缓存条目被清除。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * + * @param 缓存值类型 + */ +public final class IntCache extends SegmentedCache> { + + private final IntFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public IntCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public IntCache(IntFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public IntCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public IntCache(int concurrencyLevel, IntFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final int k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final int k, IntFunction createFunction) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final int k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 只在没有有效值时写入,返回最终关联的值。 */ + public V putIfAbsent(final int k, final V v) { + int mix = HashCommon.mix(k); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + static final class Segment extends HashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return node.key; + } + + /** 在写锁内合并并发变更。 */ + private V getCache(final int k, final int mix, IntFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, table[index]); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final int k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private V put(final int k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final int key; + private final V value; + private volatile Node next; + + private Node(int key, V value, Node next) { + this.key = key; + this.value = value; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/Interner.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/Interner.java new file mode 100644 index 0000000..34967fe --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/Interner.java @@ -0,0 +1,62 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.util.function.UnaryOperator; + +/** + * 按相等关系或指定策略合并对象实例,方便调用方复用不可变值。 + * 参与比较和哈希的对象状态在驻留期间须保持稳定。弱引用实现允许无外部引用的实例被回收。 + * + * @param 可驻留的对象类型 + */ +public interface Interner { + + /** 共享的原样返回函数。 */ + UnaryOperator IDENTITY_OPERATOR = UnaryOperator.identity(); + + /** + * 返回将输入原样用作驻留实例的函数。 + * + * @param 驻留对象类型 + * @return 原样返回函数 + */ + @SuppressWarnings("unchecked") + static UnaryOperator identityMappingFunction() { + return (UnaryOperator) IDENTITY_OPERATOR; + } + + /** + * 查找与样本等价的驻留实例,缺失时登记样本。 + * + * @param sample 用于查找的非空样本 + * @return 该等价类的共享实例 + */ + T intern(final T sample); + + /** + * 查找与样本等价的实例,缺失时允许调用方用复制品参与驻留。 + * + * @param sample 用于查找的非空样本 + * @param mappingFunction 生成非空实例的函数,结果须与样本等价并使用相同哈希 + * @return 该等价类的共享实例 + */ + T intern(final T sample, UnaryOperator mappingFunction); + + /** + * 查询是否已有与样本等价且仍可访问的实例。 + * + * @param sample 用于查找的非空样本 + * @return 存在可用驻留实例时为真 + */ + boolean isPresent(final T sample); + + /** + * 仅在缺少等价实例时登记样本。 + * + * @param sample 供驻留的非空样本 + * @return 本次操作登记了样本时为真 + */ + boolean addIfAbsent(final T sample); + + /** 清除当前驻留记录。调用方此前取得的实例可继续使用。 */ + void clear(); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/LoadingCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/LoadingCache.java new file mode 100644 index 0000000..efc3443 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/LoadingCache.java @@ -0,0 +1,101 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 以统一接口访问相等键、身份键或自定义策略的加载缓存。实现可以强引用或弱引用值。 + * 并发查找可能同时计算同一个缺失值。供多个线程共享的计算函数应允许并发调用。 + * + * @param 缓存键类型 + * @param 缓存值类型 + */ +public interface LoadingCache { + + /** + * 查找键,缺失时计算值并尝试写入。计算依赖其他键时使用 {@link #getCacheRecursive(Object, Function)}。 + * + * @param k 要查找的键 + * @param createFunction 缓存未命中时使用的计算函数 + * @return 本次查找或写入取得的值 + */ + V getCache(final K k, Function createFunction); + + /** + * 查找原键,缺失时将键转换为可保留的形式,再用于计算和写入。 + * + * @param k 用于首次查找的键 + * @param createFunction 用转换后的键计算值的函数 + * @param keyMappingFunction 转换键的函数,须保留当前缓存策略中的等价关系 + * @return 本次查找或写入取得的值 + */ + V getCache(final K k, Function createFunction, UnaryOperator keyMappingFunction); + + /** + * 查找或计算缓存值。计算函数在写入操作之外运行,可在计算时访问同一缓存的其他键。 + * + * @param k 要查找的键 + * @param createFunction 缓存未命中时使用的计算函数,调用方负责避免循环依赖 + * @return 本次查找或写入取得的值 + */ + V getCacheRecursive(final K k, Function createFunction); + + /** + * 查找原键,缺失时使用转换后的键执行可访问其他键的计算。 + * + * @param k 用于首次查找的键 + * @param createFunction 可访问同一缓存中其他键的计算函数 + * @param keyMappingFunction 转换键的函数,须保留当前缓存策略中的等价关系 + * @return 本次查找或写入取得的值 + */ + V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction); + + /** + * 获取构建缓存时配置的默认计算函数。 + * + * @return 默认计算函数,构建时未配置则为空 + */ + default Function createFunction() { + return null; + } + + /** + * 使用默认计算函数查找或填充缓存。使用此重载前须配置默认函数。 + * + * @param k 要查找的键 + * @return 本次查找或写入取得的值 + */ + default V getCache(final K k) { + return getCache(k, createFunction()); + } + + /** + * 使用已配置的默认函数查找或填充缓存,允许计算时查找其他键。 + * + * @param k 要查找的键 + * @return 本次查找或写入取得的值 + */ + default V getCacheRecursive(final K k) { + return getCacheRecursive(k, createFunction()); + } + + /** + * 读取已有条目,无需配置计算函数。 + * + * @param k 要查找的键 + * @return 已关联的值,键缺失或弱引用值已回收时为空 + */ + V getIfPresent(final K k); + + /** + * 仅在键没有可用值时写入给定值。 + * + * @param k 要写入的键 + * @param v 要关联的非空值 + * @return 本次操作观察到的已有值或本次写入的值 + */ + V putIfAbsent(final K k, final V v); + + /** 清除当前缓存项。与清除并行的计算仍可能写入新值。 */ + void clear(); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/LongCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/LongCache.java new file mode 100644 index 0000000..dea70ba --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/LongCache.java @@ -0,0 +1,181 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.LongFunction; + +/** + * 使用原始类型 {@code long} 作为键,强引用缓存值,直到缓存条目被清除。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * + * @param 缓存值类型 + */ +public final class LongCache extends SegmentedCache> { + + private final LongFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public LongCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public LongCache(LongFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public LongCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public LongCache(int concurrencyLevel, LongFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final long k) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final long k, LongFunction createFunction) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final long k) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 只在没有有效值时写入,返回最终关联的值。 */ + public V putIfAbsent(final long k, final V v) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + static final class Segment extends HashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return Long.hashCode(node.key); + } + + /** 在写锁内合并并发变更。 */ + private V getCache(final long k, final int mix, LongFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, table[index]); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final long k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private V put(final long k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + return curr.value; + } + curr = curr.next; + } + table[index] = new Node<>(k, v, node); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node implements ChainNode> { + + private final long key; + private final V value; + private volatile Node next; + + private Node(long key, V value, Node next) { + this.key = key; + this.value = value; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/ReclaimableCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ReclaimableCache.java new file mode 100644 index 0000000..4e83472 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ReclaimableCache.java @@ -0,0 +1,7 @@ +package com.modularmc.mmclutils.api.collection.cache; + +/** 弱引用缓存向清理线程提供的回收入口。 */ +interface ReclaimableCache { + + void clearCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/SegmentedCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/SegmentedCache.java new file mode 100644 index 0000000..f32de43 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/SegmentedCache.java @@ -0,0 +1,51 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.util.function.IntFunction; + +/** 以二的幂次分段索引,多个线程可并行访问不同分段。 */ +abstract class SegmentedCache> { + + static final int DEFAULT_CONCURRENCY = Runtime.getRuntime().availableProcessors(); + + /** 构造时一次性创建的分段。散列计算决定键由哪一段存储。 */ + protected final SEG[] segments; + private final int segmentShift; + private final int segmentMask; + + /** 并发度必须大于零。 */ + @SuppressWarnings("unchecked") + protected SegmentedCache(int concurrencyLevel, IntFunction segmentFactory) { + if (concurrencyLevel <= 0) throw new IllegalArgumentException("concurrencyLevel must be positive"); + int ssize = 1; + while (ssize < concurrencyLevel) { + ssize <<= 1; + } + this.segmentShift = 32 - Integer.numberOfTrailingZeros(ssize); + this.segmentMask = ssize - 1; + this.segments = (SEG[]) new HashSegment[ssize]; + for (int i = 0; i < ssize; i++) { + segments[i] = segmentFactory.apply(i); + } + } + + /** 使用混合后的哈希选择对应分段。 */ + protected final SEG segmentFor(int mix) { + return segments[(mix >>> segmentShift) & segmentMask]; + } + + /** 逐段移除全部条目。并发写入期间各段独立清理。 */ + protected final void clearSegments() { + for (var segment : segments) { + segment.clear(); + } + } + + /** 统计各分段条目数,并发修改时返回各段读取结果的合计。 */ + public final int size() { + int total = 0; + for (var segment : segments) { + total += segment.size; + } + return total; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakCustomHashInterner.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakCustomHashInterner.java new file mode 100644 index 0000000..9b284de --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakCustomHashInterner.java @@ -0,0 +1,193 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.UnaryOperator; + +/** + * 按调用方提供的哈希与相等策略驻留对象。没有外部强引用的驻留实例可被回收。 + * + * @param 驻留对象类型 + */ +public final class WeakCustomHashInterner extends WeakSegmentedCache> implements Interner, ReclaimableCache { + + private final Hash.Strategy strategy; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakCustomHashInterner(Hash.Strategy strategy) { + this(SegmentedCache.DEFAULT_CONCURRENCY, strategy); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakCustomHashInterner(int concurrencyLevel, Hash.Strategy strategy) { + super(concurrencyLevel, i -> new Segment<>(strategy)); + CacheReferenceQueue.add(this); + this.strategy = strategy; + } + + @Override + public T intern(final T sample) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).intern(sample, hash, mix, Interner.identityMappingFunction()); + } + + @Override + public T intern(T sample, UnaryOperator mappingFunction) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).intern(sample, hash, mix, mappingFunction); + } + + @Override + public boolean isPresent(final T sample) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).contains(sample, hash, mix); + } + + @Override + public boolean addIfAbsent(final T sample) { + int hash = strategy.hashCode(sample); + int mix = HashCommon.mix(hash); + return segmentFor(mix).add(sample, hash, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + final static class Segment extends WeakHashSegment> { + + private final Hash.Strategy strategy; + + private Segment(Hash.Strategy strategy) { + this.strategy = strategy; + } + + @Override + @SuppressWarnings("unchecked") + protected WeakReferenceNode[] newArray(int capacity) { + return new WeakReferenceNode[capacity]; + } + + @Override + protected int nodeHash(WeakReferenceNode node) { + return node.hash; + } + + /** 在写锁内合并并发变更。 */ + private T intern(final T k, final int hash, int mix, UnaryOperator mappingFunction) { + long stamp = readLock(); + try { + WeakReferenceNode curr = table[mix & mask]; + while (curr != null) { + T key = curr.get(); + if (key != null && curr.hash == hash && (key == k || strategy.equals(k, key))) { + return key; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + final T v = mappingFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + WeakReferenceNode node = table[index]; + WeakReferenceNode prev = null; + WeakReferenceNode curr = node; + while (curr != null) { + T key = curr.get(); + if (key == null) { + if (prev == null) { + node = curr.next; + table[index] = node; + } else { + prev.next = curr.next; + } + size--; + } else { + if (curr.hash == hash && (key == v || strategy.equals(v, key))) { + return key; + } + prev = curr; + } + curr = curr.next; + } + table[index] = new WeakReferenceNode<>(v, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + private boolean contains(final T k, final int hash, int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + WeakReferenceNode curr = table[index]; + while (curr != null) { + T key = curr.get(); + // 替换已被回收的节点,保留原键所在的链位置。 + + if (key != null && curr.hash == hash && (key == k || strategy.equals(k, key))) { + return true; + } + curr = curr.next; + } + return false; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private boolean add(final T k, final int hash, int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + WeakReferenceNode node = table[index]; + WeakReferenceNode prev = null; + WeakReferenceNode curr = node; + while (curr != null) { + T key = curr.get(); + if (key == null) { + if (prev == null) { + node = curr.next; + table[index] = node; + } else { + prev.next = curr.next; + } + size--; + } else { + if (curr.hash == hash && (key == k || strategy.equals(k, key))) { + return false; + } + prev = curr; + } + curr = curr.next; + } + table[index] = new WeakReferenceNode<>(k, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return true; + } finally { + unlockWrite(stamp); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakHashInterner.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakHashInterner.java new file mode 100644 index 0000000..7698c15 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakHashInterner.java @@ -0,0 +1,184 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.UnaryOperator; + +/** + * 按值相等性驻留对象。没有外部强引用的驻留实例可被回收。 + * + * @param 驻留对象类型 + */ +public final class WeakHashInterner extends WeakSegmentedCache> implements Interner, ReclaimableCache { + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakHashInterner() { + this(SegmentedCache.DEFAULT_CONCURRENCY); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakHashInterner(int concurrencyLevel) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + } + + @Override + public T intern(final T sample) { + int hash = sample.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).intern(sample, hash, mix, Interner.identityMappingFunction()); + } + + @Override + public T intern(T sample, UnaryOperator mappingFunction) { + int hash = sample.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).intern(sample, hash, mix, mappingFunction); + } + + @Override + public boolean isPresent(final T sample) { + int hash = sample.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).contains(sample, hash, mix); + } + + @Override + public boolean addIfAbsent(final T sample) { + int hash = sample.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).add(sample, hash, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + final static class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected WeakReferenceNode[] newArray(int capacity) { + return new WeakReferenceNode[capacity]; + } + + @Override + protected int nodeHash(WeakReferenceNode node) { + return node.hash; + } + + /** 在写锁内合并并发变更。 */ + private T intern(final T k, final int hash, int mix, UnaryOperator mappingFunction) { + long stamp = readLock(); + try { + WeakReferenceNode curr = table[mix & mask]; + while (curr != null) { + T key = curr.get(); + if (key != null && curr.hash == hash && (key == k || k.equals(key))) { + return key; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + final T v = mappingFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + WeakReferenceNode node = table[index]; + WeakReferenceNode prev = null; + WeakReferenceNode curr = node; + while (curr != null) { + T key = curr.get(); + if (key == null) { + if (prev == null) { + node = curr.next; + table[index] = node; + } else { + prev.next = curr.next; + } + size--; + } else { + if (curr.hash == hash && (key == v || v.equals(key))) { + return key; + } + prev = curr; + } + curr = curr.next; + } + table[index] = new WeakReferenceNode<>(v, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + private boolean contains(final T k, final int hash, int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + WeakReferenceNode curr = table[index]; + while (curr != null) { + T key = curr.get(); + // 替换已被回收的节点,保留原键所在的链位置。 + + if (key != null && curr.hash == hash && (key == k || k.equals(key))) { + return true; + } + curr = curr.next; + } + return false; + } finally { + unlockRead(stamp); + } + } + + /** 只在缺少该键时写入。 */ + private boolean add(final T k, final int hash, int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + WeakReferenceNode node = table[index]; + WeakReferenceNode prev = null; + WeakReferenceNode curr = node; + while (curr != null) { + T key = curr.get(); + if (key == null) { + if (prev == null) { + node = curr.next; + table[index] = node; + } else { + prev.next = curr.next; + } + size--; + } else { + if (curr.hash == hash && (key == k || k.equals(key))) { + return false; + } + prev = curr; + } + curr = curr.next; + } + table[index] = new WeakReferenceNode<>(k, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return true; + } finally { + unlockWrite(stamp); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakHashSegment.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakHashSegment.java new file mode 100644 index 0000000..1b1db9a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakHashSegment.java @@ -0,0 +1,103 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.util.Arrays; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; + +/** 记录弱引用节点并处理回收。命中的键可复用原有节点位置。 */ +abstract class WeakHashSegment> extends HashSegment { + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private static final int BACKGROUND_BATCH = 10000; + + protected final ReferenceQueue queue = new ReferenceQueue<>(); + + protected WeakHashSegment() { + int n = arraySize(Hash.DEFAULT_INITIAL_SIZE, Hash.DEFAULT_LOAD_FACTOR); + this.table = newArray(n); + this.mask = n - 1; + this.maxFill = (int) (n * Hash.DEFAULT_LOAD_FACTOR); + } + + /** 在写锁内合并并发变更。 */ + protected final void clear() { + long stamp = writeLock(); + try { + if (size != 0) { + size = 0; + Arrays.fill(table, null); + } + while (queue.poll() != null) { + // 更新链表链接并保持探测顺序。 + } + } finally { + unlockWrite(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + @SuppressWarnings("unchecked") + private int expungeLocked(int limit) { + int processed = 0; + Reference ref; + while (processed < limit && (ref = queue.poll()) != null) { + unlink((N) ref); + processed++; + } + return processed; + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + @SuppressWarnings("unchecked") + final void expunge() { + int processed = BACKGROUND_BATCH; + while (processed == BACKGROUND_BATCH) { + Reference first = queue.poll(); + if (first == null) { + return; + } + long stamp = writeLock(); + try { + unlink((N) first); + processed = 1 + expungeLocked(BACKGROUND_BATCH - 1); + } finally { + unlockWrite(stamp); + } + } + } + + /** 在写锁内合并并发变更。 */ + final void expungeAll() { + long stamp = writeLock(); + try { + expungeLocked(Integer.MAX_VALUE); + } finally { + unlockWrite(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private void unlink(N node) { + int index = HashCommon.mix(nodeHash(node)) & mask; + N prev = null; + N curr = table[index]; + while (curr != null) { + if (curr == node) { + if (prev == null) { + table[index] = curr.getNext(); + } else { + prev.setNext(curr.getNext()); + } + size--; + return; + } + prev = curr; + curr = curr.getNext(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakReferenceNode.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakReferenceNode.java new file mode 100644 index 0000000..81c9f3c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakReferenceNode.java @@ -0,0 +1,27 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; + +/** 调整开放寻址探测链。 */ +final class WeakReferenceNode extends WeakReference implements ChainNode> { + + final int hash; + volatile WeakReferenceNode next; + + WeakReferenceNode(T value, int hash, WeakReferenceNode next, ReferenceQueue queue) { + super(value, queue); + this.hash = hash; + this.next = next; + } + + @Override + public WeakReferenceNode getNext() { + return next; + } + + @Override + public void setNext(WeakReferenceNode next) { + this.next = next; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakReferenceValueNode.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakReferenceValueNode.java new file mode 100644 index 0000000..32640b2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakReferenceValueNode.java @@ -0,0 +1,29 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; + +/** 更新链表链接并保持探测顺序。 */ +final class WeakReferenceValueNode extends WeakReference implements ChainNode> { + + final K key; + final int hash; + volatile WeakReferenceValueNode next; + + WeakReferenceValueNode(K key, V value, int hash, WeakReferenceValueNode next, ReferenceQueue queue) { + super(value, queue); + this.key = key; + this.hash = hash; + this.next = next; + } + + @Override + public WeakReferenceValueNode getNext() { + return next; + } + + @Override + public void setNext(WeakReferenceValueNode next) { + this.next = next; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakSegmentedCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakSegmentedCache.java new file mode 100644 index 0000000..91fa8b5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakSegmentedCache.java @@ -0,0 +1,28 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import java.util.function.IntFunction; + +/** 在分段缓存上统一分发弱引用回收通知。 */ +abstract class WeakSegmentedCache> extends SegmentedCache { + + /** 并发度必须大于零。 */ + protected WeakSegmentedCache(int concurrencyLevel, IntFunction segmentFactory) { + super(concurrencyLevel, segmentFactory); + } + + /** 在写锁内合并并发变更。 */ + protected final void expungeStaleEntries() { + HashSegment[] segments = this.segments; + for (var segment : segments) { + ((WeakHashSegment) segment).expungeAll(); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + final void drainCollected() { + HashSegment[] segments = this.segments; + for (var segment : segments) { + ((WeakHashSegment) segment).expunge(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueByteCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueByteCache.java new file mode 100644 index 0000000..01f3d81 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueByteCache.java @@ -0,0 +1,216 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.bytes.Byte2ObjectFunction; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; + +/** + * 使用原始类型 {@code byte} 作为键,弱引用缓存值。值失去外部强引用后,后续查找可能重新创建。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * + * @param 缓存值类型 + */ +public final class WeakValueByteCache extends WeakSegmentedCache> implements ReclaimableCache { + + private final Byte2ObjectFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueByteCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueByteCache(Byte2ObjectFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueByteCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueByteCache(int concurrencyLevel, Byte2ObjectFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final byte k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final byte k, Byte2ObjectFunction createFunction) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final byte k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + public V putIfAbsent(final byte k, final V v) { + int mix = HashCommon.mix(k); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + static final class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return node.key; + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final byte k, final int mix, Byte2ObjectFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.get(k); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final byte k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final byte k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node extends WeakReference implements ChainNode> { + + private final byte key; + private volatile Node next; + + private Node(byte key, V value, Node next, ReferenceQueue queue) { + super(value, queue); + this.key = key; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueCustomHashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueCustomHashCache.java new file mode 100644 index 0000000..47fad43 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueCustomHashCache.java @@ -0,0 +1,226 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 按指定的哈希与相等策略保存弱引用值。值失去外部强引用后可回收。 + * + * @param 缓存键类型 + * @param 缓存值类型 + */ +public final class WeakValueCustomHashCache extends WeakSegmentedCache> implements LoadingCache, ReclaimableCache { + + private final Hash.Strategy strategy; + private final Function createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueCustomHashCache(Hash.Strategy strategy) { + this(strategy, SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueCustomHashCache(Hash.Strategy strategy, Function createFunction) { + this(strategy, SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueCustomHashCache(Hash.Strategy strategy, int concurrencyLevel) { + this(strategy, concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueCustomHashCache(Hash.Strategy strategy, int concurrencyLevel, Function createFunction) { + super(concurrencyLevel, i -> new Segment<>(strategy)); + CacheReferenceQueue.add(this); + this.strategy = strategy; + this.createFunction = createFunction; + } + + @Override + public Function createFunction() { + return createFunction; + } + + @Override + public V getCache(final K k, Function createFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCache(K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction); + } + + @Override + public V getIfPresent(final K k) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getIfAbsent(k, hash, mix); + } + + @Override + public V putIfAbsent(final K k, final V v) { + int hash = strategy.hashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).put(k, v, hash, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + final static class Segment extends WeakHashSegment> { + + private final Hash.Strategy strategy; + + private Segment(Hash.Strategy strategy) { + this.strategy = strategy; + } + + @Override + @SuppressWarnings("unchecked") + protected WeakReferenceValueNode[] newArray(int capacity) { + return new WeakReferenceValueNode[capacity]; + } + + @Override + protected int nodeHash(WeakReferenceValueNode node) { + return node.hash; + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final K k, final int hash, int mix, + Function createFunction, UnaryOperator keyMappingFunction) { + long stamp = readLock(); + try { + WeakReferenceValueNode curr = table[mix & mask]; + while (curr != null) { + if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var mapped = keyMappingFunction.apply(k); + final var v = createFunction.apply(mapped); + stamp = writeLock(); + try { + final int index = mix & mask; + final WeakReferenceValueNode node = table[index]; + WeakReferenceValueNode prev = null; + WeakReferenceValueNode curr = node; + while (curr != null) { + if (curr.hash == hash && (mapped == curr.key || strategy.equals(mapped, curr.key))) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new WeakReferenceValueNode<>(mapped, v, hash, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new WeakReferenceValueNode<>(mapped, v, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final K k, final int hash, int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + WeakReferenceValueNode curr = table[index]; + while (curr != null) { + if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final K k, final V v, final int hash, int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final WeakReferenceValueNode node = table[index]; + WeakReferenceValueNode prev = null; + WeakReferenceValueNode curr = node; + while (curr != null) { + if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new WeakReferenceValueNode<>(k, v, hash, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new WeakReferenceValueNode<>(k, v, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueDoubleCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueDoubleCache.java new file mode 100644 index 0000000..6ea16a5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueDoubleCache.java @@ -0,0 +1,217 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.function.DoubleFunction; + +/** + * 使用原始类型 {@code double} 作为键,弱引用缓存值。值失去外部强引用后,后续查找可能重新创建。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * 浮点键区分正负零,同一类型的 NaN 使用相同的键。 + * + * @param 缓存值类型 + */ +public final class WeakValueDoubleCache extends WeakSegmentedCache> implements ReclaimableCache { + + private final DoubleFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueDoubleCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueDoubleCache(DoubleFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueDoubleCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueDoubleCache(int concurrencyLevel, DoubleFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final double k) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final double k, DoubleFunction createFunction) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final double k) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + public V putIfAbsent(final double k, final V v) { + int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k))); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + static final class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return Long.hashCode(Double.doubleToLongBits(node.key)); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final double k, final int mix, DoubleFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final double k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final double k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node extends WeakReference implements ChainNode> { + + private final double key; + private volatile Node next; + + private Node(double key, V value, Node next, ReferenceQueue queue) { + super(value, queue); + this.key = key; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueFloatCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueFloatCache.java new file mode 100644 index 0000000..2c4661b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueFloatCache.java @@ -0,0 +1,217 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.floats.Float2ObjectFunction; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; + +/** + * 使用原始类型 {@code float} 作为键,弱引用缓存值。值失去外部强引用后,后续查找可能重新创建。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * 浮点键区分正负零,同一类型的 NaN 使用相同的键。 + * + * @param 缓存值类型 + */ +public final class WeakValueFloatCache extends WeakSegmentedCache> implements ReclaimableCache { + + private final Float2ObjectFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueFloatCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueFloatCache(Float2ObjectFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueFloatCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueFloatCache(int concurrencyLevel, Float2ObjectFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final float k) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final float k, Float2ObjectFunction createFunction) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final float k) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + public V putIfAbsent(final float k, final V v) { + int mix = HashCommon.mix(Float.floatToIntBits(k)); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + static final class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return Float.floatToIntBits(node.key); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final float k, final int mix, Float2ObjectFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.get(k); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final float k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final float k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node extends WeakReference implements ChainNode> { + + private final float key; + private volatile Node next; + + private Node(float key, V value, Node next, ReferenceQueue queue) { + super(value, queue); + this.key = key; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueHashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueHashCache.java new file mode 100644 index 0000000..ed5bd44 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueHashCache.java @@ -0,0 +1,218 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 按键的值相等性保存弱引用值。值失去外部强引用后可回收。 + * + * @param 缓存键类型 + * @param 缓存值类型 + */ +public final class WeakValueHashCache extends WeakSegmentedCache> implements LoadingCache, ReclaimableCache { + + private final Function createFunction; + + /** 以默认并发级别创建弱值缓存,缺失值由调用处提供加载函数。 */ + public WeakValueHashCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueHashCache(Function createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 以指定并发级别创建弱值缓存。键按相等性索引,值允许被垃圾回收。 */ + public WeakValueHashCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueHashCache(int concurrencyLevel, Function createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + this.createFunction = createFunction; + } + + @Override + public Function createFunction() { + return createFunction; + } + + @Override + public V getCache(final K k, Function createFunction) { + int hash = k.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCache(K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = k.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction) { + int hash = k.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = k.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction); + } + + @Override + public V getIfPresent(final K k) { + int hash = k.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getIfAbsent(k, hash, mix); + } + + @Override + public V putIfAbsent(final K k, final V v) { + int hash = k.hashCode(); + int mix = HashCommon.mix(hash); + return segmentFor(mix).put(k, v, hash, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + final static class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected WeakReferenceValueNode[] newArray(int capacity) { + return new WeakReferenceValueNode[capacity]; + } + + @Override + protected int nodeHash(WeakReferenceValueNode node) { + return node.hash; + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final K k, final int hash, int mix, + Function createFunction, UnaryOperator keyMappingFunction) { + long stamp = readLock(); + try { + WeakReferenceValueNode curr = table[mix & mask]; + while (curr != null) { + if (curr.hash == hash && (curr.key == k || k.equals(curr.key))) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var mapped = keyMappingFunction.apply(k); + final var v = createFunction.apply(mapped); + stamp = writeLock(); + try { + final int index = mix & mask; + final WeakReferenceValueNode node = table[index]; + WeakReferenceValueNode prev = null; + WeakReferenceValueNode curr = node; + while (curr != null) { + if (curr.hash == hash && (curr.key == mapped || mapped.equals(curr.key))) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new WeakReferenceValueNode<>(mapped, v, hash, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new WeakReferenceValueNode<>(mapped, v, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final K k, final int hash, int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + WeakReferenceValueNode curr = table[index]; + while (curr != null) { + if (curr.hash == hash && (curr.key == k || k.equals(curr.key))) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final K k, final V v, final int hash, int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final WeakReferenceValueNode node = table[index]; + WeakReferenceValueNode prev = null; + WeakReferenceValueNode curr = node; + while (curr != null) { + if (curr.hash == hash && (curr.key == k || k.equals(curr.key))) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new WeakReferenceValueNode<>(k, v, hash, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new WeakReferenceValueNode<>(k, v, hash, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueIdentityHashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueIdentityHashCache.java new file mode 100644 index 0000000..0f34191 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueIdentityHashCache.java @@ -0,0 +1,242 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * 按键的引用身份保存弱引用值。值失去外部强引用后可回收。 + * + * @param 缓存键类型 + * @param 缓存值类型 + */ +public final class WeakValueIdentityHashCache extends WeakSegmentedCache> implements LoadingCache, ReclaimableCache { + + private final Function createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueIdentityHashCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueIdentityHashCache(Function createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueIdentityHashCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueIdentityHashCache(int concurrencyLevel, Function createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + this.createFunction = createFunction; + } + + @Override + public Function createFunction() { + return createFunction; + } + + @Override + public V getCache(final K k, Function createFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCache(K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, keyMappingFunction); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, Interner.identityMappingFunction()); + } + + @Override + public V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getCache(k, mix, createFunction, keyMappingFunction); + } + + @Override + public V getIfPresent(final K k) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).getIfAbsent(k, mix); + } + + @Override + public V putIfAbsent(final K k, final V v) { + int hash = System.identityHashCode(k); + int mix = HashCommon.mix(hash); + return segmentFor(mix).put(k, v, mix); + } + + @Override + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + final static class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return System.identityHashCode(node.key); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final K k, final int mix, Function createFunction, UnaryOperator keyMappingFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var mapped = keyMappingFunction.apply(k); + final var v = createFunction.apply(mapped); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == mapped) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(mapped, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(mapped, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final K k, final int mix) { + long stamp = readLock(); + try { + final int index = mix & mask; + Node curr = table[index]; + while (curr != null) { + if (curr.key == k) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final K k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node extends WeakReference implements ChainNode> { + + private final K key; + private volatile Node next; + + private Node(K key, V value, Node next, ReferenceQueue queue) { + super(value, queue); + this.key = key; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueIntCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueIntCache.java new file mode 100644 index 0000000..43d4863 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueIntCache.java @@ -0,0 +1,216 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.function.IntFunction; + +/** + * 使用原始类型 {@code int} 作为键,弱引用缓存值。值失去外部强引用后,后续查找可能重新创建。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * + * @param 缓存值类型 + */ +public final class WeakValueIntCache extends WeakSegmentedCache> implements ReclaimableCache { + + private final IntFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueIntCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueIntCache(IntFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueIntCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueIntCache(int concurrencyLevel, IntFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final int k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final int k, IntFunction createFunction) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final int k) { + int mix = HashCommon.mix(k); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + public V putIfAbsent(final int k, final V v) { + int mix = HashCommon.mix(k); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + static final class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return node.key; + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final int k, final int mix, IntFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final int k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final int k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node extends WeakReference implements ChainNode> { + + private final int key; + private volatile Node next; + + private Node(int key, V value, Node next, ReferenceQueue queue) { + super(value, queue); + this.key = key; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueLongCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueLongCache.java new file mode 100644 index 0000000..9cd39eb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/WeakValueLongCache.java @@ -0,0 +1,216 @@ +package com.modularmc.mmclutils.api.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.function.LongFunction; + +/** + * 使用原始类型 {@code long} 作为键,弱引用缓存值。值失去外部强引用后,后续查找可能重新创建。 + * 计算函数在分段锁外运行,并发写入在锁内合并。 + * + * @param 缓存值类型 + */ +public final class WeakValueLongCache extends WeakSegmentedCache> implements ReclaimableCache { + + private final LongFunction createFunction; + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueLongCache() { + this(SegmentedCache.DEFAULT_CONCURRENCY, null); + } + + /** 使用默认并发度。创建函数由参数决定,可省略。 */ + public WeakValueLongCache(LongFunction createFunction) { + this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueLongCache(int concurrencyLevel) { + this(concurrencyLevel, null); + } + + /** 按给定的并发度初始化缓存。并发度必须大于零。 */ + public WeakValueLongCache(int concurrencyLevel, LongFunction createFunction) { + super(concurrencyLevel, i -> new Segment<>()); + CacheReferenceQueue.add(this); + this.createFunction = createFunction; + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getCache(final long k) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 在锁外执行计算,允许回调再次访问同一缓存。 */ + public V getCache(final long k, LongFunction createFunction) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).getCache(k, mix, createFunction); + } + + /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */ + public V getIfPresent(final long k) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).getIfAbsent(k, mix); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + public V putIfAbsent(final long k, final V v) { + int mix = HashCommon.mix(Long.hashCode(k)); + return segmentFor(mix).put(k, v, mix); + } + + /** 清除全部条目。 */ + public void clear() { + clearSegments(); + } + + @Override + public void clearCache() { + expungeStaleEntries(); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + static final class Segment extends WeakHashSegment> { + + private Segment() {} + + @Override + @SuppressWarnings("unchecked") + protected Node[] newArray(int capacity) { + return new Node[capacity]; + } + + @Override + protected int nodeHash(Node node) { + return Long.hashCode(node.key); + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V getCache(final long k, final int mix, LongFunction createFunction) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + V v = curr.get(); + if (v != null) return v; + break; + } + curr = curr.next; + } + } finally { + unlockRead(stamp); + } + // 在锁外执行计算,允许回调再次访问同一缓存。 + final var v = createFunction.apply(k); + stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + V existing = curr.get(); + if (existing != null) { + return existing; + } + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + + /** 只读取现有条目。 */ + private V getIfAbsent(final long k, final int mix) { + long stamp = readLock(); + try { + Node curr = table[mix & mask]; + while (curr != null) { + if (curr.key == k) { + return curr.get(); + } + curr = curr.next; + } + return null; + } finally { + unlockRead(stamp); + } + } + + /** 替换已被回收的节点,保留原键所在的链位置。 */ + private V put(final long k, final V v, final int mix) { + long stamp = writeLock(); + try { + final int index = mix & mask; + final Node node = table[index]; + Node prev = null; + Node curr = node; + while (curr != null) { + if (curr.key == k) { + V old = curr.get(); + if (old != null) return old; + // 替换已被回收的节点,保留原键所在的链位置。 + var n = new Node<>(k, v, curr.next, queue); + if (prev == null) { + table[index] = n; + } else { + prev.next = n; + } + return v; + } + prev = curr; + curr = curr.next; + } + table[index] = new Node<>(k, v, node, queue); + if (++size > maxFill) { + resize(); + } + return v; + } finally { + unlockWrite(stamp); + } + } + } + + static final class Node extends WeakReference implements ChainNode> { + + private final long key; + private volatile Node next; + + private Node(long key, V value, Node next, ReferenceQueue queue) { + super(value, queue); + this.key = key; + this.next = next; + } + + @Override + public Node getNext() { + return next; + } + + @Override + public void setNext(Node next) { + this.next = next; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/LongCounters.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/LongCounters.java new file mode 100644 index 0000000..c578ade --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/LongCounters.java @@ -0,0 +1,129 @@ +package com.modularmc.mmclutils.api.collection.map; + +import com.modularmc.mmclutils.api.collection.map.hash.Object2LongOpenCachedHashMap; + +import it.unimi.dsi.fastutil.objects.Object2LongMap; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.Reference2LongMap; +import it.unimi.dsi.fastutil.objects.Reference2LongOpenHashMap; + +import java.util.Arrays; + +/** 无装箱计数表,分别支持相等键和引用键。 */ +public final class LongCounters { + + private LongCounters() {} + + /** 以默认容量创建相等键计数表。 */ + public static ByEquality byEquality() { + return new ByEquality<>(16); + } + + /** 创建相等键计数表并按预期条目数预留空间。 */ + public static ByEquality byEquality(int expected) { + return new ByEquality<>(expected); + } + + /** 复制给定映射的键和原始计数。新表使用独立的存储与默认返回值。 */ + public static ByEquality byEquality(Object2LongMap source) { + var counter = new ByEquality(source.size()); + source.object2LongEntrySet().forEach(entry -> counter.counts.put(entry.getKey(), entry.getLongValue())); + return counter; + } + + /** 以默认容量创建引用键计数表。 */ + public static ByIdentity byIdentity() { + return new ByIdentity<>(16); + } + + /** 创建引用键计数表并按预期条目数预留空间。 */ + public static ByIdentity byIdentity(int expected) { + return new ByIdentity<>(expected); + } + + private static long added(long current, long delta) { + long result = current + delta; + return (current | delta) >= 0 && result < 0 ? Long.MAX_VALUE : result; + } + + /** 按相等性计数并保存键的哈希值。迭代条目只在当前步有效。 */ + public static final class ByEquality implements Iterable> { + + private final Object2LongOpenCachedHashMap counts; + + private ByEquality(int expected) { + counts = new Object2LongOpenCachedHashMap<>(expected); + } + + /** 返回相等键计数表的实时视图,值可直接修改。 */ + public Object2LongMap values() { + return counts; + } + + /** 返回累加前的值。正溢出时饱和到 long 的最大值。空键累加返回零。 */ + public long addTo(K key, long delta) { + if (key == null) return 0; + long old = counts.getLong(key); + counts.put(key, added(old, delta)); + return old; + } + + /** 为指定数量的新键预留空间。已有键数计入所需总容量。 */ + public void ensureAdditionalCapacity(int additional) { + if (additional < 0) throw new IllegalArgumentException("预留容量不得为负数"); + counts.ensureCapacity(Math.addExact(counts.size(), additional)); + } + + /** 将已有计数全部置零,保留键和底层容量。 */ + public void reset() { + counts.resetValues(); + } + + /** 移除所有当前计数为零的键。 */ + public void removeZeros() { + counts.object2LongEntrySet().removeIf(entry -> entry.getLongValue() == 0); + } + + @Override + public ObjectIterator> iterator() { + return counts.object2LongEntrySet().fastIterator(); + } + } + + /** 按引用身份计数。迭代条目只在当前步有效。 */ + public static final class ByIdentity extends Reference2LongOpenHashMap implements Iterable> { + + private ByIdentity(int expected) { + super(expected); + } + + @Override + public long addTo(K key, long delta) { + if (key == null) return 0; + long old = getOrDefault(key, 0); + put(key, added(old, delta)); + return old; + } + + /** 为指定数量的新键预留空间。已有键数计入所需总容量。 */ + public void ensureAdditionalCapacity(int additional) { + if (additional < 0) throw new IllegalArgumentException("预留容量不得为负数"); + ensureCapacity(Math.addExact(size(), additional)); + } + + /** 将已有计数全部置零,保留键和底层容量。 */ + public void reset() { + Arrays.fill(value, 0); + } + + /** 移除所有当前计数为零的键。 */ + public void removeZeros() { + reference2LongEntrySet().removeIf(entry -> entry.getLongValue() == 0); + } + + @Override + public ObjectIterator> iterator() { + return reference2LongEntrySet().fastIterator(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/MultiMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/MultiMap.java new file mode 100644 index 0000000..84ca033 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/MultiMap.java @@ -0,0 +1,192 @@ +package com.modularmc.mmclutils.api.collection.map; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceFunction; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +/** + * 为一个键保存多个值,可由调用方选择底层映射和值集合。集合定义值的比较、去重与迭代顺序。 + * 使用同一实例的读写操作须在同一个线程执行,或由使用方进行同步。 + * + * @param 键类型 + * @param 值类型 + */ +public interface MultiMap { + + /** 使用传入的实时映射,值集合在写入缺失键时由工厂创建。工厂每次须提供独立的可变集合。 */ + static MultiMap create(Map> map, Supplier> factory) { + return new MultiMapWrapper<>(map, factory); + } + + /** 创建以键的 {@link Object#equals} 区分条目的多值映射。 */ + static MultiMap create(Supplier> factory) { + return new MultiMapWrapper<>(new HashMap<>(), factory); + } + + /** 创建以引用身份区分键的多值映射。各值集合自行定义值的比较与迭代顺序。 */ + static MultiMap createIdentity(Supplier> factory) { + return new MultiMapWrapper<>(new Reference2ReferenceOpenHashMap<>(), factory); + } + + /** 返回底层映射的实时视图。对该映射或值集合的修改立即反映到本对象。 */ + Map> getMap(); + + /** 返回指定键的值集合。键缺失时返回不可变空列表。 */ + Collection get(K key); + + /** 判断底层映射是否含该键,包括显式持有空集合的键。 */ + boolean containsKey(K key); + + /** 按该键的值集合提供的相等规则检查指定值。 */ + boolean containsValue(K key, V value); + + /** 添加一个值。可否保存重复值由集合工厂决定。 */ + void put(K key, V value); + + /** 把给定集合的元素追加到该键关联的集合。 */ + void putAll(K key, Collection values); + + /** 删除指定值并返回是否有变化。删除最后一项时一并移除键。 */ + boolean remove(K key, V value); + + /** 删除此键下与给定集合匹配的所有项。结果为空时移除键。 */ + boolean removeAll(K key, Collection values); + + /** 移除该键并交还原集合。键缺失时返回不可变空列表。 */ + Collection remove(K key); + + /** 返回一级键的数量。 */ + int size(); + + /** 遍历各值集合并求元素数的总和,包含允许重复存储的项。 */ + int valueCount(); + + /** 逐项访问键和值。回调中请勿结构性修改当前映射。 */ + void forEach(BiConsumer action); + + /** 判断底层映射是否还有键。 */ + boolean isEmpty(); + + /** 移除所有外层键以及从本映射可访问的值。 */ + void clear(); + + /** 使用调用方提供的 Map 和集合工厂保存多值映射。 */ + final class MultiMapWrapper implements MultiMap { + + private final Map> map; + private final Reference2ReferenceFunction> factory; + private final boolean isRefMap; + + private MultiMapWrapper(Map> map, Supplier> factory) { + this.map = map; + this.factory = unusedKey -> factory.get(); + this.isRefMap = map instanceof Reference2ReferenceMap; + } + + @Override + public Map> getMap() { + return map; + } + + @Override + public Collection get(K key) { + var values = map.get(key); + if (values != null) return values; + return Collections.emptyList(); + } + + @Override + public boolean containsKey(K key) { + return map.containsKey(key); + } + + @Override + public boolean containsValue(K key, V value) { + var values = map.get(key); + return values != null && values.contains(value); + } + + @Override + public void put(K key, V value) { + if (isRefMap) { + ((Reference2ReferenceMap>) map).computeIfAbsent(key, factory).add(value); + } else { + map.computeIfAbsent(key, factory).add(value); + } + } + + @Override + public void putAll(K key, Collection values) { + if (isRefMap) { + ((Reference2ReferenceMap>) map).computeIfAbsent(key, factory).addAll(values); + } else { + map.computeIfAbsent(key, factory).addAll(values); + } + } + + @Override + public boolean remove(K key, V value) { + var values = map.get(key); + if (values != null && values.remove(value)) { + if (values.isEmpty()) map.remove(key); + return true; + } + return false; + } + + @Override + public boolean removeAll(K key, Collection values) { + var bound = map.get(key); + if (bound == null || !bound.removeAll(values)) { + return false; + } + if (bound.isEmpty()) { + map.remove(key); + } + return true; + } + + @Override + public Collection remove(K key) { + var values = map.remove(key); + if (values != null) return values; + return Collections.emptyList(); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public int valueCount() { + int count = 0; + for (var values : map.values()) { + count += values.size(); + } + return count; + } + + @Override + public void forEach(BiConsumer action) { + map.forEach((k, vs) -> vs.forEach(v -> action.accept(k, v))); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public void clear() { + map.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/NestedMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/NestedMap.java new file mode 100644 index 0000000..18e3774 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/NestedMap.java @@ -0,0 +1,197 @@ +package com.modularmc.mmclutils.api.collection.map; + +import com.modularmc.mmclutils.api.function.TriConsumer; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceFunction; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +/** + * 按外层键和内层键索引单个值。写入时按需创建内层映射,两层键分别由各自的映射定义比较规则。 + * 使用同一实例的读写操作须在同一个线程执行,或由使用方进行同步。 + * + * @param 外层键类型 + * @param 内层键类型 + * @param 值类型 + */ +public interface NestedMap { + + /** 使用传入的外层 Map。工厂每次须返回一个独立且比较规则一致的内层 Map。 */ + static NestedMap create(Map> map, Supplier> factory) { + return new NestedMapWrapper<>(map, factory); + } + + /** 由 {@link Object#equals} 比较外层键,内层键按提供的 Map 工厂定义。 */ + static NestedMap create(Supplier> factory) { + return new NestedMapWrapper<>(new HashMap<>(), factory); + } + + /** 按引用身份比较外层键,内层键按提供的 Map 工厂定义。 */ + static NestedMap createIdentity(Supplier> factory) { + return new NestedMapWrapper<>(new Reference2ReferenceOpenHashMap<>(), factory); + } + + /** 返回可直接修改的底层映射,各内层映射同样可见。 */ + Map> getMap(); + + /** 按两级键查一个值。外层键不存在时返回空值,内层键缺失时沿用内层映射的返回值。 */ + V get(K1 k1, K2 k2); + + /** 返回内层映射的实时视图。外层键缺失时返回不可变空映射。 */ + Map get(K1 k1); + + /** 判断是否存在该外层键。 */ + boolean containsKey(K1 k1); + + /** 判断两级路径下是否存在该内层键。 */ + boolean containsKey(K1 k1, K2 k2); + + /** 存入值,并返回内层映射的原值或默认返回值。首次写入时分配内层映射。 */ + V put(K1 k1, K2 k2, V value); + + /** 在内层键缺失时用该键计算并记录结果。返回值沿用内层映射的计算规则。 */ + V computeIfAbsent(K1 k1, K2 k2, Reference2ReferenceFunction mappingFunction); + + /** 移除内层键并返回原值。外层键不存在时返回空值。移除非空原值并清空内层时顺带删除外层键。 */ + V remove(K1 k1, K2 k2); + + /** 移除外层键并交还对应映射。键缺失时返回不可变空映射。 */ + Map remove(K1 k1); + + /** 返回外层键的数量。 */ + int size(); + + /** 遍历内层映射,统计已存储的两级键值对总数。 */ + int valueCount(); + + /** 遍历每个两级键值对。回调中请勿结构性修改映射。 */ + void forEach(TriConsumer action); + + /** 判断外层映射是否还有键。 */ + boolean isEmpty(); + + /** 移除所有外层键以及从本映射可访问的值。 */ + void clear(); + + /** 使用调用方选择的内外两层 Map 保存两级键值对。 */ + final class NestedMapWrapper implements NestedMap { + + private final Map> map; + private final Reference2ReferenceFunction> factory; + private final boolean isRefMap; + + private boolean isInnerRefMap; + + private NestedMapWrapper(Map> map, Supplier> factory) { + this.map = map; + this.factory = unusedKey -> { + var innerMap = factory.get(); + if (innerMap instanceof Reference2ReferenceMap) { + isInnerRefMap = true; + } + return innerMap; + }; + this.isRefMap = map instanceof Reference2ReferenceMap; + } + + @Override + public Map> getMap() { + return map; + } + + @Override + public Map get(K1 k1) { + var innerMap = map.get(k1); + if (innerMap != null) return innerMap; + return Collections.emptyMap(); + } + + @Override + public boolean containsKey(K1 k1) { + return map.containsKey(k1); + } + + @Override + public boolean containsKey(K1 k1, K2 k2) { + var innerMap = map.get(k1); + return innerMap != null && innerMap.containsKey(k2); + } + + @Override + public V get(K1 k1, K2 k2) { + var innerMap = map.get(k1); + return innerMap == null ? null : innerMap.get(k2); + } + + @Override + public V put(K1 k1, K2 k2, V value) { + return innerMapFor(k1).put(k2, value); + } + + @Override + public V computeIfAbsent(K1 k1, K2 k2, Reference2ReferenceFunction mappingFunction) { + Map innerMap = innerMapFor(k1); + if (isInnerRefMap) { + return ((Reference2ReferenceMap) innerMap).computeIfAbsent(k2, mappingFunction); + } + return innerMap.computeIfAbsent(k2, mappingFunction); + } + + @Override + public V remove(K1 k1, K2 k2) { + Map innerMap = map.get(k1); + if (innerMap == null) return null; + V removed = innerMap.remove(k2); + if (removed != null && innerMap.isEmpty()) map.remove(k1); + return removed; + } + + @Override + public Map remove(K1 k1) { + var innerMap = map.remove(k1); + if (innerMap != null) return innerMap; + return Collections.emptyMap(); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public int valueCount() { + int count = 0; + for (var innerMap : map.values()) { + count += innerMap.size(); + } + return count; + } + + @Override + public void forEach(TriConsumer action) { + map.forEach((k1, vs) -> vs.forEach((k2, v) -> action.accept(k1, k2, v))); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public void clear() { + map.clear(); + } + + private Map innerMapFor(K1 k1) { + if (isRefMap) { + return ((Reference2ReferenceMap>) map).computeIfAbsent(k1, factory); + } + return map.computeIfAbsent(k1, factory); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/NestedMultiMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/NestedMultiMap.java new file mode 100644 index 0000000..9420f72 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/NestedMultiMap.java @@ -0,0 +1,271 @@ +package com.modularmc.mmclutils.api.collection.map; + +import com.modularmc.mmclutils.api.function.TriConsumer; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceFunction; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +/** + * 按外层键和内层键索引值集合。写入时按需创建缺失的内层映射和值集合。 + * 使用同一实例的读写操作须在同一个线程执行,或由使用方进行同步。 + * + * @param 外层键类型 + * @param 内层键类型 + * @param 值类型 + */ +public interface NestedMultiMap { + + /** 包装指定外层映射。工厂每次须提供独立且可修改的内层映射或值集合。 */ + static NestedMultiMap create( + Map>> map, + Supplier>> mapFactory, + Supplier> collectionFactory) { + return new NestedMultiMapWrapper<>(map, mapFactory, collectionFactory); + } + + /** 按相等性比较外层键,内层的存储策略由两个工厂提供。 */ + static NestedMultiMap create( + Supplier>> mapFactory, Supplier> collectionFactory) { + return new NestedMultiMapWrapper<>(new HashMap<>(), mapFactory, collectionFactory); + } + + /** 按引用身份比较外层键。内层映射和值集合的比较规则由各工厂提供。 */ + static NestedMultiMap createIdentity( + Supplier>> mapFactory, Supplier> collectionFactory) { + return new NestedMultiMapWrapper<>(new Reference2ReferenceOpenHashMap<>(), mapFactory, collectionFactory); + } + + /** 返回底层数据的实时视图。通过此视图修改集合会影响本对象。 */ + Map>> getMap(); + + /** 返回指定路径下的原集合。任一级键缺失时返回不可变空列表。 */ + Collection get(K1 k1, K2 k2); + + /** 返回指定外层键的原映射。键缺失时返回不可变空映射。 */ + Map> get(K1 k1); + + /** 判断是否存在该外层键。 */ + boolean containsKey(K1 k1); + + /** 判断内层是否登记了给定键。 */ + boolean containsKey(K1 k1, K2 k2); + + /** 使用指定路径下的值集合检查给定值。 */ + boolean containsValue(K1 k1, K2 k2, V value); + + /** 插入一个值,按需创建内层映射和值集合。 */ + void put(K1 k1, K2 k2, V value); + + /** 将各元素加入该路径下的集合。重复值按集合自身的规则处理。 */ + void putAll(K1 k1, K2 k2, Collection values); + + /** 删除给定值并返回是否变化。集合或内层映射清空时删除对应键。 */ + boolean remove(K1 k1, K2 k2, V value); + + /** 移除匹配集合中任一项的值。删除后清理变空的路径。 */ + boolean removeAll(K1 k1, K2 k2, Collection values); + + /** 移除指定内层集合并交还其内容。路径缺失时返回不可变空列表。 */ + Collection remove(K1 k1, K2 k2); + + /** 移除外层键并交还内层映射。键缺失时返回不可变空映射。 */ + Map> remove(K1 k1); + + /** 返回外层键的数量。 */ + int size(); + + /** 遍历各层并合计实际存储的值数量。 */ + int valueCount(); + + /** 逐个访问外层键、内层键和值。回调中请勿结构性修改当前容器。 */ + void forEach(TriConsumer action); + + /** 判断是否还存放外层键。 */ + boolean isEmpty(); + + /** 移除所有外层键以及从本映射可访问的值。 */ + void clear(); + + /** 使用给定的 Map 和集合工厂存储两级键对应的多值集合。 */ + final class NestedMultiMapWrapper implements NestedMultiMap { + + private final Map>> map; + private final Reference2ReferenceFunction>> mapFactory; + private final Reference2ReferenceFunction> collectionFactory; + private final boolean isRefMap; + + private boolean isInnerRefMap; + + /** 包装现有实时映射。每次调用内层 Map 工厂或集合工厂都应得到独立的可变对象。 */ + public NestedMultiMapWrapper( + Map>> map, + Supplier>> mapFactory, + Supplier> collectionFactory) { + this.map = map; + this.collectionFactory = unusedKey -> collectionFactory.get(); + this.mapFactory = unusedKey -> { + var innerMap = mapFactory.get(); + if (innerMap instanceof Reference2ReferenceMap) { + isInnerRefMap = true; + } + return innerMap; + }; + this.isRefMap = map instanceof Reference2ReferenceMap; + } + + @Override + public Map>> getMap() { + return map; + } + + @Override + public Collection get(K1 k1, K2 k2) { + var innerMap = map.get(k1); + if (innerMap == null) return Collections.emptyList(); + var values = innerMap.get(k2); + if (values != null) return values; + return Collections.emptyList(); + } + + @Override + public Map> get(K1 k1) { + var innerMap = map.get(k1); + if (innerMap != null) return innerMap; + return Collections.emptyMap(); + } + + @Override + public boolean containsKey(K1 k1) { + return map.containsKey(k1); + } + + @Override + public boolean containsKey(K1 k1, K2 k2) { + var innerMap = map.get(k1); + return innerMap != null && innerMap.containsKey(k2); + } + + @Override + public boolean containsValue(K1 k1, K2 k2, V value) { + var innerMap = map.get(k1); + if (innerMap == null) return false; + var values = innerMap.get(k2); + return values != null && values.contains(value); + } + + @Override + public void put(K1 k1, K2 k2, V value) { + valuesFor(k1, k2).add(value); + } + + @Override + public void putAll(K1 k1, K2 k2, Collection values) { + valuesFor(k1, k2).addAll(values); + } + + @Override + public boolean removeAll(K1 k1, K2 k2, Collection values) { + var innerMap = map.get(k1); + if (innerMap == null) return false; + var bound = innerMap.get(k2); + if (bound == null || !bound.removeAll(values)) { + return false; + } + if (bound.isEmpty()) { + innerMap.remove(k2); + if (innerMap.isEmpty()) { + map.remove(k1); + } + } + return true; + } + + @Override + public boolean remove(K1 k1, K2 k2, V value) { + var innerMap = map.get(k1); + if (innerMap == null) return false; + var values = innerMap.get(k2); + if (values == null) return false; + if (values.remove(value)) { + if (values.isEmpty()) { + innerMap.remove(k2); + if (innerMap.isEmpty()) { + map.remove(k1); + } + } + return true; + } + return false; + } + + @Override + public Collection remove(K1 k1, K2 k2) { + var innerMap = map.get(k1); + if (innerMap == null) return Collections.emptyList(); + var values = innerMap.remove(k2); + if (values == null) return Collections.emptyList(); + if (innerMap.isEmpty()) { + map.remove(k1); + } + return values; + } + + @Override + public Map> remove(K1 k1) { + var innerMap = map.remove(k1); + if (innerMap != null) return innerMap; + return Collections.emptyMap(); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public int valueCount() { + int count = 0; + for (var innerMap : map.values()) { + for (var values : innerMap.values()) { + count += values.size(); + } + } + return count; + } + + @Override + public void forEach(TriConsumer action) { + map.forEach((k1, v1s) -> v1s.forEach((k2, v2s) -> v2s.forEach(v -> action.accept(k1, k2, v)))); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public void clear() { + map.clear(); + } + + private Collection valuesFor(K1 k1, K2 k2) { + Map> innerMap; + if (isRefMap) { + innerMap = ((Reference2ReferenceMap>>) map).computeIfAbsent(k1, mapFactory); + } else { + innerMap = map.computeIfAbsent(k1, mapFactory); + } + if (isInnerRefMap) { + return ((Reference2ReferenceMap>) innerMap).computeIfAbsent(k2, collectionFactory); + } + return innerMap.computeIfAbsent(k2, collectionFactory); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2BooleanMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2BooleanMap.java new file mode 100644 index 0000000..ff8fbcc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2BooleanMap.java @@ -0,0 +1,498 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.booleans.AbstractBooleanCollection; +import it.unimi.dsi.fastutil.booleans.BooleanCollection; +import it.unimi.dsi.fastutil.booleans.BooleanIterator; +import it.unimi.dsi.fastutil.objects.AbstractObjectSet; +import it.unimi.dsi.fastutil.objects.AbstractReference2BooleanMap; +import it.unimi.dsi.fastutil.objects.AbstractReferenceSet; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.Reference2BooleanFunction; +import it.unimi.dsi.fastutil.objects.Reference2BooleanMap; +import it.unimi.dsi.fastutil.objects.ReferenceSet; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** 用枚举序号直接寻址的映射。按枚举常量的序号定位,缺失时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2BooleanMap> extends AbstractReference2BooleanMap { + + private final Class keyType; + private final K[] keys; + private final boolean[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final BooleanCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2BooleanMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new boolean[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2BooleanMap(Enum2BooleanMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public boolean getBoolean(Object key) { + if (!isValidKey(key)) return defRetValue; + boolean v = vals[((Enum) key).ordinal()]; + return v ? v : defRetValue; + } + + @Override + public boolean getOrDefault(Object key, boolean defaultValue) { + if (!isValidKey(key)) return defaultValue; + boolean v = vals[((Enum) key).ordinal()]; + return v ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public boolean put(K key, boolean value) { + int i = key.ordinal(); + boolean old = vals[i]; + vals[i] = value; + if (!value) { + if (old) size--; + } else if (!old) { + size++; + } + return old ? old : defRetValue; + } + + @Override + public boolean removeBoolean(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + boolean old = vals[i]; + if (!old) return defRetValue; + vals[i] = false; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()]; + } + + @Override + public boolean containsValue(boolean value) { + return value && size > 0; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, false); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2BooleanMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i]) action.accept(keys[i], Boolean.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2BooleanEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public BooleanCollection values() { + return values; + } + + @Override + public boolean putIfAbsent(K key, boolean value) { + int i = key.ordinal(); + boolean old = vals[i]; + if (old) return old; + if (value) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, boolean value) { + if (!value || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = false; + size--; + return true; + } + + @Override + public boolean replace(K key, boolean oldValue, boolean newValue) { + if (!oldValue || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public boolean replace(K key, boolean value) { + boolean old = vals[key.ordinal()]; + if (!old) return defRetValue; + put(key, value); + return old; + } + + @Override + public boolean computeIfAbsent(K key, Predicate mappingFunction) { + int i = key.ordinal(); + boolean v = vals[i]; + if (v) return v; + boolean newValue = mappingFunction.test(key); + if (newValue) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public boolean computeIfAbsent(K key, Reference2BooleanFunction mappingFunction) { + int i = key.ordinal(); + boolean v = vals[i]; + if (v) return v; + boolean newValue = mappingFunction.getBoolean(key); + if (newValue) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public boolean computeBooleanIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + boolean old = vals[i]; + if (!old) return defRetValue; + Boolean newValue = remappingFunction.apply(key, Boolean.valueOf(old)); + if (newValue == null) { + vals[i] = false; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public boolean computeBoolean(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + boolean old = vals[i]; + Boolean newValue = remappingFunction.apply(key, !old ? null : Boolean.valueOf(old)); + if (newValue == null) { + if (old) { + vals[i] = false; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2BooleanMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + if (vals[i]) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Boolean bv) || !bv.booleanValue()) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + + for (int i = 0, n = vals.length; i < n; i++) { + if (vals[i]) h += keys[i].hashCode() ^ 1231; + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2BooleanMap other && other.keyType == keyType) { + if (other.size == 0) return; + final boolean[] src = other.vals; + final boolean[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + if (src[i]) { + if (!dst[i]) sz++; + dst[i] = true; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2BooleanMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2BooleanMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i]) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2BooleanMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] && ov instanceof Boolean bv && bv.booleanValue(); + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeBoolean(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2BooleanMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public boolean getBooleanValue() { + return vals[index]; + } + + @Override + public boolean setValue(boolean value) { + boolean old = vals[index]; + vals[index] = value; + if (!value) { + if (old) size--; + } else if (!old) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Boolean bv && bv.booleanValue() == vals[index]; + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ Boolean.hashCode(vals[index]); + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2BooleanMap.this.vals; + final int length = vals.length; + while (cursor < length && !vals[cursor]) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current]) { + vals[current] = false; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2BooleanMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements BooleanIterator { + + @Override + public boolean nextBoolean() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2BooleanMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2BooleanMap.this.removeBoolean(o); + return true; + } + } + + private final class Values extends AbstractBooleanCollection { + + @Override + public BooleanIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(boolean value) { + return Enum2BooleanMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2BooleanMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ByteMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ByteMap.java new file mode 100644 index 0000000..c7d79ed --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ByteMap.java @@ -0,0 +1,548 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.bytes.AbstractByteCollection; +import it.unimi.dsi.fastutil.bytes.ByteBinaryOperator; +import it.unimi.dsi.fastutil.bytes.ByteCollection; +import it.unimi.dsi.fastutil.bytes.ByteIterator; +import it.unimi.dsi.fastutil.objects.AbstractObjectSet; +import it.unimi.dsi.fastutil.objects.AbstractReference2ByteMap; +import it.unimi.dsi.fastutil.objects.AbstractReferenceSet; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.Reference2ByteFunction; +import it.unimi.dsi.fastutil.objects.Reference2ByteMap; +import it.unimi.dsi.fastutil.objects.ReferenceSet; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +/** 用枚举序号直接寻址的映射。槽位的零值表示缺少该键;读取缺失键时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2ByteMap> extends AbstractReference2ByteMap { + + private final Class keyType; + private final K[] keys; + private final byte[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final ByteCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2ByteMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new byte[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2ByteMap(Enum2ByteMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public byte getByte(Object key) { + if (!isValidKey(key)) return defRetValue; + byte v = vals[((Enum) key).ordinal()]; + return v != (byte) 0 ? v : defRetValue; + } + + @Override + public byte getOrDefault(Object key, byte defaultValue) { + if (!isValidKey(key)) return defaultValue; + byte v = vals[((Enum) key).ordinal()]; + return v != (byte) 0 ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public byte put(K key, byte value) { + int i = key.ordinal(); + byte old = vals[i]; + vals[i] = value; + if (value == (byte) 0) { + if (old != (byte) 0) size--; + } else if (old == (byte) 0) { + size++; + } + return old != (byte) 0 ? old : defRetValue; + } + + @Override + public byte removeByte(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + byte old = vals[i]; + if (old == (byte) 0) return defRetValue; + vals[i] = (byte) 0; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != (byte) 0; + } + + @Override + public boolean containsValue(byte value) { + if (value == (byte) 0) return false; + final var vals = Enum2ByteMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] == value) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, (byte) 0); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2ByteMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != (byte) 0) action.accept(keys[i], Byte.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2ByteEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public ByteCollection values() { + return values; + } + + @Override + public byte putIfAbsent(K key, byte value) { + int i = key.ordinal(); + byte old = vals[i]; + if (old != (byte) 0) return old; + if (value != (byte) 0) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, byte value) { + if (value == (byte) 0 || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = (byte) 0; + size--; + return true; + } + + @Override + public boolean replace(K key, byte oldValue, byte newValue) { + if (oldValue == (byte) 0 || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public byte replace(K key, byte value) { + byte old = vals[key.ordinal()]; + if (old == (byte) 0) return defRetValue; + put(key, value); + return old; + } + + @Override + public byte computeIfAbsent(K key, ToIntFunction mappingFunction) { + int i = key.ordinal(); + byte v = vals[i]; + if (v != (byte) 0) return v; + byte newValue = (byte) mappingFunction.applyAsInt(key); + if (newValue != (byte) 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public byte computeIfAbsent(K key, Reference2ByteFunction mappingFunction) { + int i = key.ordinal(); + byte v = vals[i]; + if (v != (byte) 0) return v; + byte newValue = mappingFunction.getByte(key); + if (newValue != (byte) 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public byte computeByteIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + byte old = vals[i]; + if (old == (byte) 0) return defRetValue; + Byte newValue = remappingFunction.apply(key, Byte.valueOf(old)); + if (newValue == null) { + vals[i] = (byte) 0; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public byte computeByte(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + byte old = vals[i]; + Byte newValue = remappingFunction.apply(key, old == (byte) 0 ? null : Byte.valueOf(old)); + if (newValue == null) { + if (old != (byte) 0) { + vals[i] = (byte) 0; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** + * 将增量加到现有值上并返回旧值。缺失项从默认返回值开始累加,结果为零时清除该项。 + * + * @param key 要更新的枚举常量 + * @param incr 增量,允许为负 + * @return 累加前的值,缺少该键时返回默认值 + */ + public byte addTo(K key, byte incr) { + int i = key.ordinal(); + byte old = vals[i]; + if (old == (byte) 0) { + + byte sum = (byte) (defRetValue + incr); + if (sum == (byte) 0) return defRetValue; + vals[i] = sum; + size++; + return defRetValue; + } + byte sum = (byte) (old + incr); + vals[i] = sum; + if (sum == (byte) 0) size--; + return old; + } + + @Override + public byte mergeByte(K key, byte value, ByteBinaryOperator remappingFunction) { + int i = key.ordinal(); + byte old = vals[i]; + byte newValue = old == (byte) 0 ? value : remappingFunction.apply(old, value); + if (newValue == (byte) 0) { + if (old != (byte) 0) { + vals[i] = (byte) 0; + size--; + } + return defRetValue; + } + if (old == (byte) 0) size++; + vals[i] = newValue; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2ByteMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + byte v = vals[i]; + if (v != (byte) 0) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Byte bv) || bv.byteValue() != v) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + byte v = vals[i]; + if (v != (byte) 0) h += keys[i].hashCode() ^ v; + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2ByteMap other && other.keyType == keyType) { + if (other.size == 0) return; + final byte[] src = other.vals; + final byte[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + byte v = src[i]; + if (v != (byte) 0) { + if (dst[i] == (byte) 0) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2ByteMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2ByteMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != (byte) 0) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ByteMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] != (byte) 0 && ov instanceof Byte bv && bv.byteValue() == vals[i]; + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeByte(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2ByteMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public byte getByteValue() { + return vals[index]; + } + + @Override + public byte setValue(byte value) { + byte old = vals[index]; + vals[index] = value; + if (value == (byte) 0) { + if (old != (byte) 0) size--; + } else if (old == (byte) 0) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Byte bv && bv.byteValue() == vals[index]; + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ vals[index]; + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2ByteMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == (byte) 0) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != (byte) 0) { + vals[current] = (byte) 0; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2ByteMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements ByteIterator { + + @Override + public byte nextByte() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ByteMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2ByteMap.this.removeByte(o); + return true; + } + } + + private final class Values extends AbstractByteCollection { + + @Override + public ByteIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(byte value) { + return Enum2ByteMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ByteMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2CharMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2CharMap.java new file mode 100644 index 0000000..7b7e464 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2CharMap.java @@ -0,0 +1,542 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.chars.AbstractCharCollection; +import it.unimi.dsi.fastutil.chars.CharBinaryOperator; +import it.unimi.dsi.fastutil.chars.CharCollection; +import it.unimi.dsi.fastutil.chars.CharIterator; +import it.unimi.dsi.fastutil.objects.*; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +/** 用枚举序号直接寻址的映射。槽位的零值表示缺少该键;读取缺失键时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2CharMap> extends AbstractReference2CharMap { + + private final Class keyType; + private final K[] keys; + private final char[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final CharCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2CharMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new char[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2CharMap(Enum2CharMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public char getChar(Object key) { + if (!isValidKey(key)) return defRetValue; + char v = vals[((Enum) key).ordinal()]; + return v != (char) 0 ? v : defRetValue; + } + + @Override + public char getOrDefault(Object key, char defaultValue) { + if (!isValidKey(key)) return defaultValue; + char v = vals[((Enum) key).ordinal()]; + return v != (char) 0 ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public char put(K key, char value) { + int i = key.ordinal(); + char old = vals[i]; + vals[i] = value; + if (value == (char) 0) { + if (old != (char) 0) size--; + } else if (old == (char) 0) { + size++; + } + return old != (char) 0 ? old : defRetValue; + } + + @Override + public char removeChar(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + char old = vals[i]; + if (old == (char) 0) return defRetValue; + vals[i] = (char) 0; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != (char) 0; + } + + @Override + public boolean containsValue(char value) { + if (value == (char) 0) return false; + final var vals = Enum2CharMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] == value) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, (char) 0); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2CharMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != (char) 0) action.accept(keys[i], Character.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2CharEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public CharCollection values() { + return values; + } + + @Override + public char putIfAbsent(K key, char value) { + int i = key.ordinal(); + char old = vals[i]; + if (old != (char) 0) return old; + if (value != (char) 0) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, char value) { + if (value == (char) 0 || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = (char) 0; + size--; + return true; + } + + @Override + public boolean replace(K key, char oldValue, char newValue) { + if (oldValue == (char) 0 || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public char replace(K key, char value) { + char old = vals[key.ordinal()]; + if (old == (char) 0) return defRetValue; + put(key, value); + return old; + } + + @Override + public char computeIfAbsent(K key, ToIntFunction mappingFunction) { + int i = key.ordinal(); + char v = vals[i]; + if (v != (char) 0) return v; + char newValue = (char) mappingFunction.applyAsInt(key); + if (newValue != (char) 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public char computeIfAbsent(K key, Reference2CharFunction mappingFunction) { + int i = key.ordinal(); + char v = vals[i]; + if (v != (char) 0) return v; + char newValue = mappingFunction.getChar(key); + if (newValue != (char) 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public char computeCharIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + char old = vals[i]; + if (old == (char) 0) return defRetValue; + Character newValue = remappingFunction.apply(key, Character.valueOf(old)); + if (newValue == null) { + vals[i] = (char) 0; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public char computeChar(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + char old = vals[i]; + Character newValue = remappingFunction.apply(key, old == (char) 0 ? null : Character.valueOf(old)); + if (newValue == null) { + if (old != (char) 0) { + vals[i] = (char) 0; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** + * 将增量加到现有值上并返回旧值。缺失项从默认返回值开始累加,结果为零时清除该项。 + * + * @param key 要更新的枚举常量 + * @param incr 增量,允许为负 + * @return 累加前的值,缺少该键时返回默认值 + */ + public char addTo(K key, char incr) { + int i = key.ordinal(); + char old = vals[i]; + if (old == (char) 0) { + + char sum = (char) (defRetValue + incr); + if (sum == (char) 0) return defRetValue; + vals[i] = sum; + size++; + return defRetValue; + } + char sum = (char) (old + incr); + vals[i] = sum; + if (sum == (char) 0) size--; + return old; + } + + @Override + public char mergeChar(K key, char value, CharBinaryOperator remappingFunction) { + int i = key.ordinal(); + char old = vals[i]; + char newValue = old == (char) 0 ? value : remappingFunction.apply(old, value); + if (newValue == (char) 0) { + if (old != (char) 0) { + vals[i] = (char) 0; + size--; + } + return defRetValue; + } + if (old == (char) 0) size++; + vals[i] = newValue; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2CharMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + char v = vals[i]; + if (v != (char) 0) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Character cv) || cv.charValue() != v) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + char v = vals[i]; + if (v != (char) 0) h += keys[i].hashCode() ^ v; + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2CharMap other && other.keyType == keyType) { + if (other.size == 0) return; + final char[] src = other.vals; + final char[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + char v = src[i]; + if (v != (char) 0) { + if (dst[i] == (char) 0) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2CharMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2CharMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != (char) 0) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2CharMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] != (char) 0 && ov instanceof Character cv && cv.charValue() == vals[i]; + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeChar(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2CharMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public char getCharValue() { + return vals[index]; + } + + @Override + public char setValue(char value) { + char old = vals[index]; + vals[index] = value; + if (value == (char) 0) { + if (old != (char) 0) size--; + } else if (old == (char) 0) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Character cv && cv.charValue() == vals[index]; + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ vals[index]; + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2CharMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == (char) 0) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != (char) 0) { + vals[current] = (char) 0; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2CharMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements CharIterator { + + @Override + public char nextChar() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2CharMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2CharMap.this.removeChar(o); + return true; + } + } + + private final class Values extends AbstractCharCollection { + + @Override + public CharIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(char value) { + return Enum2CharMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2CharMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2DoubleMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2DoubleMap.java new file mode 100644 index 0000000..f2b57e8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2DoubleMap.java @@ -0,0 +1,543 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.doubles.AbstractDoubleCollection; +import it.unimi.dsi.fastutil.doubles.DoubleCollection; +import it.unimi.dsi.fastutil.doubles.DoubleIterator; +import it.unimi.dsi.fastutil.objects.*; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.DoubleBinaryOperator; +import java.util.function.ToDoubleFunction; + +/** 用枚举序号直接寻址的映射。槽位的零值表示缺少该键;读取缺失键时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2DoubleMap> extends AbstractReference2DoubleMap { + + private final Class keyType; + private final K[] keys; + private final double[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final DoubleCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2DoubleMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new double[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2DoubleMap(Enum2DoubleMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public double getDouble(Object key) { + if (!isValidKey(key)) return defRetValue; + double v = vals[((Enum) key).ordinal()]; + return v != 0D ? v : defRetValue; + } + + @Override + public double getOrDefault(Object key, double defaultValue) { + if (!isValidKey(key)) return defaultValue; + double v = vals[((Enum) key).ordinal()]; + return v != 0D ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public double put(K key, double value) { + int i = key.ordinal(); + double old = vals[i]; + vals[i] = value; + if (value == 0D) { + if (old != 0D) size--; + } else if (old == 0D) { + size++; + } + return old != 0D ? old : defRetValue; + } + + @Override + public double removeDouble(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + double old = vals[i]; + if (old == 0D) return defRetValue; + vals[i] = 0D; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != 0D; + } + + @Override + public boolean containsValue(double value) { + if (value == 0D) return false; + final long bits = Double.doubleToLongBits(value); + final var vals = Enum2DoubleMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (Double.doubleToLongBits(vals[i]) == bits) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, 0D); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2DoubleMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0D) action.accept(keys[i], Double.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2DoubleEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public DoubleCollection values() { + return values; + } + + @Override + public double putIfAbsent(K key, double value) { + int i = key.ordinal(); + double old = vals[i]; + if (old != 0D) return old; + if (value != 0D) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, double value) { + if (value == 0D || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = 0D; + size--; + return true; + } + + @Override + public boolean replace(K key, double oldValue, double newValue) { + if (oldValue == 0D || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public double replace(K key, double value) { + double old = vals[key.ordinal()]; + if (old == 0D) return defRetValue; + put(key, value); + return old; + } + + @Override + public double computeIfAbsent(K key, ToDoubleFunction mappingFunction) { + int i = key.ordinal(); + double v = vals[i]; + if (v != 0D) return v; + double newValue = mappingFunction.applyAsDouble(key); + if (newValue != 0D) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public double computeIfAbsent(K key, Reference2DoubleFunction mappingFunction) { + int i = key.ordinal(); + double v = vals[i]; + if (v != 0D) return v; + double newValue = mappingFunction.getDouble(key); + if (newValue != 0D) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public double computeDoubleIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + double old = vals[i]; + if (old == 0D) return defRetValue; + Double newValue = remappingFunction.apply(key, Double.valueOf(old)); + if (newValue == null) { + vals[i] = 0D; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public double computeDouble(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + double old = vals[i]; + Double newValue = remappingFunction.apply(key, old == 0D ? null : Double.valueOf(old)); + if (newValue == null) { + if (old != 0D) { + vals[i] = 0D; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** + * 将增量加到现有值上并返回旧值。缺失项从默认返回值开始累加,结果为零时清除该项。 + * + * @param key 要更新的枚举常量 + * @param incr 增量,允许为负 + * @return 累加前的值,缺少该键时返回默认值 + */ + public double addTo(K key, double incr) { + int i = key.ordinal(); + double old = vals[i]; + if (old == 0D) { + + double sum = defRetValue + incr; + if (sum == 0D) return defRetValue; + vals[i] = sum; + size++; + return defRetValue; + } + double sum = old + incr; + vals[i] = sum; + if (sum == 0D) size--; + return old; + } + + @Override + public double mergeDouble(K key, double value, DoubleBinaryOperator remappingFunction) { + int i = key.ordinal(); + double old = vals[i]; + double newValue = old == 0D ? value : remappingFunction.applyAsDouble(old, value); + if (newValue == 0D) { + if (old != 0D) { + vals[i] = 0D; + size--; + } + return defRetValue; + } + if (old == 0D) size++; + vals[i] = newValue; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2DoubleMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + double v = vals[i]; + if (v != 0D) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Double dv) || Double.doubleToLongBits(dv.doubleValue()) != Double.doubleToLongBits(v)) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + double v = vals[i]; + if (v != 0D) h += keys[i].hashCode() ^ Double.hashCode(v); + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2DoubleMap other && other.keyType == keyType) { + if (other.size == 0) return; + final double[] src = other.vals; + final double[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + double v = src[i]; + if (v != 0D) { + if (dst[i] == 0D) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2DoubleMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2DoubleMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0D) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2DoubleMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] != 0D && ov instanceof Double dv && Double.doubleToLongBits(dv.doubleValue()) == Double.doubleToLongBits(vals[i]); + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeDouble(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2DoubleMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public double getDoubleValue() { + return vals[index]; + } + + @Override + public double setValue(double value) { + double old = vals[index]; + vals[index] = value; + if (value == 0D) { + if (old != 0D) size--; + } else if (old == 0D) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Double dv && Double.doubleToLongBits(dv.doubleValue()) == Double.doubleToLongBits(vals[index]); + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ Double.hashCode(vals[index]); + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2DoubleMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == 0D) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != 0D) { + vals[current] = 0D; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2DoubleMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements DoubleIterator { + + @Override + public double nextDouble() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2DoubleMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2DoubleMap.this.removeDouble(o); + return true; + } + } + + private final class Values extends AbstractDoubleCollection { + + @Override + public DoubleIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(double value) { + return Enum2DoubleMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2DoubleMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2FloatMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2FloatMap.java new file mode 100644 index 0000000..5357497 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2FloatMap.java @@ -0,0 +1,543 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.floats.AbstractFloatCollection; +import it.unimi.dsi.fastutil.floats.FloatBinaryOperator; +import it.unimi.dsi.fastutil.floats.FloatCollection; +import it.unimi.dsi.fastutil.floats.FloatIterator; +import it.unimi.dsi.fastutil.objects.*; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToDoubleFunction; + +/** 用枚举序号直接寻址的映射。槽位的零值表示缺少该键;读取缺失键时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2FloatMap> extends AbstractReference2FloatMap { + + private final Class keyType; + private final K[] keys; + private final float[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final FloatCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2FloatMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new float[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2FloatMap(Enum2FloatMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public float getFloat(Object key) { + if (!isValidKey(key)) return defRetValue; + float v = vals[((Enum) key).ordinal()]; + return v != 0F ? v : defRetValue; + } + + @Override + public float getOrDefault(Object key, float defaultValue) { + if (!isValidKey(key)) return defaultValue; + float v = vals[((Enum) key).ordinal()]; + return v != 0F ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public float put(K key, float value) { + int i = key.ordinal(); + float old = vals[i]; + vals[i] = value; + if (value == 0F) { + if (old != 0F) size--; + } else if (old == 0F) { + size++; + } + return old != 0F ? old : defRetValue; + } + + @Override + public float removeFloat(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + float old = vals[i]; + if (old == 0F) return defRetValue; + vals[i] = 0F; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != 0F; + } + + @Override + public boolean containsValue(float value) { + if (value == 0F) return false; + final int bits = Float.floatToIntBits(value); + final var vals = Enum2FloatMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (Float.floatToIntBits(vals[i]) == bits) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, 0F); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2FloatMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0F) action.accept(keys[i], Float.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2FloatEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public FloatCollection values() { + return values; + } + + @Override + public float putIfAbsent(K key, float value) { + int i = key.ordinal(); + float old = vals[i]; + if (old != 0F) return old; + if (value != 0F) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, float value) { + if (value == 0F || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = 0F; + size--; + return true; + } + + @Override + public boolean replace(K key, float oldValue, float newValue) { + if (oldValue == 0F || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public float replace(K key, float value) { + float old = vals[key.ordinal()]; + if (old == 0F) return defRetValue; + put(key, value); + return old; + } + + @Override + public float computeIfAbsent(K key, ToDoubleFunction mappingFunction) { + int i = key.ordinal(); + float v = vals[i]; + if (v != 0F) return v; + float newValue = (float) mappingFunction.applyAsDouble(key); + if (newValue != 0F) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public float computeIfAbsent(K key, Reference2FloatFunction mappingFunction) { + int i = key.ordinal(); + float v = vals[i]; + if (v != 0F) return v; + float newValue = mappingFunction.getFloat(key); + if (newValue != 0F) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public float computeFloatIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + float old = vals[i]; + if (old == 0F) return defRetValue; + Float newValue = remappingFunction.apply(key, Float.valueOf(old)); + if (newValue == null) { + vals[i] = 0F; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public float computeFloat(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + float old = vals[i]; + Float newValue = remappingFunction.apply(key, old == 0F ? null : Float.valueOf(old)); + if (newValue == null) { + if (old != 0F) { + vals[i] = 0F; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** + * 将增量加到现有值上并返回旧值。缺失项从默认返回值开始累加,结果为零时清除该项。 + * + * @param key 要更新的枚举常量 + * @param incr 增量,允许为负 + * @return 累加前的值,缺少该键时返回默认值 + */ + public float addTo(K key, float incr) { + int i = key.ordinal(); + float old = vals[i]; + if (old == 0F) { + + float sum = defRetValue + incr; + if (sum == 0F) return defRetValue; + vals[i] = sum; + size++; + return defRetValue; + } + float sum = old + incr; + vals[i] = sum; + if (sum == 0F) size--; + return old; + } + + @Override + public float mergeFloat(K key, float value, FloatBinaryOperator remappingFunction) { + int i = key.ordinal(); + float old = vals[i]; + float newValue = old == 0F ? value : remappingFunction.apply(old, value); + if (newValue == 0F) { + if (old != 0F) { + vals[i] = 0F; + size--; + } + return defRetValue; + } + if (old == 0F) size++; + vals[i] = newValue; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2FloatMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + float v = vals[i]; + if (v != 0F) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Float fv) || Float.floatToIntBits(fv.floatValue()) != Float.floatToIntBits(v)) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + float v = vals[i]; + if (v != 0F) h += keys[i].hashCode() ^ Float.hashCode(v); + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2FloatMap other && other.keyType == keyType) { + if (other.size == 0) return; + final float[] src = other.vals; + final float[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + float v = src[i]; + if (v != 0F) { + if (dst[i] == 0F) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2FloatMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2FloatMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0F) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2FloatMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] != 0F && ov instanceof Float fv && Float.floatToIntBits(fv.floatValue()) == Float.floatToIntBits(vals[i]); + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeFloat(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2FloatMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public float getFloatValue() { + return vals[index]; + } + + @Override + public float setValue(float value) { + float old = vals[index]; + vals[index] = value; + if (value == 0F) { + if (old != 0F) size--; + } else if (old == 0F) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Float fv && Float.floatToIntBits(fv.floatValue()) == Float.floatToIntBits(vals[index]); + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ Float.hashCode(vals[index]); + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2FloatMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == 0F) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != 0F) { + vals[current] = 0F; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2FloatMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements FloatIterator { + + @Override + public float nextFloat() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2FloatMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2FloatMap.this.removeFloat(o); + return true; + } + } + + private final class Values extends AbstractFloatCollection { + + @Override + public FloatIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(float value) { + return Enum2FloatMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2FloatMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2IntMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2IntMap.java new file mode 100644 index 0000000..f6e232d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2IntMap.java @@ -0,0 +1,542 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.ints.AbstractIntCollection; +import it.unimi.dsi.fastutil.ints.IntCollection; +import it.unimi.dsi.fastutil.ints.IntIterator; +import it.unimi.dsi.fastutil.objects.*; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.IntBinaryOperator; +import java.util.function.ToIntFunction; + +/** 用枚举序号直接寻址的映射。槽位的零值表示缺少该键;读取缺失键时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2IntMap> extends AbstractReference2IntMap { + + private final Class keyType; + private final K[] keys; + private final int[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final IntCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2IntMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new int[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2IntMap(Enum2IntMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public int getInt(Object key) { + if (!isValidKey(key)) return defRetValue; + int v = vals[((Enum) key).ordinal()]; + return v != 0 ? v : defRetValue; + } + + @Override + public int getOrDefault(Object key, int defaultValue) { + if (!isValidKey(key)) return defaultValue; + int v = vals[((Enum) key).ordinal()]; + return v != 0 ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public int put(K key, int value) { + int i = key.ordinal(); + int old = vals[i]; + vals[i] = value; + if (value == 0) { + if (old != 0) size--; + } else if (old == 0) { + size++; + } + return old != 0 ? old : defRetValue; + } + + @Override + public int removeInt(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + int old = vals[i]; + if (old == 0) return defRetValue; + vals[i] = 0; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != 0; + } + + @Override + public boolean containsValue(int value) { + if (value == 0) return false; + final var vals = Enum2IntMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] == value) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, 0); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2IntMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0) action.accept(keys[i], Integer.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2IntEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public IntCollection values() { + return values; + } + + @Override + public int putIfAbsent(K key, int value) { + int i = key.ordinal(); + int old = vals[i]; + if (old != 0) return old; + if (value != 0) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, int value) { + if (value == 0 || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = 0; + size--; + return true; + } + + @Override + public boolean replace(K key, int oldValue, int newValue) { + if (oldValue == 0 || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public int replace(K key, int value) { + int old = vals[key.ordinal()]; + if (old == 0) return defRetValue; + put(key, value); + return old; + } + + @Override + public int computeIfAbsent(K key, ToIntFunction mappingFunction) { + int i = key.ordinal(); + int v = vals[i]; + if (v != 0) return v; + int newValue = mappingFunction.applyAsInt(key); + if (newValue != 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public int computeIfAbsent(K key, Reference2IntFunction mappingFunction) { + int i = key.ordinal(); + int v = vals[i]; + if (v != 0) return v; + int newValue = mappingFunction.getInt(key); + if (newValue != 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public int computeIntIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + int old = vals[i]; + if (old == 0) return defRetValue; + Integer newValue = remappingFunction.apply(key, Integer.valueOf(old)); + if (newValue == null) { + vals[i] = 0; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public int computeInt(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + int old = vals[i]; + Integer newValue = remappingFunction.apply(key, old == 0 ? null : Integer.valueOf(old)); + if (newValue == null) { + if (old != 0) { + vals[i] = 0; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** + * 将增量加到现有值上并返回旧值。缺失项从默认返回值开始累加,结果为零时清除该项。 + * + * @param key 要更新的枚举常量 + * @param incr 增量,允许为负 + * @return 累加前的值,缺少该键时返回默认值 + */ + public int addTo(K key, int incr) { + int i = key.ordinal(); + int old = vals[i]; + if (old == 0) { + + int sum = defRetValue + incr; + if (sum == 0) return defRetValue; + vals[i] = sum; + size++; + return defRetValue; + } + int sum = old + incr; + vals[i] = sum; + if (sum == 0) size--; + return old; + } + + @Override + public int mergeInt(K key, int value, IntBinaryOperator remappingFunction) { + int i = key.ordinal(); + int old = vals[i]; + int newValue = old == 0 ? value : remappingFunction.applyAsInt(old, value); + if (newValue == 0) { + if (old != 0) { + vals[i] = 0; + size--; + } + return defRetValue; + } + if (old == 0) size++; + vals[i] = newValue; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2IntMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + int v = vals[i]; + if (v != 0) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Integer iv) || iv.intValue() != v) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + int v = vals[i]; + if (v != 0) h += keys[i].hashCode() ^ v; + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2IntMap other && other.keyType == keyType) { + if (other.size == 0) return; + final int[] src = other.vals; + final int[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + int v = src[i]; + if (v != 0) { + if (dst[i] == 0) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2IntMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2IntMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2IntMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] != 0 && ov instanceof Integer iv && iv.intValue() == vals[i]; + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeInt(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2IntMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public int getIntValue() { + return vals[index]; + } + + @Override + public int setValue(int value) { + int old = vals[index]; + vals[index] = value; + if (value == 0) { + if (old != 0) size--; + } else if (old == 0) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Integer iv && iv.intValue() == vals[index]; + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ vals[index]; + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2IntMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == 0) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != 0) { + vals[current] = 0; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2IntMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements IntIterator { + + @Override + public int nextInt() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2IntMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2IntMap.this.removeInt(o); + return true; + } + } + + private final class Values extends AbstractIntCollection { + + @Override + public IntIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(int value) { + return Enum2IntMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2IntMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2LongMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2LongMap.java new file mode 100644 index 0000000..88cc0aa --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2LongMap.java @@ -0,0 +1,542 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.longs.AbstractLongCollection; +import it.unimi.dsi.fastutil.longs.LongCollection; +import it.unimi.dsi.fastutil.longs.LongIterator; +import it.unimi.dsi.fastutil.objects.*; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.LongBinaryOperator; +import java.util.function.ToLongFunction; + +/** 用枚举序号直接寻址的映射。槽位的零值表示缺少该键;读取缺失键时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2LongMap> extends AbstractReference2LongMap { + + private final Class keyType; + private final K[] keys; + private final long[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final LongCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2LongMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new long[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2LongMap(Enum2LongMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public long getLong(Object key) { + if (!isValidKey(key)) return defRetValue; + long v = vals[((Enum) key).ordinal()]; + return v != 0L ? v : defRetValue; + } + + @Override + public long getOrDefault(Object key, long defaultValue) { + if (!isValidKey(key)) return defaultValue; + long v = vals[((Enum) key).ordinal()]; + return v != 0L ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public long put(K key, long value) { + int i = key.ordinal(); + long old = vals[i]; + vals[i] = value; + if (value == 0L) { + if (old != 0L) size--; + } else if (old == 0L) { + size++; + } + return old != 0L ? old : defRetValue; + } + + @Override + public long removeLong(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + long old = vals[i]; + if (old == 0L) return defRetValue; + vals[i] = 0L; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != 0L; + } + + @Override + public boolean containsValue(long value) { + if (value == 0L) return false; + final var vals = Enum2LongMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] == value) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, 0L); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2LongMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0L) action.accept(keys[i], Long.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2LongEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public LongCollection values() { + return values; + } + + @Override + public long putIfAbsent(K key, long value) { + int i = key.ordinal(); + long old = vals[i]; + if (old != 0L) return old; + if (value != 0L) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, long value) { + if (value == 0L || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = 0L; + size--; + return true; + } + + @Override + public boolean replace(K key, long oldValue, long newValue) { + if (oldValue == 0L || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public long replace(K key, long value) { + long old = vals[key.ordinal()]; + if (old == 0L) return defRetValue; + put(key, value); + return old; + } + + @Override + public long computeIfAbsent(K key, ToLongFunction mappingFunction) { + int i = key.ordinal(); + long v = vals[i]; + if (v != 0L) return v; + long newValue = mappingFunction.applyAsLong(key); + if (newValue != 0L) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public long computeIfAbsent(K key, Reference2LongFunction mappingFunction) { + int i = key.ordinal(); + long v = vals[i]; + if (v != 0L) return v; + long newValue = mappingFunction.getLong(key); + if (newValue != 0L) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public long computeLongIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + long old = vals[i]; + if (old == 0L) return defRetValue; + Long newValue = remappingFunction.apply(key, Long.valueOf(old)); + if (newValue == null) { + vals[i] = 0L; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public long computeLong(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + long old = vals[i]; + Long newValue = remappingFunction.apply(key, old == 0L ? null : Long.valueOf(old)); + if (newValue == null) { + if (old != 0L) { + vals[i] = 0L; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** + * 将增量加到现有值上并返回旧值。缺失项从默认返回值开始累加,结果为零时清除该项。 + * + * @param key 要更新的枚举常量 + * @param incr 增量,允许为负 + * @return 累加前的值,缺少该键时返回默认值 + */ + public long addTo(K key, long incr) { + int i = key.ordinal(); + long old = vals[i]; + if (old == 0L) { + + long sum = defRetValue + incr; + if (sum == 0L) return defRetValue; + vals[i] = sum; + size++; + return defRetValue; + } + long sum = old + incr; + vals[i] = sum; + if (sum == 0L) size--; + return old; + } + + @Override + public long mergeLong(K key, long value, LongBinaryOperator remappingFunction) { + int i = key.ordinal(); + long old = vals[i]; + long newValue = old == 0L ? value : remappingFunction.applyAsLong(old, value); + if (newValue == 0L) { + if (old != 0L) { + vals[i] = 0L; + size--; + } + return defRetValue; + } + if (old == 0L) size++; + vals[i] = newValue; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2LongMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + long v = vals[i]; + if (v != 0L) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Long lv) || lv.longValue() != v) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + long v = vals[i]; + if (v != 0L) h += keys[i].hashCode() ^ Long.hashCode(v); + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2LongMap other && other.keyType == keyType) { + if (other.size == 0) return; + final long[] src = other.vals; + final long[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + long v = src[i]; + if (v != 0L) { + if (dst[i] == 0L) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2LongMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2LongMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != 0L) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2LongMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] != 0L && ov instanceof Long lv && lv.longValue() == vals[i]; + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeLong(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2LongMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public long getLongValue() { + return vals[index]; + } + + @Override + public long setValue(long value) { + long old = vals[index]; + vals[index] = value; + if (value == 0L) { + if (old != 0L) size--; + } else if (old == 0L) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Long lv && lv.longValue() == vals[index]; + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ Long.hashCode(vals[index]); + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2LongMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == 0L) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != 0L) { + vals[current] = 0L; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2LongMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements LongIterator { + + @Override + public long nextLong() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2LongMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2LongMap.this.removeLong(o); + return true; + } + } + + private final class Values extends AbstractLongCollection { + + @Override + public LongIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(long value) { + return Enum2LongMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2LongMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ObjectMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ObjectMap.java new file mode 100644 index 0000000..e635e6b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ObjectMap.java @@ -0,0 +1,525 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.objects.*; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; + +/** 用枚举序号直接寻址的映射。按枚举常量的序号定位,缺失时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2ObjectMap, V> extends AbstractReference2ReferenceMap { + + private static final Object NULL = new Object(); + + private final Class keyType; + private final K[] keys; + private final Object[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final ReferenceCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2ObjectMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new Object[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2ObjectMap(Enum2ObjectMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public V get(Object key) { + if (!isValidKey(key)) return defRetValue; + Object v = vals[((Enum) key).ordinal()]; + return v == null ? defRetValue : unmaskNull(v); + } + + @Override + public V getOrDefault(Object key, V defaultValue) { + if (!isValidKey(key)) return defaultValue; + Object v = vals[((Enum) key).ordinal()]; + return v == null ? defaultValue : unmaskNull(v); + } + + @Override + public V put(K key, V value) { + int i = key.ordinal(); + Object old = vals[i]; + + vals[i] = maskNull(value); + if (old == null) size++; + return old == null ? defRetValue : unmaskNull(old); + } + + @Override + public V remove(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + Object old = vals[i]; + if (old == null) return defRetValue; + vals[i] = null; + size--; + return unmaskNull(old); + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != null; + } + + @Override + public boolean containsValue(Object value) { + Object v = maskNull(value); + final var vals = Enum2ObjectMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (v.equals(vals[i])) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, null); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2ObjectMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != null) action.accept(keys[i], unmaskNull(vals[i])); + } + } + + @Override + public FastEntrySet reference2ReferenceEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public ReferenceCollection values() { + return values; + } + + @Override + public V putIfAbsent(K key, V value) { + int i = key.ordinal(); + Object old = vals[i]; + if (old != null) return unmaskNull(old); + vals[i] = maskNull(value); + size++; + return defRetValue; + } + + @Override + public boolean remove(Object key, Object value) { + if (!isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + Object v = vals[i]; + if (v == null || !Objects.equals(unmaskNull(v), value)) return false; + vals[i] = null; + size--; + return true; + } + + @Override + public boolean replace(K key, V oldValue, V newValue) { + int i = key.ordinal(); + Object v = vals[i]; + if (v == null || !Objects.equals(unmaskNull(v), oldValue)) return false; + vals[i] = maskNull(newValue); + return true; + } + + @Override + public V replace(K key, V value) { + int i = key.ordinal(); + Object old = vals[i]; + if (old == null) return defRetValue; + vals[i] = maskNull(value); + return unmaskNull(old); + } + + @Override + public V computeIfAbsent(K key, Function mappingFunction) { + int i = key.ordinal(); + Object old = vals[i]; + V present = unmaskNull(old); + + if (present != null) return present; + V newValue = mappingFunction.apply(key); + if (newValue != null) { + vals[i] = maskNull(newValue); + if (old == null) size++; + } + return newValue; + } + + @Override + public V computeIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + V oldValue = unmaskNull(vals[i]); + + if (oldValue == null) return defRetValue; + V newValue = remappingFunction.apply(key, oldValue); + if (newValue == null) { + vals[i] = null; + size--; + return defRetValue; + } + vals[i] = maskNull(newValue); + return newValue; + } + + @Override + public V compute(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + Object old = vals[i]; + V newValue = remappingFunction.apply(key, unmaskNull(old)); + if (newValue == null) { + if (old != null) { + vals[i] = null; + size--; + } + return defRetValue; + } + vals[i] = maskNull(newValue); + if (old == null) size++; + return newValue; + } + + @Override + public V merge(K key, V value, BiFunction remappingFunction) { + Objects.requireNonNull(value); + int i = key.ordinal(); + Object old = vals[i]; + V oldValue = unmaskNull(old); + V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value); + if (newValue == null) { + if (old != null) { + vals[i] = null; + size--; + } + return defRetValue; + } + vals[i] = maskNull(newValue); + if (old == null) size++; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2ObjectMap other && other.keyType == keyType) { + final Object[] a = this.vals; + final Object[] b = other.vals; + for (int i = 0, n = a.length; i < n; i++) { + Object av = a[i]; + Object bv = b[i]; + if (av == bv) continue; + if (av == null || bv == null) return false; + if (!Objects.equals(unmaskNull(av), unmaskNull(bv))) return false; + } + return true; + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + Object v = vals[i]; + if (v != null) { + V uv = unmaskNull(v); + if (uv == null) { + + if (!m.containsKey(keys[i]) || m.get(keys[i]) != null) return false; + } else { + if (!uv.equals(m.get(keys[i]))) return false; + } + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + Object v = vals[i]; + if (v != null) h += keys[i].hashCode() ^ Objects.hashCode(unmaskNull(v)); + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + @SuppressWarnings("unchecked") + public void putAll(Map m) { + if (m instanceof Enum2ObjectMap other && other.keyType == keyType) { + if (other.size == 0) return; + final Object[] src = other.vals; + final Object[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + Object v = src[i]; + if (v != null) { + if (dst[i] == null) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private static Object maskNull(Object value) { + return value == null ? NULL : value; + } + + @SuppressWarnings("unchecked") + private V unmaskNull(Object value) { + return (V) (value == NULL ? null : value); + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2ReferenceMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2ObjectMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != null) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ObjectMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + return vals[i] != null && Objects.equals(unmaskNull(vals[i]), e.getValue()); + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + Enum2ObjectMap.this.remove(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2ReferenceMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public V getValue() { + return unmaskNull(vals[index]); + } + + @Override + public V setValue(V value) { + V old = getValue(); + vals[index] = maskNull(value); + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + return e.getKey() == keys[index] && Objects.equals(getValue(), e.getValue()); + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ Objects.hashCode(getValue()); + } + + @Override + public String toString() { + return keys[index] + "=" + getValue(); + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2ObjectMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == null) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != null) { + vals[current] = null; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2ReferenceMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements ObjectIterator { + + @Override + public V next() { + return unmaskNull(vals[advance()]); + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ObjectMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2ObjectMap.this.remove(o); + return true; + } + } + + private final class Values extends AbstractReferenceCollection { + + @Override + public ObjectIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(Object o) { + return containsValue(o); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ObjectMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ShortMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ShortMap.java new file mode 100644 index 0000000..2bd0323 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/Enum2ShortMap.java @@ -0,0 +1,542 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +import it.unimi.dsi.fastutil.objects.*; +import it.unimi.dsi.fastutil.shorts.AbstractShortCollection; +import it.unimi.dsi.fastutil.shorts.ShortBinaryOperator; +import it.unimi.dsi.fastutil.shorts.ShortCollection; +import it.unimi.dsi.fastutil.shorts.ShortIterator; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +/** 用枚举序号直接寻址的映射。槽位的零值表示缺少该键;读取缺失键时返回配置的默认值。 迭代器可复用同一个可变条目。 */ +public final class Enum2ShortMap> extends AbstractReference2ShortMap { + + private final Class keyType; + private final K[] keys; + private final short[] vals; + private int size; + + private final EntrySet entrySet = new EntrySet(); + private final ReferenceSet keySet = new KeySet(); + private final ShortCollection values = new Values(); + + /** 为该枚举的全部常量分配槽位。 */ + public Enum2ShortMap(Class keyType) { + this.keyType = keyType; + this.keys = EnumMaps.universe(keyType); + this.vals = new short[keys.length]; + } + + /** 复制槽位中的条目,使用新映射的初始默认返回值。 */ + public Enum2ShortMap(Enum2ShortMap map) { + this.keyType = map.keyType; + this.keys = map.keys; + this.vals = map.vals.clone(); + this.size = map.size; + } + + /** 返回此映射按序号直接寻址时使用的枚举类型。 */ + public Class keyType() { + return keyType; + } + + @Override + public short getShort(Object key) { + if (!isValidKey(key)) return defRetValue; + short v = vals[((Enum) key).ordinal()]; + return v != (short) 0 ? v : defRetValue; + } + + @Override + public short getOrDefault(Object key, short defaultValue) { + if (!isValidKey(key)) return defaultValue; + short v = vals[((Enum) key).ordinal()]; + return v != (short) 0 ? v : defaultValue; + } + + /** 写入零值会移除映射,缺失时返回默认返回值。 */ + @Override + public short put(K key, short value) { + int i = key.ordinal(); + short old = vals[i]; + vals[i] = value; + if (value == (short) 0) { + if (old != (short) 0) size--; + } else if (old == (short) 0) { + size++; + } + return old != (short) 0 ? old : defRetValue; + } + + @Override + public short removeShort(Object key) { + if (!isValidKey(key)) return defRetValue; + int i = ((Enum) key).ordinal(); + short old = vals[i]; + if (old == (short) 0) return defRetValue; + vals[i] = (short) 0; + size--; + return old; + } + + @Override + public boolean containsKey(Object key) { + return isValidKey(key) && vals[((Enum) key).ordinal()] != (short) 0; + } + + @Override + public boolean containsValue(short value) { + if (value == (short) 0) return false; + final var vals = Enum2ShortMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] == value) return true; + } + return false; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + if (size == 0) return; + Arrays.fill(vals, (short) 0); + size = 0; + } + + @Override + public void forEach(BiConsumer action) { + final var vals = Enum2ShortMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != (short) 0) action.accept(keys[i], Short.valueOf(vals[i])); + } + } + + @Override + public FastEntrySet reference2ShortEntrySet() { + return entrySet; + } + + @Override + public ReferenceSet keySet() { + return keySet; + } + + @Override + public ShortCollection values() { + return values; + } + + @Override + public short putIfAbsent(K key, short value) { + int i = key.ordinal(); + short old = vals[i]; + if (old != (short) 0) return old; + if (value != (short) 0) { + vals[i] = value; + size++; + } + return defRetValue; + } + + @Override + public boolean remove(Object key, short value) { + if (value == (short) 0 || !isValidKey(key)) return false; + int i = ((Enum) key).ordinal(); + if (vals[i] != value) return false; + vals[i] = (short) 0; + size--; + return true; + } + + @Override + public boolean replace(K key, short oldValue, short newValue) { + if (oldValue == (short) 0 || vals[key.ordinal()] != oldValue) return false; + put(key, newValue); + return true; + } + + @Override + public short replace(K key, short value) { + short old = vals[key.ordinal()]; + if (old == (short) 0) return defRetValue; + put(key, value); + return old; + } + + @Override + public short computeIfAbsent(K key, ToIntFunction mappingFunction) { + int i = key.ordinal(); + short v = vals[i]; + if (v != (short) 0) return v; + short newValue = (short) mappingFunction.applyAsInt(key); + if (newValue != (short) 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public short computeIfAbsent(K key, Reference2ShortFunction mappingFunction) { + int i = key.ordinal(); + short v = vals[i]; + if (v != (short) 0) return v; + short newValue = mappingFunction.getShort(key); + if (newValue != (short) 0) { + vals[i] = newValue; + size++; + } + return newValue; + } + + @Override + public short computeShortIfPresent(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + short old = vals[i]; + if (old == (short) 0) return defRetValue; + Short newValue = remappingFunction.apply(key, Short.valueOf(old)); + if (newValue == null) { + vals[i] = (short) 0; + size--; + return defRetValue; + } + put(key, newValue); + return newValue; + } + + @Override + public short computeShort(K key, BiFunction remappingFunction) { + int i = key.ordinal(); + short old = vals[i]; + Short newValue = remappingFunction.apply(key, old == (short) 0 ? null : Short.valueOf(old)); + if (newValue == null) { + if (old != (short) 0) { + vals[i] = (short) 0; + size--; + } + return defRetValue; + } + put(key, newValue); + return newValue; + } + + /** + * 将增量加到现有值上并返回旧值。缺失项从默认返回值开始累加,结果为零时清除该项。 + * + * @param key 要更新的枚举常量 + * @param incr 增量,允许为负 + * @return 累加前的值,缺少该键时返回默认值 + */ + public short addTo(K key, short incr) { + int i = key.ordinal(); + short old = vals[i]; + if (old == (short) 0) { + + short sum = (short) (defRetValue + incr); + if (sum == (short) 0) return defRetValue; + vals[i] = sum; + size++; + return defRetValue; + } + short sum = (short) (old + incr); + vals[i] = sum; + if (sum == (short) 0) size--; + return old; + } + + @Override + public short mergeShort(K key, short value, ShortBinaryOperator remappingFunction) { + int i = key.ordinal(); + short old = vals[i]; + short newValue = old == (short) 0 ? value : remappingFunction.apply(old, value); + if (newValue == (short) 0) { + if (old != (short) 0) { + vals[i] = (short) 0; + size--; + } + return defRetValue; + } + if (old == (short) 0) size++; + vals[i] = newValue; + return newValue; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Map m)) return false; + if (m.size() != size) return false; + if (o instanceof Enum2ShortMap other && other.keyType == keyType) { + return Arrays.equals(vals, other.vals); + } + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + short v = vals[i]; + if (v != (short) 0) { + Object ov = m.get(keys[i]); + if (!(ov instanceof Short sv) || sv.shortValue() != v) return false; + } + } + return true; + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public int hashCode() { + int h = 0; + final var vals = this.vals; + final var keys = this.keys; + for (int i = 0, n = vals.length; i < n; i++) { + short v = vals[i]; + if (v != (short) 0) h += keys[i].hashCode() ^ v; + } + return h; + } + + /** 同类型容器可直接沿值数组遍历。 */ + @Override + public void putAll(Map m) { + if (m instanceof Enum2ShortMap other && other.keyType == keyType) { + if (other.size == 0) return; + final short[] src = other.vals; + final short[] dst = this.vals; + int sz = this.size; + for (int i = 0, n = dst.length; i < n; i++) { + short v = src[i]; + if (v != (short) 0) { + if (dst[i] == (short) 0) sz++; + dst[i] = v; + } + } + this.size = sz; + return; + } + super.putAll(m); + } + + private boolean isValidKey(Object key) { + if (key == null) return false; + Class keyClass = key.getClass(); + return keyClass == keyType || keyClass.getSuperclass() == keyType; + } + + private final class EntrySet extends AbstractObjectSet> + implements Reference2ShortMap.FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new EntryIterator(); + } + + /** 迭代复用当前条目,下一次移动时内容会更新。 */ + @Override + public void fastForEach(Consumer> consumer) { + Entry entry = new Entry(); + final var vals = Enum2ShortMap.this.vals; + final int length = vals.length; + for (int i = 0; i < length; i++) { + if (vals[i] != (short) 0) { + entry.index = i; + consumer.accept(entry); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ShortMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (!isValidKey(e.getKey())) return false; + int i = ((Enum) e.getKey()).ordinal(); + Object ov = e.getValue(); + return vals[i] != (short) 0 && ov instanceof Short sv && sv.shortValue() == vals[i]; + } + + @Override + public boolean remove(Object o) { + if (!contains(o)) return false; + removeShort(((Map.Entry) o).getKey()); + return true; + } + } + + private final class Entry implements Reference2ShortMap.Entry { + + private int index = -1; + + @Override + public K getKey() { + return keys[index]; + } + + @Override + public short getShortValue() { + return vals[index]; + } + + @Override + public short setValue(short value) { + short old = vals[index]; + vals[index] = value; + if (value == (short) 0) { + if (old != (short) 0) size--; + } else if (old == (short) 0) { + size++; + } + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry e)) return false; + Object ov = e.getValue(); + return e.getKey() == keys[index] && ov instanceof Short sv && sv.shortValue() == vals[index]; + } + + @Override + public int hashCode() { + return keys[index].hashCode() ^ vals[index]; + } + + @Override + public String toString() { + return keys[index] + "=" + vals[index]; + } + } + + private abstract class IndexIterator { + + int cursor; + int current = -1; + + public boolean hasNext() { + final var vals = Enum2ShortMap.this.vals; + final int length = vals.length; + while (cursor < length && vals[cursor] == (short) 0) { + cursor++; + } + return cursor < length; + } + + int advance() { + if (!hasNext()) throw new NoSuchElementException(); + return current = cursor++; + } + + public void remove() { + if (current < 0) throw new IllegalStateException(); + if (vals[current] != (short) 0) { + vals[current] = (short) 0; + size--; + } + current = -1; + } + } + + private final class EntryIterator extends IndexIterator implements ObjectIterator> { + + private final Entry entry = new Entry(); + + @Override + public Reference2ShortMap.Entry next() { + entry.index = advance(); + return entry; + } + } + + private final class KeyIterator extends IndexIterator implements ObjectIterator { + + @Override + public K next() { + return keys[advance()]; + } + } + + private final class ValueIterator extends IndexIterator implements ShortIterator { + + @Override + public short nextShort() { + return vals[advance()]; + } + } + + private final class KeySet extends AbstractReferenceSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ShortMap.this.clear(); + } + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + if (!containsKey(o)) return false; + Enum2ShortMap.this.removeShort(o); + return true; + } + } + + private final class Values extends AbstractShortCollection { + + @Override + public ShortIterator iterator() { + return new ValueIterator(); + } + + @Override + public boolean contains(short value) { + return Enum2ShortMap.this.containsValue(value); + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Enum2ShortMap.this.clear(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/EnumMaps.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/EnumMaps.java new file mode 100644 index 0000000..0448691 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/enums/EnumMaps.java @@ -0,0 +1,21 @@ +package com.modularmc.mmclutils.api.collection.map.enums; + +/** 缓存每种枚举类型的常量,供按序号寻址的容器共用。 */ +public final class EnumMaps { + + private EnumMaps() {} + + private static final ClassValue KEY_UNIVERSES = new ClassValue<>() { + + @Override + protected Object[] computeValue(Class type) { + return type.getEnumConstants(); + } + }; + + /** 按声明顺序返回共享枚举常量数组。槽位索引等于枚举序号,调用方须保持数组只读。 */ + @SuppressWarnings("unchecked") + public static > K[] universe(Class keyType) { + return (K[]) KEY_UNIVERSES.get(keyType); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2BooleanOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2BooleanOpenCachedHashMap.java new file mode 100644 index 0000000..762cc8c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2BooleanOpenCachedHashMap.java @@ -0,0 +1,1129 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.booleans.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2BooleanOpenCachedHashMap extends Object2BooleanOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2BooleanOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2BooleanOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2BooleanOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2BooleanOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2BooleanOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2BooleanOpenCachedHashMap(final Object2BooleanMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2BooleanOpenCachedHashMap(final Object2BooleanMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private boolean removeEntry(int pos) { + final boolean oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final boolean[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = false; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private boolean removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final boolean oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final boolean v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public boolean put(final K k, final boolean v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final boolean oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public boolean removeBoolean(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public boolean getBoolean(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public boolean getOrDefault(final Object k, final boolean defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean putIfAbsent(final K k, final boolean v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final boolean v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final boolean oldValue, final boolean v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public boolean replace(final K k, final boolean v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final boolean oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public boolean computeIfAbsent(final K k, final Predicate mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final boolean newValue = mappingFunction.test(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public boolean computeIfAbsent(final K k, final Object2BooleanFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final boolean newValue = mappingFunction.getBoolean(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public boolean computeBooleanIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Boolean newValue = remappingFunction.apply((k), Boolean.valueOf(value[pos])); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public boolean computeBoolean(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Boolean newValue = remappingFunction.apply((k), pos >= 0 ? Boolean.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + boolean newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public boolean merge(final K k, final boolean v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Boolean newValue = remappingFunction.apply(Boolean.valueOf(value[pos]), Boolean.valueOf(v)); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectBooleanPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public boolean getBooleanValue() { + return value[index]; + } + + @Override + public boolean rightBoolean() { + return value[index]; + } + + @Override + public boolean setValue(final boolean v) { + final boolean oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectBooleanPair right(final boolean v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Boolean getValue() { + return value[index]; + } + + @Deprecated + @Override + public Boolean setValue(final Boolean v) { + return Boolean.valueOf(setValue((v).booleanValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).booleanValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ (value[index] ? 1231 : 1237); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2BooleanOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + final int[] hash = Object2BooleanOpenCachedHashMap.this.hash; + final int mask = Object2BooleanOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + final int[] hash = Object2BooleanOpenCachedHashMap.this.hash; + final int mask = Object2BooleanOpenCachedHashMap.this.mask; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + final boolean[] value = Object2BooleanOpenCachedHashMap.this.value; + final int[] hash = Object2BooleanOpenCachedHashMap.this.hash; + final int mask = Object2BooleanOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2BooleanOpenCachedHashMap.this.removeBoolean(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2BooleanOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Boolean)) return false; + final K k = ((K) e.getKey()); + final boolean v = ((Boolean) (e.getValue())).booleanValue(); + if (((k) == null)) return Object2BooleanOpenCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + final int mask = Object2BooleanOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Boolean)) return false; + final K k = ((K) e.getKey()); + final boolean v = ((Boolean) (e.getValue())).booleanValue(); + if (((k) == null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + final int mask = Object2BooleanOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2BooleanOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2BooleanEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2BooleanOpenCachedHashMap.this.removeBoolean(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2BooleanOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements BooleanIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final BooleanConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public boolean nextBoolean() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements BooleanSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = BooleanSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : BooleanSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final BooleanConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public BooleanCollection values() { + if (values == null) values = new AbstractBooleanCollection() { + + @Override + public BooleanIterator iterator() { + return new ValueIterator(); + } + + @Override + public BooleanSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final BooleanConsumer consumer) { + final K[] key = Object2BooleanOpenCachedHashMap.this.key; + final boolean[] value = Object2BooleanOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(boolean v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2BooleanOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final boolean[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final boolean[] newValue = new boolean[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2BooleanOpenCachedHashMap clone() { + Object2BooleanOpenCachedHashMap c = (Object2BooleanOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final boolean[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= (value[i] ? 1231 : 1237); + h += t; + i++; + } + if (containsNullKey) h += (value[n] ? 1231 : 1237); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java new file mode 100644 index 0000000..8d373ff --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java @@ -0,0 +1,1143 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.booleans.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2BooleanOpenCustomCachedHashMap extends Object2BooleanOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2BooleanOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2BooleanOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2BooleanOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2BooleanOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2BooleanOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2BooleanOpenCustomCachedHashMap(final Object2BooleanMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2BooleanOpenCustomCachedHashMap(final Object2BooleanMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private boolean removeEntry(int pos) { + final boolean oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final boolean[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = false; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private boolean removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final boolean oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final boolean v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public boolean put(final K k, final boolean v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final boolean oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public boolean removeBoolean(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public boolean getBoolean(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public boolean getOrDefault(final Object k, final boolean defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean putIfAbsent(final K k, final boolean v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final boolean v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final boolean oldValue, final boolean v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public boolean replace(final K k, final boolean v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final boolean oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public boolean computeIfAbsent(final K k, final Predicate mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final boolean newValue = mappingFunction.test(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public boolean computeIfAbsent(final K k, final Object2BooleanFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final boolean newValue = mappingFunction.getBoolean(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public boolean computeBooleanIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Boolean newValue = remappingFunction.apply((k), Boolean.valueOf(value[pos])); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public boolean computeBoolean(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Boolean newValue = remappingFunction.apply((k), pos >= 0 ? Boolean.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + boolean newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public boolean merge(final K k, final boolean v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Boolean newValue = remappingFunction.apply(Boolean.valueOf(value[pos]), Boolean.valueOf(v)); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectBooleanPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public boolean getBooleanValue() { + return value[index]; + } + + @Override + public boolean rightBoolean() { + return value[index]; + } + + @Override + public boolean setValue(final boolean v) { + final boolean oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectBooleanPair right(final boolean v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Boolean getValue() { + return value[index]; + } + + @Deprecated + @Override + public Boolean setValue(final Boolean v) { + return Boolean.valueOf(setValue((v).booleanValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).booleanValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ (value[index] ? 1231 : 1237); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2BooleanOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + final int[] hash = Object2BooleanOpenCustomCachedHashMap.this.hash; + final int mask = Object2BooleanOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + final int[] hash = Object2BooleanOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + final boolean[] value = Object2BooleanOpenCustomCachedHashMap.this.value; + final int[] hash = Object2BooleanOpenCustomCachedHashMap.this.hash; + final int mask = Object2BooleanOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2BooleanOpenCustomCachedHashMap.this.removeBoolean(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2BooleanOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Boolean)) return false; + final K k = ((K) e.getKey()); + final boolean v = ((Boolean) (e.getValue())).booleanValue(); + if (strategy.equals(k, null)) return Object2BooleanOpenCustomCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + final int mask = Object2BooleanOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Boolean)) return false; + final K k = ((K) e.getKey()); + final boolean v = ((Boolean) (e.getValue())).booleanValue(); + if (strategy.equals(k, null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + final int mask = Object2BooleanOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2BooleanOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2BooleanEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2BooleanOpenCustomCachedHashMap.this.removeBoolean(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2BooleanOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements BooleanIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final BooleanConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public boolean nextBoolean() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements BooleanSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = BooleanSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : BooleanSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final BooleanConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public BooleanCollection values() { + if (values == null) values = new AbstractBooleanCollection() { + + @Override + public BooleanIterator iterator() { + return new ValueIterator(); + } + + @Override + public BooleanSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final BooleanConsumer consumer) { + final K[] key = Object2BooleanOpenCustomCachedHashMap.this.key; + final boolean[] value = Object2BooleanOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(boolean v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2BooleanOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final boolean[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final boolean[] newValue = new boolean[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2BooleanOpenCustomCachedHashMap clone() { + Object2BooleanOpenCustomCachedHashMap c = (Object2BooleanOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final boolean[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= (value[i] ? 1231 : 1237); + h += t; + i++; + } + if (containsNullKey) h += (value[n] ? 1231 : 1237); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ByteOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ByteOpenCachedHashMap.java new file mode 100644 index 0000000..f5efea6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ByteOpenCachedHashMap.java @@ -0,0 +1,1178 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.bytes.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2ByteOpenCachedHashMap extends Object2ByteOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2ByteOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2ByteOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2ByteOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2ByteOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2ByteOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2ByteOpenCachedHashMap(final Object2ByteMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2ByteOpenCachedHashMap(final Object2ByteMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private byte removeEntry(int pos) { + final byte oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final byte[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private byte removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final byte oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final byte v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public byte put(final K k, final byte v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final byte oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private byte addToValue(final int pos, final byte incr) { + final byte oldValue = value[pos]; + value[pos] = (byte) (oldValue + incr); + return oldValue; + } + + @Override + public byte addTo(final K k, final byte incr) { + int pos, h = 0; + if (k == null) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (curr == k || curr.equals(k))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = (byte) (defRetValue + incr); + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public byte removeByte(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public byte getByte(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public byte getOrDefault(final Object k, final byte defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public byte putIfAbsent(final K k, final byte v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final byte v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final byte oldValue, final byte v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public byte replace(final K k, final byte v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final byte oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public byte computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final byte newValue = SafeMath.safeIntToByte(mappingFunction.applyAsInt(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public byte computeIfAbsent(final K k, final Object2ByteFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final byte newValue = mappingFunction.getByte(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public byte computeByteIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Byte newValue = remappingFunction.apply((k), Byte.valueOf(value[pos])); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public byte computeByte(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Byte newValue = remappingFunction.apply((k), pos >= 0 ? Byte.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + byte newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public byte mergeByte(final K k, final byte v, ByteBinaryOperator remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final byte newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public byte merge(final K k, final byte v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Byte newValue = remappingFunction.apply(Byte.valueOf(value[pos]), Byte.valueOf(v)); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectBytePair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public byte getByteValue() { + return value[index]; + } + + @Override + public byte rightByte() { + return value[index]; + } + + @Override + public byte setValue(final byte v) { + final byte oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectBytePair right(final byte v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Byte getValue() { + return value[index]; + } + + @Deprecated + @Override + public Byte setValue(final Byte v) { + return Byte.valueOf(setValue((v).byteValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).byteValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2ByteOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2ByteOpenCachedHashMap.this.key; + final int[] hash = Object2ByteOpenCachedHashMap.this.hash; + final int mask = Object2ByteOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2ByteOpenCachedHashMap.this.key; + final int[] hash = Object2ByteOpenCachedHashMap.this.hash; + final int mask = Object2ByteOpenCachedHashMap.this.mask; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2ByteOpenCachedHashMap.this.key; + final byte[] value = Object2ByteOpenCachedHashMap.this.value; + final int[] hash = Object2ByteOpenCachedHashMap.this.hash; + final int mask = Object2ByteOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2ByteOpenCachedHashMap.this.removeByte(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2ByteOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2ByteOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2ByteOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2ByteOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Byte)) return false; + final K k = ((K) e.getKey()); + final byte v = ((Byte) (e.getValue())).byteValue(); + if (((k) == null)) return Object2ByteOpenCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2ByteOpenCachedHashMap.this.key; + final int mask = Object2ByteOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Byte)) return false; + final K k = ((K) e.getKey()); + final byte v = ((Byte) (e.getValue())).byteValue(); + if (((k) == null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2ByteOpenCachedHashMap.this.key; + final int mask = Object2ByteOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2ByteOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2ByteOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2ByteOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2ByteEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ByteOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2ByteOpenCachedHashMap.this.removeByte(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2ByteOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements ByteIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final ByteConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public byte nextByte() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements ByteSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ByteSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ByteSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final ByteConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public ByteCollection values() { + if (values == null) values = new AbstractByteCollection() { + + @Override + public ByteIterator iterator() { + return new ValueIterator(); + } + + @Override + public ByteSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final ByteConsumer consumer) { + final K[] key = Object2ByteOpenCachedHashMap.this.key; + final byte[] value = Object2ByteOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(byte v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2ByteOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final byte[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final byte[] newValue = new byte[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2ByteOpenCachedHashMap clone() { + Object2ByteOpenCachedHashMap c = (Object2ByteOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final byte[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java new file mode 100644 index 0000000..3f13c1a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java @@ -0,0 +1,1192 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.bytes.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2ByteOpenCustomCachedHashMap extends Object2ByteOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ByteOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2ByteOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2ByteOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ByteOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2ByteOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ByteOpenCustomCachedHashMap(final Object2ByteMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2ByteOpenCustomCachedHashMap(final Object2ByteMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private byte removeEntry(int pos) { + final byte oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final byte[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private byte removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final byte oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final byte v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public byte put(final K k, final byte v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final byte oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private byte addToValue(final int pos, final byte incr) { + final byte oldValue = value[pos]; + value[pos] = (byte) (oldValue + incr); + return oldValue; + } + + @Override + public byte addTo(final K k, final byte incr) { + int pos, h = 0; + if (strategy.equals(k, null)) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = (byte) (defRetValue + incr); + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public byte removeByte(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public byte getByte(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public byte getOrDefault(final Object k, final byte defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public byte putIfAbsent(final K k, final byte v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final byte v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final byte oldValue, final byte v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public byte replace(final K k, final byte v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final byte oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public byte computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final byte newValue = SafeMath.safeIntToByte(mappingFunction.applyAsInt(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public byte computeIfAbsent(final K k, final Object2ByteFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final byte newValue = mappingFunction.getByte(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public byte computeByteIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Byte newValue = remappingFunction.apply((k), Byte.valueOf(value[pos])); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public byte computeByte(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Byte newValue = remappingFunction.apply((k), pos >= 0 ? Byte.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + byte newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public byte mergeByte(final K k, final byte v, ByteBinaryOperator remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final byte newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public byte merge(final K k, final byte v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Byte newValue = remappingFunction.apply(Byte.valueOf(value[pos]), Byte.valueOf(v)); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectBytePair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public byte getByteValue() { + return value[index]; + } + + @Override + public byte rightByte() { + return value[index]; + } + + @Override + public byte setValue(final byte v) { + final byte oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectBytePair right(final byte v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Byte getValue() { + return value[index]; + } + + @Deprecated + @Override + public Byte setValue(final Byte v) { + return Byte.valueOf(setValue((v).byteValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).byteValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2ByteOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + final int[] hash = Object2ByteOpenCustomCachedHashMap.this.hash; + final int mask = Object2ByteOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + final int[] hash = Object2ByteOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + final byte[] value = Object2ByteOpenCustomCachedHashMap.this.value; + final int[] hash = Object2ByteOpenCustomCachedHashMap.this.hash; + final int mask = Object2ByteOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2ByteOpenCustomCachedHashMap.this.removeByte(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2ByteOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Byte)) return false; + final K k = ((K) e.getKey()); + final byte v = ((Byte) (e.getValue())).byteValue(); + if (strategy.equals(k, null)) return Object2ByteOpenCustomCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + final int mask = Object2ByteOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Byte)) return false; + final K k = ((K) e.getKey()); + final byte v = ((Byte) (e.getValue())).byteValue(); + if (strategy.equals(k, null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + final int mask = Object2ByteOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2ByteOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2ByteEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2ByteOpenCustomCachedHashMap.this.removeByte(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2ByteOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements ByteIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final ByteConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public byte nextByte() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements ByteSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ByteSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ByteSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final ByteConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public ByteCollection values() { + if (values == null) values = new AbstractByteCollection() { + + @Override + public ByteIterator iterator() { + return new ValueIterator(); + } + + @Override + public ByteSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final ByteConsumer consumer) { + final K[] key = Object2ByteOpenCustomCachedHashMap.this.key; + final byte[] value = Object2ByteOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(byte v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2ByteOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final byte[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final byte[] newValue = new byte[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2ByteOpenCustomCachedHashMap clone() { + Object2ByteOpenCustomCachedHashMap c = (Object2ByteOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final byte[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2CharOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2CharOpenCachedHashMap.java new file mode 100644 index 0000000..25d01df --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2CharOpenCachedHashMap.java @@ -0,0 +1,1178 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.chars.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2CharOpenCachedHashMap extends Object2CharOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2CharOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2CharOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2CharOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2CharOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2CharOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2CharOpenCachedHashMap(final Object2CharMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2CharOpenCachedHashMap(final Object2CharMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private char removeEntry(int pos) { + final char oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final char[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private char removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final char oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final char v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public char put(final K k, final char v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final char oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private char addToValue(final int pos, final char incr) { + final char oldValue = value[pos]; + value[pos] = (char) (oldValue + incr); + return oldValue; + } + + @Override + public char addTo(final K k, final char incr) { + int pos, h = 0; + if (k == null) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (curr == k || curr.equals(k))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = (char) (defRetValue + incr); + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public char removeChar(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public char getChar(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public char getOrDefault(final Object k, final char defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public char putIfAbsent(final K k, final char v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final char v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final char oldValue, final char v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public char replace(final K k, final char v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final char oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public char computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final char newValue = SafeMath.safeIntToChar(mappingFunction.applyAsInt(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public char computeIfAbsent(final K k, final Object2CharFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final char newValue = mappingFunction.getChar(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public char computeCharIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Character newValue = remappingFunction.apply((k), Character.valueOf(value[pos])); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public char computeChar(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Character newValue = remappingFunction.apply((k), pos >= 0 ? Character.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + char newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public char mergeChar(final K k, final char v, CharBinaryOperator remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final char newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public char merge(final K k, final char v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Character newValue = remappingFunction.apply(Character.valueOf(value[pos]), Character.valueOf(v)); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectCharPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public char getCharValue() { + return value[index]; + } + + @Override + public char rightChar() { + return value[index]; + } + + @Override + public char setValue(final char v) { + final char oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectCharPair right(final char v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Character getValue() { + return value[index]; + } + + @Deprecated + @Override + public Character setValue(final Character v) { + return Character.valueOf(setValue((v).charValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).charValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2CharOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2CharOpenCachedHashMap.this.key; + final int[] hash = Object2CharOpenCachedHashMap.this.hash; + final int mask = Object2CharOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2CharOpenCachedHashMap.this.key; + final int[] hash = Object2CharOpenCachedHashMap.this.hash; + final int mask = Object2CharOpenCachedHashMap.this.mask; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2CharOpenCachedHashMap.this.key; + final char[] value = Object2CharOpenCachedHashMap.this.value; + final int[] hash = Object2CharOpenCachedHashMap.this.hash; + final int mask = Object2CharOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2CharOpenCachedHashMap.this.removeChar(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2CharOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2CharOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2CharOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2CharOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Character)) return false; + final K k = ((K) e.getKey()); + final char v = ((Character) (e.getValue())).charValue(); + if (((k) == null)) return Object2CharOpenCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2CharOpenCachedHashMap.this.key; + final int mask = Object2CharOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Character)) return false; + final K k = ((K) e.getKey()); + final char v = ((Character) (e.getValue())).charValue(); + if (((k) == null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2CharOpenCachedHashMap.this.key; + final int mask = Object2CharOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2CharOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2CharOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2CharOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2CharEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2CharOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2CharOpenCachedHashMap.this.removeChar(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2CharOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements CharIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final CharConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public char nextChar() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements CharSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = CharSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : CharSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final CharConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public CharCollection values() { + if (values == null) values = new AbstractCharCollection() { + + @Override + public CharIterator iterator() { + return new ValueIterator(); + } + + @Override + public CharSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final CharConsumer consumer) { + final K[] key = Object2CharOpenCachedHashMap.this.key; + final char[] value = Object2CharOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(char v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2CharOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final char[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final char[] newValue = new char[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2CharOpenCachedHashMap clone() { + Object2CharOpenCachedHashMap c = (Object2CharOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final char[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2CharOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2CharOpenCustomCachedHashMap.java new file mode 100644 index 0000000..926d1f1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2CharOpenCustomCachedHashMap.java @@ -0,0 +1,1192 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.chars.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2CharOpenCustomCachedHashMap extends Object2CharOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2CharOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2CharOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2CharOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2CharOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2CharOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2CharOpenCustomCachedHashMap(final Object2CharMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2CharOpenCustomCachedHashMap(final Object2CharMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private char removeEntry(int pos) { + final char oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final char[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private char removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final char oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final char v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public char put(final K k, final char v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final char oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private char addToValue(final int pos, final char incr) { + final char oldValue = value[pos]; + value[pos] = (char) (oldValue + incr); + return oldValue; + } + + @Override + public char addTo(final K k, final char incr) { + int pos, h = 0; + if (strategy.equals(k, null)) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = (char) (defRetValue + incr); + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public char removeChar(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public char getChar(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public char getOrDefault(final Object k, final char defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public char putIfAbsent(final K k, final char v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final char v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final char oldValue, final char v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public char replace(final K k, final char v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final char oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public char computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final char newValue = SafeMath.safeIntToChar(mappingFunction.applyAsInt(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public char computeIfAbsent(final K k, final Object2CharFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final char newValue = mappingFunction.getChar(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public char computeCharIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Character newValue = remappingFunction.apply((k), Character.valueOf(value[pos])); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public char computeChar(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Character newValue = remappingFunction.apply((k), pos >= 0 ? Character.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + char newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public char mergeChar(final K k, final char v, CharBinaryOperator remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final char newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public char merge(final K k, final char v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Character newValue = remappingFunction.apply(Character.valueOf(value[pos]), Character.valueOf(v)); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectCharPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public char getCharValue() { + return value[index]; + } + + @Override + public char rightChar() { + return value[index]; + } + + @Override + public char setValue(final char v) { + final char oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectCharPair right(final char v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Character getValue() { + return value[index]; + } + + @Deprecated + @Override + public Character setValue(final Character v) { + return Character.valueOf(setValue((v).charValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).charValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2CharOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + final int[] hash = Object2CharOpenCustomCachedHashMap.this.hash; + final int mask = Object2CharOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + final int[] hash = Object2CharOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + final char[] value = Object2CharOpenCustomCachedHashMap.this.value; + final int[] hash = Object2CharOpenCustomCachedHashMap.this.hash; + final int mask = Object2CharOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2CharOpenCustomCachedHashMap.this.removeChar(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2CharOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Character)) return false; + final K k = ((K) e.getKey()); + final char v = ((Character) (e.getValue())).charValue(); + if (strategy.equals(k, null)) return Object2CharOpenCustomCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + final int mask = Object2CharOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Character)) return false; + final K k = ((K) e.getKey()); + final char v = ((Character) (e.getValue())).charValue(); + if (strategy.equals(k, null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + final int mask = Object2CharOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2CharOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2CharEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2CharOpenCustomCachedHashMap.this.removeChar(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2CharOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements CharIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final CharConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public char nextChar() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements CharSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = CharSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : CharSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final CharConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public CharCollection values() { + if (values == null) values = new AbstractCharCollection() { + + @Override + public CharIterator iterator() { + return new ValueIterator(); + } + + @Override + public CharSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final CharConsumer consumer) { + final K[] key = Object2CharOpenCustomCachedHashMap.this.key; + final char[] value = Object2CharOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(char v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2CharOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final char[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final char[] newValue = new char[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2CharOpenCustomCachedHashMap clone() { + Object2CharOpenCustomCachedHashMap c = (Object2CharOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final char[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2DoubleOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2DoubleOpenCachedHashMap.java new file mode 100644 index 0000000..bac8a3d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2DoubleOpenCachedHashMap.java @@ -0,0 +1,1179 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.doubles.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.DoubleBinaryOperator; +import java.util.function.DoubleConsumer; +import java.util.function.ToDoubleFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2DoubleOpenCachedHashMap extends Object2DoubleOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2DoubleOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2DoubleOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2DoubleOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2DoubleOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2DoubleOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2DoubleOpenCachedHashMap(final Object2DoubleMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2DoubleOpenCachedHashMap(final Object2DoubleMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private double removeEntry(int pos) { + final double oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final double[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0d; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private double removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final double oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final double v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public double put(final K k, final double v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final double oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private double addToValue(final int pos, final double incr) { + final double oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public double addTo(final K k, final double incr) { + int pos, h = 0; + if (k == null) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (curr == k || curr.equals(k))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public double removeDouble(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public double getDouble(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public double getOrDefault(final Object k, final double defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public double putIfAbsent(final K k, final double v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final double v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final double oldValue, final double v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public double replace(final K k, final double v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final double oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public double computeIfAbsent(final K k, final ToDoubleFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final double newValue = mappingFunction.applyAsDouble(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public double computeIfAbsent(final K k, final Object2DoubleFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final double newValue = mappingFunction.getDouble(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public double computeDoubleIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Double newValue = remappingFunction.apply((k), Double.valueOf(value[pos])); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public double computeDouble(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Double newValue = remappingFunction.apply((k), pos >= 0 ? Double.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + double newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public double mergeDouble(final K k, final double v, DoubleBinaryOperator remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final double newValue = remappingFunction.applyAsDouble(value[pos], v); + return value[pos] = newValue; + } + + @Override + public double merge(final K k, final double v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Double newValue = remappingFunction.apply(Double.valueOf(value[pos]), Double.valueOf(v)); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectDoublePair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public double getDoubleValue() { + return value[index]; + } + + @Override + public double rightDouble() { + return value[index]; + } + + @Override + public double setValue(final double v) { + final double oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectDoublePair right(final double v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Double getValue() { + return value[index]; + } + + @Deprecated + @Override + public Double setValue(final Double v) { + return Double.valueOf(setValue((v).doubleValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && (Double.doubleToRawLongBits(value[index]) == Double.doubleToRawLongBits((e.getValue()).doubleValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ HashCommon.double2int(value[index]); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2DoubleOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + final int[] hash = Object2DoubleOpenCachedHashMap.this.hash; + final int mask = Object2DoubleOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + final int[] hash = Object2DoubleOpenCachedHashMap.this.hash; + final int mask = Object2DoubleOpenCachedHashMap.this.mask; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + final double[] value = Object2DoubleOpenCachedHashMap.this.value; + final int[] hash = Object2DoubleOpenCachedHashMap.this.hash; + final int mask = Object2DoubleOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2DoubleOpenCachedHashMap.this.removeDouble(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2DoubleOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Double)) return false; + final K k = ((K) e.getKey()); + final double v = ((Double) (e.getValue())).doubleValue(); + if (((k) == null)) return Object2DoubleOpenCachedHashMap.this.containsNullKey && (Double.doubleToRawLongBits(value[n]) == Double.doubleToRawLongBits(v)); + K curr; + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + final int mask = Object2DoubleOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return (Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return (Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Double)) return false; + final K k = ((K) e.getKey()); + final double v = ((Double) (e.getValue())).doubleValue(); + if (((k) == null)) { + if (containsNullKey && (Double.doubleToRawLongBits(value[n]) == Double.doubleToRawLongBits(v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + final int mask = Object2DoubleOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if ((Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if ((Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2DoubleOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2DoubleEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2DoubleOpenCachedHashMap.this.removeDouble(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2DoubleOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements DoubleIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final DoubleConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public double nextDouble() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements DoubleSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = DoubleSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : DoubleSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final DoubleConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public DoubleCollection values() { + if (values == null) values = new AbstractDoubleCollection() { + + @Override + public DoubleIterator iterator() { + return new ValueIterator(); + } + + @Override + public DoubleSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final DoubleConsumer consumer) { + final K[] key = Object2DoubleOpenCachedHashMap.this.key; + final double[] value = Object2DoubleOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(double v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2DoubleOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final double[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final double[] newValue = new double[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2DoubleOpenCachedHashMap clone() { + Object2DoubleOpenCachedHashMap c = (Object2DoubleOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final double[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= HashCommon.double2int(value[i]); + h += t; + i++; + } + if (containsNullKey) h += HashCommon.double2int(value[n]); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java new file mode 100644 index 0000000..ff5d3d7 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java @@ -0,0 +1,1193 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.doubles.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.DoubleBinaryOperator; +import java.util.function.DoubleConsumer; +import java.util.function.ToDoubleFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2DoubleOpenCustomCachedHashMap extends Object2DoubleOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2DoubleOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2DoubleOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2DoubleOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2DoubleOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2DoubleOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2DoubleOpenCustomCachedHashMap(final Object2DoubleMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2DoubleOpenCustomCachedHashMap(final Object2DoubleMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private double removeEntry(int pos) { + final double oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final double[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0d; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private double removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final double oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final double v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public double put(final K k, final double v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final double oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private double addToValue(final int pos, final double incr) { + final double oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public double addTo(final K k, final double incr) { + int pos, h = 0; + if (strategy.equals(k, null)) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public double removeDouble(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public double getDouble(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public double getOrDefault(final Object k, final double defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public double putIfAbsent(final K k, final double v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final double v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final double oldValue, final double v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public double replace(final K k, final double v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final double oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public double computeIfAbsent(final K k, final ToDoubleFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final double newValue = mappingFunction.applyAsDouble(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public double computeIfAbsent(final K k, final Object2DoubleFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final double newValue = mappingFunction.getDouble(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public double computeDoubleIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Double newValue = remappingFunction.apply((k), Double.valueOf(value[pos])); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public double computeDouble(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Double newValue = remappingFunction.apply((k), pos >= 0 ? Double.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + double newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public double mergeDouble(final K k, final double v, DoubleBinaryOperator remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final double newValue = remappingFunction.applyAsDouble(value[pos], v); + return value[pos] = newValue; + } + + @Override + public double merge(final K k, final double v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Double newValue = remappingFunction.apply(Double.valueOf(value[pos]), Double.valueOf(v)); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectDoublePair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public double getDoubleValue() { + return value[index]; + } + + @Override + public double rightDouble() { + return value[index]; + } + + @Override + public double setValue(final double v) { + final double oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectDoublePair right(final double v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Double getValue() { + return value[index]; + } + + @Deprecated + @Override + public Double setValue(final Double v) { + return Double.valueOf(setValue((v).doubleValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && (Double.doubleToRawLongBits(value[index]) == Double.doubleToRawLongBits((e.getValue()).doubleValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ HashCommon.double2int(value[index]); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2DoubleOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + final int[] hash = Object2DoubleOpenCustomCachedHashMap.this.hash; + final int mask = Object2DoubleOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + final int[] hash = Object2DoubleOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + final double[] value = Object2DoubleOpenCustomCachedHashMap.this.value; + final int[] hash = Object2DoubleOpenCustomCachedHashMap.this.hash; + final int mask = Object2DoubleOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2DoubleOpenCustomCachedHashMap.this.removeDouble(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2DoubleOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Double)) return false; + final K k = ((K) e.getKey()); + final double v = ((Double) (e.getValue())).doubleValue(); + if (strategy.equals(k, null)) return Object2DoubleOpenCustomCachedHashMap.this.containsNullKey && (Double.doubleToRawLongBits(value[n]) == Double.doubleToRawLongBits(v)); + K curr; + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + final int mask = Object2DoubleOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return (Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return (Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Double)) return false; + final K k = ((K) e.getKey()); + final double v = ((Double) (e.getValue())).doubleValue(); + if (strategy.equals(k, null)) { + if (containsNullKey && (Double.doubleToRawLongBits(value[n]) == Double.doubleToRawLongBits(v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + final int mask = Object2DoubleOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if ((Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if ((Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2DoubleOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2DoubleEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2DoubleOpenCustomCachedHashMap.this.removeDouble(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2DoubleOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements DoubleIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final DoubleConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public double nextDouble() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements DoubleSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = DoubleSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : DoubleSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final DoubleConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public DoubleCollection values() { + if (values == null) values = new AbstractDoubleCollection() { + + @Override + public DoubleIterator iterator() { + return new ValueIterator(); + } + + @Override + public DoubleSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final DoubleConsumer consumer) { + final K[] key = Object2DoubleOpenCustomCachedHashMap.this.key; + final double[] value = Object2DoubleOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(double v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2DoubleOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final double[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final double[] newValue = new double[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2DoubleOpenCustomCachedHashMap clone() { + Object2DoubleOpenCustomCachedHashMap c = (Object2DoubleOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final double[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= HashCommon.double2int(value[i]); + h += t; + i++; + } + if (containsNullKey) h += HashCommon.double2int(value[n]); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2FloatOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2FloatOpenCachedHashMap.java new file mode 100644 index 0000000..1b2dcc4 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2FloatOpenCachedHashMap.java @@ -0,0 +1,1178 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.floats.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToDoubleFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2FloatOpenCachedHashMap extends Object2FloatOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2FloatOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2FloatOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2FloatOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2FloatOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2FloatOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2FloatOpenCachedHashMap(final Object2FloatMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2FloatOpenCachedHashMap(final Object2FloatMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private float removeEntry(int pos) { + final float oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final float[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0f; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private float removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final float oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final float v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public float put(final K k, final float v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final float oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private float addToValue(final int pos, final float incr) { + final float oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public float addTo(final K k, final float incr) { + int pos, h = 0; + if (k == null) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (curr == k || curr.equals(k))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public float removeFloat(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public float getFloat(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public float getOrDefault(final Object k, final float defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public float putIfAbsent(final K k, final float v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final float v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final float oldValue, final float v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public float replace(final K k, final float v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final float oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public float computeIfAbsent(final K k, final ToDoubleFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final float newValue = SafeMath.safeDoubleToFloat(mappingFunction.applyAsDouble(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public float computeIfAbsent(final K k, final Object2FloatFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final float newValue = mappingFunction.getFloat(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public float computeFloatIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Float newValue = remappingFunction.apply((k), Float.valueOf(value[pos])); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public float computeFloat(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Float newValue = remappingFunction.apply((k), pos >= 0 ? Float.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + float newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public float mergeFloat(final K k, final float v, FloatBinaryOperator remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final float newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public float merge(final K k, final float v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Float newValue = remappingFunction.apply(Float.valueOf(value[pos]), Float.valueOf(v)); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectFloatPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public float getFloatValue() { + return value[index]; + } + + @Override + public float rightFloat() { + return value[index]; + } + + @Override + public float setValue(final float v) { + final float oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectFloatPair right(final float v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Float getValue() { + return value[index]; + } + + @Deprecated + @Override + public Float setValue(final Float v) { + return Float.valueOf(setValue((v).floatValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && (Float.floatToRawIntBits(value[index]) == Float.floatToRawIntBits((e.getValue()).floatValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ HashCommon.float2int(value[index]); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2FloatOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2FloatOpenCachedHashMap.this.key; + final int[] hash = Object2FloatOpenCachedHashMap.this.hash; + final int mask = Object2FloatOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2FloatOpenCachedHashMap.this.key; + final int[] hash = Object2FloatOpenCachedHashMap.this.hash; + final int mask = Object2FloatOpenCachedHashMap.this.mask; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2FloatOpenCachedHashMap.this.key; + final float[] value = Object2FloatOpenCachedHashMap.this.value; + final int[] hash = Object2FloatOpenCachedHashMap.this.hash; + final int mask = Object2FloatOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2FloatOpenCachedHashMap.this.removeFloat(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2FloatOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2FloatOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2FloatOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2FloatOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Float)) return false; + final K k = ((K) e.getKey()); + final float v = ((Float) (e.getValue())).floatValue(); + if (((k) == null)) return Object2FloatOpenCachedHashMap.this.containsNullKey && (Float.floatToRawIntBits(value[n]) == Float.floatToRawIntBits(v)); + K curr; + final K[] key = Object2FloatOpenCachedHashMap.this.key; + final int mask = Object2FloatOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return (Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return (Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Float)) return false; + final K k = ((K) e.getKey()); + final float v = ((Float) (e.getValue())).floatValue(); + if (((k) == null)) { + if (containsNullKey && (Float.floatToRawIntBits(value[n]) == Float.floatToRawIntBits(v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2FloatOpenCachedHashMap.this.key; + final int mask = Object2FloatOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if ((Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if ((Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2FloatOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2FloatOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2FloatOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2FloatEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2FloatOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2FloatOpenCachedHashMap.this.removeFloat(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2FloatOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements FloatIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final FloatConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public float nextFloat() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements FloatSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = FloatSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : FloatSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final FloatConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public FloatCollection values() { + if (values == null) values = new AbstractFloatCollection() { + + @Override + public FloatIterator iterator() { + return new ValueIterator(); + } + + @Override + public FloatSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final FloatConsumer consumer) { + final K[] key = Object2FloatOpenCachedHashMap.this.key; + final float[] value = Object2FloatOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(float v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2FloatOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final float[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final float[] newValue = new float[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2FloatOpenCachedHashMap clone() { + Object2FloatOpenCachedHashMap c = (Object2FloatOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final float[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= HashCommon.float2int(value[i]); + h += t; + i++; + } + if (containsNullKey) h += HashCommon.float2int(value[n]); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java new file mode 100644 index 0000000..9ecc21e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java @@ -0,0 +1,1192 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.floats.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToDoubleFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2FloatOpenCustomCachedHashMap extends Object2FloatOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2FloatOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2FloatOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2FloatOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2FloatOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2FloatOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2FloatOpenCustomCachedHashMap(final Object2FloatMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2FloatOpenCustomCachedHashMap(final Object2FloatMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private float removeEntry(int pos) { + final float oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final float[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0f; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private float removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final float oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final float v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public float put(final K k, final float v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final float oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private float addToValue(final int pos, final float incr) { + final float oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public float addTo(final K k, final float incr) { + int pos, h = 0; + if (strategy.equals(k, null)) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public float removeFloat(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public float getFloat(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public float getOrDefault(final Object k, final float defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public float putIfAbsent(final K k, final float v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final float v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final float oldValue, final float v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public float replace(final K k, final float v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final float oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public float computeIfAbsent(final K k, final ToDoubleFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final float newValue = SafeMath.safeDoubleToFloat(mappingFunction.applyAsDouble(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public float computeIfAbsent(final K k, final Object2FloatFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final float newValue = mappingFunction.getFloat(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public float computeFloatIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Float newValue = remappingFunction.apply((k), Float.valueOf(value[pos])); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public float computeFloat(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Float newValue = remappingFunction.apply((k), pos >= 0 ? Float.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + float newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public float mergeFloat(final K k, final float v, FloatBinaryOperator remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final float newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public float merge(final K k, final float v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Float newValue = remappingFunction.apply(Float.valueOf(value[pos]), Float.valueOf(v)); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectFloatPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public float getFloatValue() { + return value[index]; + } + + @Override + public float rightFloat() { + return value[index]; + } + + @Override + public float setValue(final float v) { + final float oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectFloatPair right(final float v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Float getValue() { + return value[index]; + } + + @Deprecated + @Override + public Float setValue(final Float v) { + return Float.valueOf(setValue((v).floatValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && (Float.floatToRawIntBits(value[index]) == Float.floatToRawIntBits((e.getValue()).floatValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ HashCommon.float2int(value[index]); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2FloatOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + final int[] hash = Object2FloatOpenCustomCachedHashMap.this.hash; + final int mask = Object2FloatOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + final int[] hash = Object2FloatOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + final float[] value = Object2FloatOpenCustomCachedHashMap.this.value; + final int[] hash = Object2FloatOpenCustomCachedHashMap.this.hash; + final int mask = Object2FloatOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2FloatOpenCustomCachedHashMap.this.removeFloat(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2FloatOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Float)) return false; + final K k = ((K) e.getKey()); + final float v = ((Float) (e.getValue())).floatValue(); + if (strategy.equals(k, null)) return Object2FloatOpenCustomCachedHashMap.this.containsNullKey && (Float.floatToRawIntBits(value[n]) == Float.floatToRawIntBits(v)); + K curr; + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + final int mask = Object2FloatOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return (Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return (Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Float)) return false; + final K k = ((K) e.getKey()); + final float v = ((Float) (e.getValue())).floatValue(); + if (strategy.equals(k, null)) { + if (containsNullKey && (Float.floatToRawIntBits(value[n]) == Float.floatToRawIntBits(v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + final int mask = Object2FloatOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if ((Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if ((Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2FloatOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2FloatEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2FloatOpenCustomCachedHashMap.this.removeFloat(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2FloatOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements FloatIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final FloatConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public float nextFloat() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements FloatSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = FloatSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : FloatSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final FloatConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public FloatCollection values() { + if (values == null) values = new AbstractFloatCollection() { + + @Override + public FloatIterator iterator() { + return new ValueIterator(); + } + + @Override + public FloatSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final FloatConsumer consumer) { + final K[] key = Object2FloatOpenCustomCachedHashMap.this.key; + final float[] value = Object2FloatOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(float v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2FloatOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final float[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final float[] newValue = new float[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2FloatOpenCustomCachedHashMap clone() { + Object2FloatOpenCustomCachedHashMap c = (Object2FloatOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final float[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= HashCommon.float2int(value[i]); + h += t; + i++; + } + if (containsNullKey) h += HashCommon.float2int(value[n]); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2IntOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2IntOpenCachedHashMap.java new file mode 100644 index 0000000..1a014eb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2IntOpenCachedHashMap.java @@ -0,0 +1,1179 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.ints.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.IntBinaryOperator; +import java.util.function.IntConsumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2IntOpenCachedHashMap extends Object2IntOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2IntOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2IntOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2IntOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2IntOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2IntOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2IntOpenCachedHashMap(final Object2IntMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2IntOpenCachedHashMap(final Object2IntMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private int removeEntry(int pos) { + final int oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final int[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final int oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final int v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public int put(final K k, final int v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final int oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private int addToValue(final int pos, final int incr) { + final int oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public int addTo(final K k, final int incr) { + int pos, h = 0; + if (k == null) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (curr == k || curr.equals(k))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public int removeInt(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public int getInt(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public int getOrDefault(final Object k, final int defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public int putIfAbsent(final K k, final int v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final int v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final int oldValue, final int v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public int replace(final K k, final int v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final int oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public int computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final int newValue = mappingFunction.applyAsInt(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public int computeIfAbsent(final K k, final Object2IntFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final int newValue = mappingFunction.applyAsInt(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public int computeIntIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Integer newValue = remappingFunction.apply((k), value[pos]); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public int computeInt(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Integer newValue = remappingFunction.apply((k), pos >= 0 ? value[pos] : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + int newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public int mergeInt(final K k, final int v, IntBinaryOperator remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final int newValue = remappingFunction.applyAsInt(value[pos], v); + return value[pos] = newValue; + } + + @Override + public int merge(final K k, final int v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Integer newValue = remappingFunction.apply(value[pos], v); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectIntPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public int getIntValue() { + return value[index]; + } + + @Override + public int rightInt() { + return value[index]; + } + + @Override + public int setValue(final int v) { + final int oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectIntPair right(final int v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Integer getValue() { + return value[index]; + } + + @Deprecated + @Override + public Integer setValue(final Integer v) { + return setValue((v).intValue()); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && ((value[index]) == (e.getValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2IntOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2IntOpenCachedHashMap.this.key; + final int[] hash = Object2IntOpenCachedHashMap.this.hash; + final int mask = Object2IntOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2IntOpenCachedHashMap.this.key; + final int[] hash = Object2IntOpenCachedHashMap.this.hash; + final int mask = Object2IntOpenCachedHashMap.this.mask; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2IntOpenCachedHashMap.this.key; + final int[] value = Object2IntOpenCachedHashMap.this.value; + final int[] hash = Object2IntOpenCachedHashMap.this.hash; + final int mask = Object2IntOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2IntOpenCachedHashMap.this.removeInt(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2IntOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2IntOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2IntOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2IntOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Integer)) return false; + final K k = ((K) e.getKey()); + final int v = (Integer) (e.getValue()); + if (((k) == null)) return Object2IntOpenCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2IntOpenCachedHashMap.this.key; + final int mask = Object2IntOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Integer)) return false; + final K k = ((K) e.getKey()); + final int v = (Integer) (e.getValue()); + if (((k) == null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2IntOpenCachedHashMap.this.key; + final int mask = Object2IntOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2IntOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2IntOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2IntOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2IntEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2IntOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2IntOpenCachedHashMap.this.removeInt(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2IntOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements IntIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final IntConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public int nextInt() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements IntSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = IntSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : IntSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final IntConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public IntCollection values() { + if (values == null) values = new AbstractIntCollection() { + + @Override + public IntIterator iterator() { + return new ValueIterator(); + } + + @Override + public IntSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final IntConsumer consumer) { + final K[] key = Object2IntOpenCachedHashMap.this.key; + final int[] value = Object2IntOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(int v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2IntOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final int[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final int[] newValue = new int[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2IntOpenCachedHashMap clone() { + Object2IntOpenCachedHashMap c = (Object2IntOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final int[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2IntOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2IntOpenCustomCachedHashMap.java new file mode 100644 index 0000000..3779cdf --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2IntOpenCustomCachedHashMap.java @@ -0,0 +1,1193 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.ints.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.IntBinaryOperator; +import java.util.function.IntConsumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2IntOpenCustomCachedHashMap extends Object2IntOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2IntOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2IntOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2IntOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2IntOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2IntOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2IntOpenCustomCachedHashMap(final Object2IntMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2IntOpenCustomCachedHashMap(final Object2IntMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private int removeEntry(int pos) { + final int oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final int[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final int oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final int v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public int put(final K k, final int v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final int oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private int addToValue(final int pos, final int incr) { + final int oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public int addTo(final K k, final int incr) { + int pos, h = 0; + if (strategy.equals(k, null)) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public int removeInt(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public int getInt(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public int getOrDefault(final Object k, final int defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public int putIfAbsent(final K k, final int v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final int v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final int oldValue, final int v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public int replace(final K k, final int v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final int oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public int computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final int newValue = mappingFunction.applyAsInt(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public int computeIfAbsent(final K k, final Object2IntFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final int newValue = mappingFunction.applyAsInt(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public int computeIntIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Integer newValue = remappingFunction.apply((k), value[pos]); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public int computeInt(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Integer newValue = remappingFunction.apply((k), pos >= 0 ? value[pos] : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + int newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public int mergeInt(final K k, final int v, IntBinaryOperator remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final int newValue = remappingFunction.applyAsInt(value[pos], v); + return value[pos] = newValue; + } + + @Override + public int merge(final K k, final int v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Integer newValue = remappingFunction.apply(value[pos], v); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectIntPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public int getIntValue() { + return value[index]; + } + + @Override + public int rightInt() { + return value[index]; + } + + @Override + public int setValue(final int v) { + final int oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectIntPair right(final int v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Integer getValue() { + return value[index]; + } + + @Deprecated + @Override + public Integer setValue(final Integer v) { + return setValue((v).intValue()); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && ((value[index]) == (e.getValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2IntOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + final int[] hash = Object2IntOpenCustomCachedHashMap.this.hash; + final int mask = Object2IntOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + final int[] hash = Object2IntOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + final int[] value = Object2IntOpenCustomCachedHashMap.this.value; + final int[] hash = Object2IntOpenCustomCachedHashMap.this.hash; + final int mask = Object2IntOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2IntOpenCustomCachedHashMap.this.removeInt(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2IntOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Integer)) return false; + final K k = ((K) e.getKey()); + final int v = (Integer) (e.getValue()); + if (strategy.equals(k, null)) return Object2IntOpenCustomCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + final int mask = Object2IntOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Integer)) return false; + final K k = ((K) e.getKey()); + final int v = (Integer) (e.getValue()); + if (strategy.equals(k, null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + final int mask = Object2IntOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2IntOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2IntEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2IntOpenCustomCachedHashMap.this.removeInt(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2IntOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements IntIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final IntConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public int nextInt() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements IntSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = IntSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : IntSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final IntConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public IntCollection values() { + if (values == null) values = new AbstractIntCollection() { + + @Override + public IntIterator iterator() { + return new ValueIterator(); + } + + @Override + public IntSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final IntConsumer consumer) { + final K[] key = Object2IntOpenCustomCachedHashMap.this.key; + final int[] value = Object2IntOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(int v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2IntOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final int[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final int[] newValue = new int[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2IntOpenCustomCachedHashMap clone() { + Object2IntOpenCustomCachedHashMap c = (Object2IntOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final int[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2LongOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2LongOpenCachedHashMap.java new file mode 100644 index 0000000..48f6e96 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2LongOpenCachedHashMap.java @@ -0,0 +1,1183 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.longs.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.LongBinaryOperator; +import java.util.function.LongConsumer; +import java.util.function.ToLongFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2LongOpenCachedHashMap extends Object2LongOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2LongOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2LongOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2LongOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2LongOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2LongOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2LongOpenCachedHashMap(final Object2LongMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2LongOpenCachedHashMap(final Object2LongMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private long removeEntry(int pos) { + final long oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final long[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private long removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final long oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final long v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public long put(final K k, final long v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final long oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private long addToValue(final int pos, final long incr) { + final long oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public long addTo(final K k, final long incr) { + int pos, h = 0; + if (k == null) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (curr == k || curr.equals(k))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + /** 只清零存储值,保留键、容量及默认返回值。 */ + public void resetValues() { + Arrays.fill(value, 0); + } + + @Override + public long removeLong(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public long getLong(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public long getOrDefault(final Object k, final long defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public long putIfAbsent(final K k, final long v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final long v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final long oldValue, final long v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public long replace(final K k, final long v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final long oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public long computeIfAbsent(final K k, final ToLongFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final long newValue = mappingFunction.applyAsLong(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public long computeIfAbsent(final K k, final Object2LongFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final long newValue = mappingFunction.applyAsLong(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public long computeLongIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Long newValue = remappingFunction.apply((k), value[pos]); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public long computeLong(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Long newValue = remappingFunction.apply((k), pos >= 0 ? value[pos] : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + long newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public long mergeLong(final K k, final long v, LongBinaryOperator remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final long newValue = remappingFunction.applyAsLong(value[pos], v); + return value[pos] = newValue; + } + + @Override + public long merge(final K k, final long v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Long newValue = remappingFunction.apply(value[pos], v); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectLongPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public long getLongValue() { + return value[index]; + } + + @Override + public long rightLong() { + return value[index]; + } + + @Override + public long setValue(final long v) { + final long oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectLongPair right(final long v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Long getValue() { + return value[index]; + } + + @Deprecated + @Override + public Long setValue(final Long v) { + return setValue((v).longValue()); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && ((value[index]) == (e.getValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ HashCommon.long2int(value[index]); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2LongOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2LongOpenCachedHashMap.this.key; + final int[] hash = Object2LongOpenCachedHashMap.this.hash; + final int mask = Object2LongOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2LongOpenCachedHashMap.this.key; + final int[] hash = Object2LongOpenCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2LongOpenCachedHashMap.this.key; + final long[] value = Object2LongOpenCachedHashMap.this.value; + final int[] hash = Object2LongOpenCachedHashMap.this.hash; + final int mask = Object2LongOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2LongOpenCachedHashMap.this.removeLong(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2LongOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2LongOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2LongOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public long skip(long n) { + if (n == 0) return 0; + long skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2LongOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Long)) return false; + final K k = ((K) e.getKey()); + final long v = (Long) (e.getValue()); + if (((k) == null)) return Object2LongOpenCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2LongOpenCachedHashMap.this.key; + final int mask = Object2LongOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Long)) return false; + final K k = ((K) e.getKey()); + final long v = (Long) (e.getValue()); + if (((k) == null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2LongOpenCachedHashMap.this.key; + final int mask = Object2LongOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2LongOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2LongOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2LongOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2LongEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2LongOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2LongOpenCachedHashMap.this.removeLong(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2LongOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements LongIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final LongConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public long nextLong() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements LongSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = LongSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : LongSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final LongConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public LongCollection values() { + if (values == null) values = new AbstractLongCollection() { + + @Override + public LongIterator iterator() { + return new ValueIterator(); + } + + @Override + public LongSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final LongConsumer consumer) { + final K[] key = Object2LongOpenCachedHashMap.this.key; + final long[] value = Object2LongOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(long v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2LongOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final long[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final long[] newValue = new long[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2LongOpenCachedHashMap clone() { + Object2LongOpenCachedHashMap c = (Object2LongOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final long[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= HashCommon.long2int(value[i]); + h += t; + i++; + } + if (containsNullKey) h += HashCommon.long2int(value[n]); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2LongOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2LongOpenCustomCachedHashMap.java new file mode 100644 index 0000000..aceb15e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2LongOpenCustomCachedHashMap.java @@ -0,0 +1,1193 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.longs.*; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.LongBinaryOperator; +import java.util.function.LongConsumer; +import java.util.function.ToLongFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2LongOpenCustomCachedHashMap extends Object2LongOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2LongOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2LongOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2LongOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2LongOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2LongOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2LongOpenCustomCachedHashMap(final Object2LongMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2LongOpenCustomCachedHashMap(final Object2LongMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private long removeEntry(int pos) { + final long oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final long[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private long removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final long oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final long v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public long put(final K k, final long v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final long oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private long addToValue(final int pos, final long incr) { + final long oldValue = value[pos]; + value[pos] = oldValue + incr; + return oldValue; + } + + @Override + public long addTo(final K k, final long incr) { + int pos, h = 0; + if (strategy.equals(k, null)) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = defRetValue + incr; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public long removeLong(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public long getLong(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public long getOrDefault(final Object k, final long defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public long putIfAbsent(final K k, final long v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final long v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final long oldValue, final long v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public long replace(final K k, final long v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final long oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public long computeIfAbsent(final K k, final ToLongFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final long newValue = mappingFunction.applyAsLong(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public long computeIfAbsent(final K k, final Object2LongFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final long newValue = mappingFunction.applyAsLong(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public long computeLongIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Long newValue = remappingFunction.apply((k), value[pos]); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public long computeLong(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Long newValue = remappingFunction.apply((k), pos >= 0 ? value[pos] : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + long newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public long mergeLong(final K k, final long v, LongBinaryOperator remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final long newValue = remappingFunction.applyAsLong(value[pos], v); + return value[pos] = newValue; + } + + @Override + public long merge(final K k, final long v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Long newValue = remappingFunction.apply(value[pos], v); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectLongPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public long getLongValue() { + return value[index]; + } + + @Override + public long rightLong() { + return value[index]; + } + + @Override + public long setValue(final long v) { + final long oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectLongPair right(final long v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Long getValue() { + return value[index]; + } + + @Deprecated + @Override + public Long setValue(final Long v) { + return setValue((v).longValue()); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && ((value[index]) == (e.getValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ HashCommon.long2int(value[index]); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2LongOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + final int[] hash = Object2LongOpenCustomCachedHashMap.this.hash; + final int mask = Object2LongOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + final int[] hash = Object2LongOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + final long[] value = Object2LongOpenCustomCachedHashMap.this.value; + final int[] hash = Object2LongOpenCustomCachedHashMap.this.hash; + final int mask = Object2LongOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2LongOpenCustomCachedHashMap.this.removeLong(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2LongOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public long skip(long n) { + if (n == 0) return 0; + long skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Long)) return false; + final K k = ((K) e.getKey()); + final long v = (Long) (e.getValue()); + if (strategy.equals(k, null)) return Object2LongOpenCustomCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + final int mask = Object2LongOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Long)) return false; + final K k = ((K) e.getKey()); + final long v = (Long) (e.getValue()); + if (strategy.equals(k, null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + final int mask = Object2LongOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2LongOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2LongEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2LongOpenCustomCachedHashMap.this.removeLong(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2LongOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements LongIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final LongConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public long nextLong() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements LongSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = LongSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : LongSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final LongConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public LongCollection values() { + if (values == null) values = new AbstractLongCollection() { + + @Override + public LongIterator iterator() { + return new ValueIterator(); + } + + @Override + public LongSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final LongConsumer consumer) { + final K[] key = Object2LongOpenCustomCachedHashMap.this.key; + final long[] value = Object2LongOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(long v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2LongOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final long[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final long[] newValue = new long[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2LongOpenCustomCachedHashMap clone() { + Object2LongOpenCustomCachedHashMap c = (Object2LongOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final long[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= HashCommon.long2int(value[i]); + h += t; + i++; + } + if (containsNullKey) h += HashCommon.long2int(value[n]); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ObjectOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ObjectOpenCachedHashMap.java new file mode 100644 index 0000000..39033fe --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ObjectOpenCachedHashMap.java @@ -0,0 +1,1128 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.*; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2ObjectOpenCachedHashMap extends Object2ObjectOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2ObjectOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2ObjectOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2ObjectOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2ObjectOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2ObjectOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2ObjectOpenCachedHashMap(final Object2ObjectMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2ObjectOpenCachedHashMap(final Object2ObjectMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private V removeEntry(int pos) { + final V oldValue = value[pos]; + value[pos] = null; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final V[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = null; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private V removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final V oldValue = value[n]; + value[n] = null; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final V v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public V put(final K k, final V v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final V oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public V remove(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public V get(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public V getOrDefault(final Object k, final V defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public V putIfAbsent(final K k, final V v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final Object v) { + if (k == null) { + if (containsNullKey && Objects.equals(v, value[n])) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && Objects.equals(v, value[pos])) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && Objects.equals(v, value[pos])) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final V oldValue, final V v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || !Objects.equals(oldValue, value[pos])) return false; + value[pos] = v; + return true; + } + + @Override + public V replace(final K k, final V v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final V oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public V computeIfAbsent(K k, Function mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final V newValue = mappingFunction.apply(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public V computeIfAbsent(final K k, final Object2ObjectFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final V newValue = mappingFunction.get(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public V computeIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + if (value[pos] == null) return defRetValue; + final V newValue = remappingFunction.apply((k), (value[pos])); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = (newValue); + } + + @Override + public V compute(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final V newValue = remappingFunction.apply((k), pos >= 0 ? (value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + if (pos < 0) { + insert(-pos - 1, k, newValue, h); + return newValue; + } + return value[pos] = newValue; + } + + @Override + public V merge(final K k, final V v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || value[pos] == null) { + if (pos < 0) insert(-pos - 1, k, v, h); + else value[pos] = v; + return v; + } + final V newValue = remappingFunction.apply((value[pos]), (v)); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(value, null); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, Pair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public V getValue() { + return value[index]; + } + + @Override + public V right() { + return value[index]; + } + + @Override + public V setValue(final V v) { + final V oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public Pair right(final V v) { + value[index] = v; + return this; + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && Objects.equals(value[index], (e.getValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ (value[index] == null ? 0 : value[index].hashCode()); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2ObjectOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + final int[] hash = Object2ObjectOpenCachedHashMap.this.hash; + final int mask = Object2ObjectOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + final int[] hash = Object2ObjectOpenCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + final V[] value = Object2ObjectOpenCachedHashMap.this.value; + final int[] hash = Object2ObjectOpenCachedHashMap.this.hash; + final int mask = Object2ObjectOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = (null); + value[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + value[n] = null; + } else if (pos >= 0) shiftKeys(last); + else { + Object2ObjectOpenCachedHashMap.this.remove(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2ObjectOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) (containsNullKey ? size - 1 : size) / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public long skip(long n) { + if (n == 0) return 0; + long skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + public boolean containsAll(Collection c) { + if (c instanceof Object2ObjectMap.FastEntrySet set) { + for (ObjectIterator it = set.fastIterator(); it.hasNext();) if (!contains(it.next())) return false; + } else { + for (Object e : c) if (!contains(e)) return false; + } + return true; + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + final K k = ((K) e.getKey()); + final V v = ((V) e.getValue()); + if (k == null) return Object2ObjectOpenCachedHashMap.this.containsNullKey && Objects.equals(value[n], v); + K curr; + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + final int[] hash = Object2ObjectOpenCachedHashMap.this.hash; + final int mask = Object2ObjectOpenCachedHashMap.this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (h == hash[pos] && k.equals(curr)) return Objects.equals(value[pos], v); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (h == hash[pos] && k.equals(curr)) return Objects.equals(value[pos], v); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + final K k = ((K) e.getKey()); + final V v = ((V) e.getValue()); + if (k == null) { + if (containsNullKey && Objects.equals(value[n], v)) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + final int[] hash = Object2ObjectOpenCachedHashMap.this.hash; + final int mask = Object2ObjectOpenCachedHashMap.this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (h == hash[pos] && k.equals(curr)) { + if (Objects.equals(value[pos], v)) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (h == hash[pos] && k.equals(curr)) { + if (Objects.equals(value[pos], v)) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2ObjectOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2ObjectEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2ObjectOpenCachedHashMap.this.remove(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2ObjectOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator> implements ObjectIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(value[index]); + } + + @Override + public V next() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator, ValueSpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public ObjectCollection values() { + if (values == null) values = new AbstractObjectCollection<>() { + + @Override + public ObjectIterator iterator() { + return new ValueIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new ValueSpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ObjectOpenCachedHashMap.this.key; + final V[] value = Object2ObjectOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2ObjectOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final V[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final V[] newValue = (V[]) new Object[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = containsNullKey ? size - 1 : size; j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2ObjectOpenCachedHashMap clone() { + Object2ObjectOpenCachedHashMap c = (Object2ObjectOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final V[] value = this.value; + final int[] hash = this.hash; + for (int j = containsNullKey ? size - 1 : size, i = 0, t = 0; j-- != 0;) { + while ((key[i]) == null) i++; + if (this != key[i]) t = hash[i]; + if (this != value[i]) t ^= (value[i] == null ? 0 : value[i].hashCode()); + h += t; + i++; + } + if (containsNullKey) h += (value[n] == null ? 0 : value[n].hashCode()); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ObjectOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ObjectOpenCustomCachedHashMap.java new file mode 100644 index 0000000..e39c55b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ObjectOpenCustomCachedHashMap.java @@ -0,0 +1,1136 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2ObjectOpenCustomCachedHashMap extends Object2ObjectOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ObjectOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2ObjectOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2ObjectOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ObjectOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2ObjectOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ObjectOpenCustomCachedHashMap(final Object2ObjectMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2ObjectOpenCustomCachedHashMap(final Object2ObjectMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private V removeEntry(int pos) { + final V oldValue = value[pos]; + value[pos] = null; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final V[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = (null); + value[last] = null; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private V removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final V oldValue = value[n]; + value[n] = null; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final V v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public V put(final K k, final V v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final V oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + @SuppressWarnings("unchecked") + public V remove(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public V get(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public V getOrDefault(final Object k, final V defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public V putIfAbsent(final K k, final V v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final Object v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && Objects.equals(v, value[n])) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && Objects.equals(v, value[pos])) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && Objects.equals(v, value[pos])) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final V oldValue, final V v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || !Objects.equals(oldValue, value[pos])) return false; + value[pos] = v; + return true; + } + + @Override + public V replace(final K k, final V v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final V oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public V computeIfAbsent(K k, Function mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final V newValue = mappingFunction.apply(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public V computeIfAbsent(final K k, final Object2ObjectFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final V newValue = mappingFunction.get(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public V computeIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + if (value[pos] == null) return defRetValue; + final V newValue = remappingFunction.apply((k), (value[pos])); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = (newValue); + } + + @Override + public V compute(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final V newValue = remappingFunction.apply((k), pos >= 0 ? (value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + if (pos < 0) { + insert(-pos - 1, k, newValue, h); + return newValue; + } + return value[pos] = newValue; + } + + @Override + public V merge(final K k, final V v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || value[pos] == null) { + if (pos < 0) insert(-pos - 1, k, v, h); + else value[pos] = v; + return v; + } + final V newValue = remappingFunction.apply((value[pos]), (v)); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(value, null); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, Pair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public V getValue() { + return value[index]; + } + + @Override + public V right() { + return value[index]; + } + + @Override + public V setValue(final V v) { + final V oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public Pair right(final V v) { + value[index] = v; + return this; + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && Objects.equals(value[index], (e.getValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ (value[index] == null ? 0 : value[index].hashCode()); + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2ObjectOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + final int[] hash = Object2ObjectOpenCustomCachedHashMap.this.hash; + final int mask = Object2ObjectOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + final int[] hash = Object2ObjectOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + final V[] value = Object2ObjectOpenCustomCachedHashMap.this.value; + final int[] hash = Object2ObjectOpenCustomCachedHashMap.this.hash; + final int mask = Object2ObjectOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = (null); + value[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + value[n] = null; + } else if (pos >= 0) shiftKeys(last); + else { + Object2ObjectOpenCustomCachedHashMap.this.remove(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2ObjectOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public long skip(long n) { + if (n == 0) return 0; + long skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + final K k = ((K) e.getKey()); + final V v = ((V) e.getValue()); + if (strategy.equals(k, null)) return Object2ObjectOpenCustomCachedHashMap.this.containsNullKey && Objects.equals(value[n], v); + K curr; + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + final int mask = Object2ObjectOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if ((strategy.equals(curr, k))) return Objects.equals(value[pos], v); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if ((strategy.equals(curr, k))) return Objects.equals(value[pos], v); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + final K k = ((K) e.getKey()); + final V v = ((V) e.getValue()); + if (strategy.equals(k, null)) { + if (containsNullKey && Objects.equals(value[n], v)) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + final int mask = Object2ObjectOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (Objects.equals(value[pos], v)) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (Objects.equals(value[pos], v)) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2ObjectOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2ObjectEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2ObjectOpenCustomCachedHashMap.this.remove(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2ObjectOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator> implements ObjectIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(value[index]); + } + + @Override + public V next() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator, ValueSpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public ObjectCollection values() { + if (values == null) values = new AbstractObjectCollection<>() { + + @Override + public ObjectIterator iterator() { + return new ValueIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new ValueSpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ObjectOpenCustomCachedHashMap.this.key; + final V[] value = Object2ObjectOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2ObjectOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final V[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final V[] newValue = (V[]) new Object[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2ObjectOpenCustomCachedHashMap clone() { + Object2ObjectOpenCustomCachedHashMap c = (Object2ObjectOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final V[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while ((key[i]) == null) i++; + if (this != key[i]) t = hash[i]; + if (this != value[i]) t ^= (value[i] == null ? 0 : value[i].hashCode()); + h += t; + i++; + } + if (containsNullKey) h += (value[n] == null ? 0 : value[n].hashCode()); + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ShortOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ShortOpenCachedHashMap.java new file mode 100644 index 0000000..e342a81 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ShortOpenCachedHashMap.java @@ -0,0 +1,1178 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.objects.*; +import it.unimi.dsi.fastutil.shorts.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2ShortOpenCachedHashMap extends Object2ShortOpenHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + */ + public Object2ShortOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + */ + public Object2ShortOpenCachedHashMap(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 创建空映射。 使用默认负载因子。 */ + public Object2ShortOpenCachedHashMap() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2ShortOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2ShortOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + */ + public Object2ShortOpenCachedHashMap(final Object2ShortMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + */ + public Object2ShortOpenCachedHashMap(final Object2ShortMap m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private short removeEntry(int pos) { + final short oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final short[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private short removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final short oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || k.equals(curr))) return pos; + } + } + + private void insert(final int pos, final K k, final short v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public short put(final K k, final short v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final short oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private short addToValue(final int pos, final short incr) { + final short oldValue = value[pos]; + value[pos] = (short) (oldValue + incr); + return oldValue; + } + + @Override + public short addTo(final K k, final short incr) { + int pos, h = 0; + if (k == null) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (curr == k || curr.equals(k))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = (short) (defRetValue + incr); + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public short removeShort(final Object k) { + if (k == null) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public short getShort(final Object k) { + if (k == null) return containsNullKey ? value[n] : defRetValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (k == null) return containsNullKey; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public short getOrDefault(final Object k, final short defaultValue) { + if (k == null) return containsNullKey ? value[n] : defaultValue; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (k == curr || k.equals(curr))) return value[pos]; + } + } + + @Override + public short putIfAbsent(final K k, final short v) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final short v) { + if (k == null) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = k.hashCode(); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final short oldValue, final short v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public short replace(final K k, final short v) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final short oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public short computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final short newValue = SafeMath.safeIntToShort(mappingFunction.applyAsInt(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public short computeIfAbsent(final K k, final Object2ShortFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final short newValue = mappingFunction.getShort(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public short computeShortIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Short newValue = remappingFunction.apply((k), Short.valueOf(value[pos])); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public short computeShort(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + final Short newValue = remappingFunction.apply((k), pos >= 0 ? Short.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + short newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public short mergeShort(final K k, final short v, ShortBinaryOperator remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final short newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public short merge(final K k, final short v, final BiFunction remappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = k.hashCode(); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Short newValue = remappingFunction.apply(Short.valueOf(value[pos]), Short.valueOf(v)); + if (newValue == null) { + if (k == null) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectShortPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public short getShortValue() { + return value[index]; + } + + @Override + public short rightShort() { + return value[index]; + } + + @Override + public short setValue(final short v) { + final short oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectShortPair right(final short v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Short getValue() { + return value[index]; + } + + @Deprecated + @Override + public Short setValue(final Short v) { + return Short.valueOf(setValue((v).shortValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return Objects.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).shortValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2ShortOpenCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2ShortOpenCachedHashMap.this.key; + final int[] hash = Object2ShortOpenCachedHashMap.this.hash; + final int mask = Object2ShortOpenCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2ShortOpenCachedHashMap.this.key; + final int[] hash = Object2ShortOpenCachedHashMap.this.hash; + final int mask = Object2ShortOpenCachedHashMap.this.mask; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = k.hashCode(); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && k.equals(key[p]))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2ShortOpenCachedHashMap.this.key; + final short[] value = Object2ShortOpenCachedHashMap.this.value; + final int[] hash = Object2ShortOpenCachedHashMap.this.hash; + final int mask = Object2ShortOpenCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2ShortOpenCachedHashMap.this.removeShort(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2ShortOpenCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2ShortOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2ShortOpenCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2ShortOpenCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Short)) return false; + final K k = ((K) e.getKey()); + final short v = ((Short) (e.getValue())).shortValue(); + if (((k) == null)) return Object2ShortOpenCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2ShortOpenCachedHashMap.this.key; + final int mask = Object2ShortOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((k).equals(curr))) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Short)) return false; + final K k = ((K) e.getKey()); + final short v = ((Short) (e.getValue())).shortValue(); + if (((k) == null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2ShortOpenCachedHashMap.this.key; + final int mask = Object2ShortOpenCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix((k).hashCode())) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (((curr).equals(k))) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2ShortOpenCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2ShortOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2ShortOpenCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2ShortEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ShortOpenCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2ShortOpenCachedHashMap.this.removeShort(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2ShortOpenCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements ShortIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final ShortConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public short nextShort() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements ShortSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ShortSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ShortSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final ShortConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public ShortCollection values() { + if (values == null) values = new AbstractShortCollection() { + + @Override + public ShortIterator iterator() { + return new ValueIterator(); + } + + @Override + public ShortSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final ShortConsumer consumer) { + final K[] key = Object2ShortOpenCachedHashMap.this.key; + final short[] value = Object2ShortOpenCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(short v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2ShortOpenCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final short[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final short[] newValue = new short[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2ShortOpenCachedHashMap clone() { + Object2ShortOpenCachedHashMap c = (Object2ShortOpenCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final short[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java new file mode 100644 index 0000000..69816f3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java @@ -0,0 +1,1192 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.SafeMath; +import it.unimi.dsi.fastutil.objects.*; +import it.unimi.dsi.fastutil.shorts.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Map; +import java.util.Spliterator; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.ToIntFunction; + +import static it.unimi.dsi.fastutil.HashCommon.arraySize; +import static it.unimi.dsi.fastutil.HashCommon.maxFill; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class Object2ShortOpenCustomCachedHashMap extends Object2ShortOpenCustomHashMap { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** + * 创建空映射。 + * + * @param expected 预计存放的键数 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ShortOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param expected 预计存放的键数 + * @param strategy 键的散列与相等性策略 + */ + public Object2ShortOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 创建空映射。 使用默认负载因子。 + * + * @param strategy 键的散列与相等性策略 + */ + public Object2ShortOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ShortOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2ShortOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * 从给定映射复制条目。 + * + * @param m 复制条目的来源映射 + * @param f 触发扩容的负载因子 + * @param strategy 键的散列与相等性策略 + */ + public Object2ShortOpenCustomCachedHashMap(final Object2ShortMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + /** + * 从给定映射复制条目。 使用默认负载因子。 + * + * @param m 复制条目的来源映射 + * @param strategy 键的散列与相等性策略 + */ + public Object2ShortOpenCustomCachedHashMap(final Object2ShortMap m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNullKey ? size - 1 : size; + } + + private short removeEntry(int pos) { + final short oldValue = value[pos]; + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final short[] value = this.value; + final int[] hash = this.hash; + final int mask = this.mask; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + value[last] = 0; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private short removeNullEntry() { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + final short oldValue = value[n]; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return oldValue; + } + + private int find(final K k, final int h) { + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return -(pos + 1); + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return pos; + } + } + + private void insert(final int pos, final K k, final short v, final int h) { + if (pos == n) containsNullKey = true; + key[pos] = k; + value[pos] = v; + hash[pos] = h; + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + } + + @Override + public short put(final K k, final short v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return defRetValue; + } + final short oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + private short addToValue(final int pos, final short incr) { + final short oldValue = value[pos]; + value[pos] = (short) (oldValue + incr); + return oldValue; + } + + @Override + public short addTo(final K k, final short incr) { + int pos, h = 0; + if (strategy.equals(k, null)) { + if (containsNullKey) return addToValue(n, incr); + pos = n; + containsNullKey = true; + } else { + h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return addToValue(pos, incr); + while ((curr = key[pos = (pos + 1) & mask]) != null); + } + } + key[pos] = k; + hash[pos] = h; + value[pos] = (short) (defRetValue + incr); + if (size++ >= maxFill) rehash(arraySize(size + 1, f)); + return defRetValue; + } + + @Override + public short removeShort(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNullKey) return removeNullEntry(); + return defRetValue; + } + K curr; + K fk = (K) k; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return removeEntry(pos); + } + } + + @Override + public short getShort(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defRetValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public boolean containsKey(final Object k) { + if (strategy.equals((K) k, null)) return containsNullKey; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return true; + } + } + + @Override + public short getOrDefault(final Object k, final short defaultValue) { + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return defaultValue; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr))) return value[pos]; + } + } + + @Override + public short putIfAbsent(final K k, final short v) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + insert(-pos - 1, k, v, h); + return defRetValue; + } + + @Override + public boolean remove(final Object k, final short v) { + if (strategy.equals((K) k, null)) { + if (containsNullKey && v == value[n]) { + removeNullEntry(); + return true; + } + return false; + } + K fk = (K) k; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = this.mask; + final int h = strategy.hashCode(fk); + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (fk == curr || strategy.equals(fk, curr)) && v == value[pos]) { + removeEntry(pos); + return true; + } + } + } + + @Override + public boolean replace(final K k, final short oldValue, final short v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0 || oldValue != value[pos]) return false; + value[pos] = v; + return true; + } + + @Override + public short replace(final K k, final short v) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final short oldValue = value[pos]; + value[pos] = v; + return oldValue; + } + + @Override + public short computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final short newValue = SafeMath.safeIntToShort(mappingFunction.applyAsInt(k)); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public short computeIfAbsent(final K k, final Object2ShortFunction mappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + if (!mappingFunction.containsKey(k)) return defRetValue; + final short newValue = mappingFunction.getShort(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } + + @Override + public short computeShortIfPresent(final K k, final BiFunction remappingFunction) { + int pos; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + int h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) return defRetValue; + final Short newValue = remappingFunction.apply((k), Short.valueOf(value[pos])); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public short computeShort(final K k, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + final Short newValue = remappingFunction.apply((k), pos >= 0 ? Short.valueOf(value[pos]) : null); + if (newValue == null) { + if (pos >= 0) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + } + return defRetValue; + } + short newVal = newValue; + if (pos < 0) { + insert(-pos - 1, k, newVal, h); + return newVal; + } + return value[pos] = newVal; + } + + @Override + public short mergeShort(final K k, final short v, ShortBinaryOperator remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final short newValue = remappingFunction.apply(value[pos], v); + return value[pos] = newValue; + } + + @Override + public short merge(final K k, final short v, final BiFunction remappingFunction) { + int pos, h = 0; + if (strategy.equals(k, null)) { + pos = containsNullKey ? n : -(n + 1); + } else { + h = strategy.hashCode(k); + pos = find(k, h); + } + if (pos < 0) { + insert(-pos - 1, k, v, h); + return v; + } + final Short newValue = remappingFunction.apply(Short.valueOf(value[pos]), Short.valueOf(v)); + if (newValue == null) { + if (strategy.equals(k, null)) removeNullEntry(); + else removeEntry(pos); + return defRetValue; + } + return value[pos] = newValue; + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNullKey = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + final class MapEntry implements Entry, ObjectShortPair { + + int index; + + MapEntry(final int index) { + this.index = index; + } + + MapEntry() {} + + @Override + public K getKey() { + return key[index]; + } + + @Override + public K left() { + return key[index]; + } + + @Override + public short getShortValue() { + return value[index]; + } + + @Override + public short rightShort() { + return value[index]; + } + + @Override + public short setValue(final short v) { + final short oldValue = value[index]; + value[index] = v; + return oldValue; + } + + @Override + public ObjectShortPair right(final short v) { + value[index] = v; + return this; + } + + @Deprecated + @Override + public Short getValue() { + return value[index]; + } + + @Deprecated + @Override + public Short setValue(final Short v) { + return Short.valueOf(setValue((v).shortValue())); + } + + @SuppressWarnings("unchecked") + @Override + public boolean equals(final Object o) { + if (!(o instanceof Map.Entry)) return false; + Map.Entry e = (Map.Entry) o; + return strategy.equals(key[index], (e.getKey())) && ((value[index]) == ((e.getValue()).shortValue())); + } + + @Override + public int hashCode() { + return hash[index] ^ value[index]; + } + + @Override + public String toString() { + return key[index] + "=>" + value[index]; + } + } + + private abstract class MapIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNullKey = Object2ShortOpenCustomCachedHashMap.this.containsNullKey; + ObjectArrayList wrapped; + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + public boolean hasNext() { + return c != 0; + } + + public int nextEntry() { + c--; + if (mustReturnNullKey) { + mustReturnNullKey = false; + return last = n; + } + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + final int[] hash = Object2ShortOpenCustomCachedHashMap.this.hash; + final int mask = Object2ShortOpenCustomCachedHashMap.this.mask; + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + return p; + } + if (!((key[pos]) == null)) return last = pos; + } + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNullKey) { + mustReturnNullKey = false; + acceptOnIndex(action, last = n); + c--; + } + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + final int[] hash = Object2ShortOpenCustomCachedHashMap.this.hash; + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + final K k = wrapped.get(-pos - 1); + final int h = strategy.hashCode(k); + int p = HashCommon.mix(h) & mask; + while (!(hash[p] == h && strategy.equals(key[p], k))) p = (p + 1) & mask; + acceptOnIndex(action, p); + c--; + } else if (!((key[pos]) == null)) { + acceptOnIndex(action, last = pos); + c--; + } + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + final short[] value = Object2ShortOpenCustomCachedHashMap.this.value; + final int[] hash = Object2ShortOpenCustomCachedHashMap.this.hash; + final int mask = Object2ShortOpenCustomCachedHashMap.this.mask; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + value[last] = value[pos]; + hash[last] = ch; + } + } + + public void remove() { + if (last == n) { + containsNullKey = false; + key[n] = null; + hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + Object2ShortOpenCustomCachedHashMap.this.removeShort(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + public int skip(final int n) { + int i = n; + while (i-- != 0 && hasNext()) nextEntry(); + return n - i - 1; + } + } + + private final class EntryIterator extends MapIterator>> implements ObjectIterator> { + + private MapEntry entry; + + @Override + public MapEntry next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(entry = new MapEntry(index)); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private final class FastEntryIterator extends MapIterator>> implements ObjectIterator> { + + private final MapEntry entry = new MapEntry(); + + @Override + public MapEntry next() { + entry.index = nextEntry(); + return entry; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + entry.index = index; + action.accept(entry); + } + } + + private abstract class MapSpliterator> { + + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = Object2ShortOpenCustomCachedHashMap.this.containsNullKey; + boolean hasSplit = false; + + MapSpliterator() {} + + MapSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + abstract void acceptOnIndex(final ConsumerType action, final int index); + + abstract SplitType makeForSplit(int pos, int max, boolean mustReturnNull); + + public boolean tryAdvance(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + return true; + } + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + ++c; + acceptOnIndex(action, pos++); + return true; + } + ++pos; + } + return false; + } + + public void forEachRemaining(final ConsumerType action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + acceptOnIndex(action, n); + } + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + while (pos < max) { + if (!((key[pos]) == null)) { + acceptOnIndex(action, pos); + ++c; + } + ++pos; + } + } + + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + public SplitType trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SplitType split = makeForSplit(retPos, myNewPos, mustReturnNull); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + public int skip(int n) { + if (n == 0) return 0; + int skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + while (pos < max && n > 0) { + if (!((key[pos++]) == null)) { + ++skipped; + --n; + } + } + return skipped; + } + } + + private final class EntrySpliterator extends MapSpliterator>, EntrySpliterator> implements ObjectSpliterator> { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + EntrySpliterator() {} + + EntrySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer> action, final int index) { + action.accept(new MapEntry(index)); + } + + @Override + EntrySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new EntrySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class MapEntrySet extends AbstractObjectSet> implements FastEntrySet { + + @Override + public ObjectIterator> iterator() { + return new EntryIterator(); + } + + @Override + public ObjectIterator> fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectSpliterator> spliterator() { + return new EntrySpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean contains(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Short)) return false; + final K k = ((K) e.getKey()); + final short v = ((Short) (e.getValue())).shortValue(); + if (strategy.equals(k, null)) return Object2ShortOpenCustomCachedHashMap.this.containsNullKey && ((value[n]) == (v)); + K curr; + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + final int mask = Object2ShortOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) return ((value[pos]) == (v)); + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean remove(final Object o) { + if (!(o instanceof Map.Entry e)) return false; + if (e.getValue() == null || !(e.getValue() instanceof Short)) return false; + final K k = ((K) e.getKey()); + final short v = ((Short) (e.getValue())).shortValue(); + if (strategy.equals(k, null)) { + if (containsNullKey && ((value[n]) == (v))) { + removeNullEntry(); + return true; + } + return false; + } + K curr; + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + final int mask = Object2ShortOpenCustomCachedHashMap.this.mask; + int pos; + if (((curr = key[pos = (HashCommon.mix(strategy.hashCode(k))) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + return false; + } + while (true) { + if (((curr = key[pos = (pos + 1) & mask]) == null)) return false; + if (strategy.equals(k, curr)) { + if (((value[pos]) == (v))) { + removeEntry(pos); + return true; + } + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Object2ShortOpenCustomCachedHashMap.this.clear(); + } + + @Override + public void forEach(final Consumer> consumer) { + if (containsNullKey) consumer.accept(new MapEntry(n)); + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(new MapEntry(pos)); + } + + @Override + public void fastForEach(final Consumer> consumer) { + final MapEntry entry = new MapEntry(); + if (containsNullKey) { + entry.index = n; + consumer.accept(entry); + } + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + for (int pos = n; pos-- != 0;) + if (!((key[pos]) == null)) { + entry.index = pos; + consumer.accept(entry); + } + } + } + + @Override + public FastEntrySet object2ShortEntrySet() { + if (entries == null) entries = new MapEntrySet(); + return entries; + } + + private final class KeyIterator extends MapIterator> implements ObjectIterator { + + public KeyIterator() { + super(); + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + public K next() { + return key[nextEntry()]; + } + } + + private final class KeySpliterator extends MapSpliterator, KeySpliterator> implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + KeySpliterator() {} + + KeySpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final Consumer action, final int index) { + action.accept(key[index]); + } + + @Override + KeySpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new KeySpliterator(pos, max, mustReturnNull, true); + } + } + + private final class KeySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new KeySpliterator(); + } + + @Override + public void forEach(final Consumer consumer) { + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + if (containsNullKey) consumer.accept(key[n]); + for (int pos = n; pos-- != 0;) { + final K k = key[pos]; + if (!((k) == null)) consumer.accept(k); + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(Object k) { + return containsKey(k); + } + + @Override + public boolean remove(Object k) { + final int oldSize = size; + Object2ShortOpenCustomCachedHashMap.this.removeShort(k); + return size != oldSize; + } + + @Override + public void clear() { + Object2ShortOpenCustomCachedHashMap.this.clear(); + } + } + + @Override + public ObjectSet keySet() { + if (keys == null) keys = new KeySet(); + return keys; + } + + private final class ValueIterator extends MapIterator implements ShortIterator { + + public ValueIterator() { + super(); + } + + @Override + void acceptOnIndex(final ShortConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + public short nextShort() { + return value[nextEntry()]; + } + } + + private final class ValueSpliterator extends MapSpliterator implements ShortSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ShortSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + + ValueSpliterator() {} + + ValueSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + super(pos, max, mustReturnNull, hasSplit); + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ShortSpliterators.COLLECTION_SPLITERATOR_CHARACTERISTICS; + } + + @Override + void acceptOnIndex(final ShortConsumer action, final int index) { + action.accept(value[index]); + } + + @Override + ValueSpliterator makeForSplit(int pos, int max, boolean mustReturnNull) { + return new ValueSpliterator(pos, max, mustReturnNull, true); + } + } + + @Override + public ShortCollection values() { + if (values == null) values = new AbstractShortCollection() { + + @Override + public ShortIterator iterator() { + return new ValueIterator(); + } + + @Override + public ShortSpliterator spliterator() { + return new ValueSpliterator(); + } + + /** {@inheritDoc} */ + @Override + public void forEach(final ShortConsumer consumer) { + final K[] key = Object2ShortOpenCustomCachedHashMap.this.key; + final short[] value = Object2ShortOpenCustomCachedHashMap.this.value; + if (containsNullKey) consumer.accept(value[n]); + for (int pos = n; pos-- != 0;) if (!((key[pos]) == null)) consumer.accept(value[pos]); + } + + @Override + public int size() { + return size; + } + + @Override + public boolean contains(short v) { + return containsValue(v); + } + + @Override + public void clear() { + Object2ShortOpenCustomCachedHashMap.this.clear(); + } + }; + return values; + } + + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final short[] value = this.value; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final short[] newValue = new short[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + for (int j = realSize(); j-- != 0;) { + while (((key[--i]) == null)); + if (!((newKey[pos = HashCommon.mix(h = hash[i]) & mask]) == null)) + while (!((newKey[pos = (pos + 1) & mask]) == null)); + newKey[pos] = key[i]; + newValue[pos] = value[i]; + newHash[pos] = h; + } + newKey[newN] = key[n]; + newValue[newN] = value[n]; + n = newN; + this.mask = mask; + maxFill = maxFill(n, f); + this.key = newKey; + this.value = newValue; + this.hash = newHash; + } + + @Override + public Object2ShortOpenCustomCachedHashMap clone() { + Object2ShortOpenCustomCachedHashMap c = (Object2ShortOpenCustomCachedHashMap) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final short[] value = this.value; + final int[] hash = this.hash; + for (int j = realSize(), i = 0, t = 0; j-- != 0;) { + while (((key[i]) == null)) i++; + if (this != key[i]) t = hash[i]; + t ^= value[i]; + h += t; + i++; + } + if (containsNullKey) h += value[n]; + return h; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/ObjectOpenCachedHashSet.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/ObjectOpenCachedHashSet.java new file mode 100644 index 0000000..98775fb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/ObjectOpenCachedHashSet.java @@ -0,0 +1,509 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.Spliterator; +import java.util.function.Consumer; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查键的相等性。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class ObjectOpenCachedHashSet extends ObjectOpenHashSet { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = entry.hashCode(); + } + } + + /** 按预计元素数分配空集合,使用指定负载因子。 */ + public ObjectOpenCachedHashSet(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + /** 按预计元素数分配空集合,使用默认负载因子。 */ + public ObjectOpenCachedHashSet(final int expected) { + super(expected, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 使用默认初始容量和负载因子创建空集合。 */ + public ObjectOpenCachedHashSet() { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); + hash = new int[n + 1]; + } + + /** 复制普通集合的元素,以指定负载因子分配容量。 */ + public ObjectOpenCachedHashSet(final Collection c, final float f) { + super(c.size(), f); + hash = new int[n + 1]; + addAll(c); + } + + /** 复制普通集合的元素,使用默认负载因子。 */ + public ObjectOpenCachedHashSet(final Collection c) { + this(c, DEFAULT_LOAD_FACTOR); + } + + /** 复制 fastutil 集合的元素,使用指定负载因子。 */ + public ObjectOpenCachedHashSet(final ObjectCollection c, final float f) { + super(c.size(), f); + hash = new int[n + 1]; + addAll(c); + } + + /** 复制 fastutil 集合的元素,使用默认负载因子。 */ + public ObjectOpenCachedHashSet(final ObjectCollection c) { + this(c, DEFAULT_LOAD_FACTOR); + } + + /** 消耗迭代器的剩余元素,使用指定负载因子。 */ + public ObjectOpenCachedHashSet(final Iterator i, final float f) { + super(DEFAULT_INITIAL_SIZE, f); + hash = new int[n + 1]; + while (i.hasNext()) add(i.next()); + } + + /** 消耗迭代器的剩余元素,使用默认负载因子。 */ + public ObjectOpenCachedHashSet(final Iterator i) { + this(i, DEFAULT_LOAD_FACTOR); + } + + /** 复制数组的一段连续区间,使用指定负载因子。偏移和长度须在数组范围内。 */ + public ObjectOpenCachedHashSet(final K[] a, final int offset, final int length, final float f) { + super(Math.max(length, 0), f); + hash = new int[n + 1]; + ObjectArrays.ensureOffsetLength(a, offset, length); + for (int i = 0; i < length; i++) add(a[offset + i]); + } + + /** 复制数组的一段连续区间,使用默认负载因子。 */ + public ObjectOpenCachedHashSet(final K[] a, final int offset, final int length) { + this(a, offset, length, DEFAULT_LOAD_FACTOR); + } + + /** 复制整个数组,使用指定负载因子。 */ + public ObjectOpenCachedHashSet(final K[] a, final float f) { + this(a, 0, a.length, f); + } + + /** 复制整个数组,使用默认负载因子。 */ + public ObjectOpenCachedHashSet(final K[] a) { + this(a, 0, a.length, DEFAULT_LOAD_FACTOR); + } + + private int realSize() { + return containsNull ? size - 1 : size; + } + + @Override + public boolean add(final K k) { + if (k == null) { + if (containsNull) return false; + containsNull = true; + } else { + final int h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do { + if (hash[pos] == h && (curr == k || curr.equals(k))) return false; + } while ((curr = key[pos = (pos + 1) & mask]) != null); + } + key[pos] = k; + hash[pos] = h; + } + if (size++ >= maxFill) rehash(HashCommon.arraySize(size + 1, f)); + return true; + } + + @Override + public K addOrGet(final K k) { + if (k == null) { + if (containsNull) return key[n]; + containsNull = true; + } else { + final int h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do { + if (hash[pos] == h && (curr == k || curr.equals(k))) return curr; + } while ((curr = key[pos = (pos + 1) & mask]) != null); + } + key[pos] = k; + hash[pos] = h; + } + if (size++ >= maxFill) rehash(HashCommon.arraySize(size + 1, f)); + return k; + } + + private boolean removeEntry(int pos) { + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return true; + } + + private boolean removeNullEntry() { + containsNull = false; + key[n] = null; + hash[n] = 0; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return true; + } + + @Override + public boolean remove(final Object k) { + if (k == null) { + if (containsNull) return removeNullEntry(); + return false; + } + final int h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return removeEntry(pos); + } + } + + @Override + public boolean contains(final Object k) { + if (k == null) return containsNull; + final int h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (k == curr || k.equals(curr))) return true; + } + } + + @Override + public K get(final Object k) { + if (k == null) return key[n]; + final int h = k.hashCode(); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return null; + if (hash[pos] == h && (k == curr || k.equals(curr))) return curr; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return null; + if (hash[pos] == h && (k == curr || k.equals(curr))) return curr; + } + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNull = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + @Override + public ObjectIterator iterator() { + return new SetIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new SetSpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + K k; + for (int j = realSize(); j-- != 0;) { + while ((k = key[--i]) == null); + h = hash[i]; + pos = HashCommon.mix(h) & mask; + if (newKey[pos] != null) while ((newKey[pos = (pos + 1) & mask]) != null); + newKey[pos] = k; + newHash[pos] = h; + } + n = newN; + this.mask = mask; + maxFill = HashCommon.maxFill(n, f); + this.key = newKey; + this.hash = newHash; + } + + @Override + public ObjectOpenCachedHashSet clone() { + ObjectOpenCachedHashSet c = (ObjectOpenCachedHashSet) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final int[] hash = this.hash; + for (int j = realSize(), i = 0; j-- != 0;) { + while (key[i] == null) i++; + if (this != key[i]) h += hash[i]; + i++; + } + return h; + } + + private final class SetIterator implements ObjectIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNull = ObjectOpenCachedHashSet.this.containsNull; + ObjectArrayList wrapped; + + @Override + public boolean hasNext() { + return c != 0; + } + + @Override + public K next() { + c--; + final K[] key = ObjectOpenCachedHashSet.this.key; + if (mustReturnNull) { + mustReturnNull = false; + last = n; + return key[n]; + } + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + return wrapped.get(-pos - 1); + } + if (key[pos] != null) return key[last = pos]; + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = ObjectOpenCachedHashSet.this.key; + final int[] hash = ObjectOpenCachedHashSet.this.hash; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + hash[last] = ch; + } + } + + @Override + public void remove() { + if (last == -1) throw new IllegalStateException(); + if (last == n) { + ObjectOpenCachedHashSet.this.containsNull = false; + ObjectOpenCachedHashSet.this.key[n] = null; + ObjectOpenCachedHashSet.this.hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + ObjectOpenCachedHashSet.this.remove(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + @Override + public void forEachRemaining(final Consumer action) { + final K[] key = ObjectOpenCachedHashSet.this.key; + if (mustReturnNull) { + mustReturnNull = false; + last = n; + action.accept(key[n]); + c--; + } + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + action.accept(wrapped.get(-pos - 1)); + c--; + } else if (key[pos] != null) { + action.accept(key[last = pos]); + c--; + } + } + } + } + + private final class SetSpliterator implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = ObjectOpenCachedHashSet.this.containsNull; + boolean hasSplit = false; + + SetSpliterator() {} + + SetSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + @Override + public boolean tryAdvance(final Consumer action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + action.accept(key[n]); + return true; + } + final K[] key = ObjectOpenCachedHashSet.this.key; + while (pos < max) { + if (key[pos] != null) { + ++c; + action.accept(key[pos++]); + return true; + } else { + ++pos; + } + } + return false; + } + + @Override + public void forEachRemaining(final Consumer action) { + final K[] key = ObjectOpenCachedHashSet.this.key; + if (mustReturnNull) { + mustReturnNull = false; + action.accept(key[n]); + ++c; + } + while (pos < max) { + if (key[pos] != null) { + action.accept(key[pos]); + ++c; + } + ++pos; + } + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + @Override + public SetSpliterator trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SetSpliterator split = new SetSpliterator(retPos, myNewPos, mustReturnNull, true); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + @Override + public long skip(long n) { + if (n == 0) return 0; + long skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = ObjectOpenCachedHashSet.this.key; + while (pos < max && n > 0) { + if (key[pos++] != null) { + ++skipped; + --n; + } + } + return skipped; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/ObjectOpenCustomCachedHashSet.java b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/ObjectOpenCustomCachedHashSet.java new file mode 100644 index 0000000..6861f70 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/collection/map/hash/ObjectOpenCustomCachedHashSet.java @@ -0,0 +1,519 @@ +package com.modularmc.mmclutils.api.collection.map.hash; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.objects.*; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.Spliterator; +import java.util.function.Consumer; + +/** 缓存键哈希的开放寻址容器。先比较哈希和对象身份,再检查调用方的相等策略。 扩容时复用哈希值,实例由单个线程使用。 */ +public final class ObjectOpenCustomCachedHashSet extends ObjectOpenCustomHashSet { + + private int[] hash; + + @Serial + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // fastutil 按读入后的槽位重建哈希表,缓存哈希要与新的槽位对齐。 + hash = new int[n + 1]; + for (int i = 0; i < n; i++) { + K entry = key[i]; + if (entry != null) hash[i] = strategy.hashCode(entry); + } + } + + /** 按预计元素数分配空集合,使用指定负载因子。 */ + public ObjectOpenCustomCachedHashSet(final int expected, final float f, final Hash.Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + /** 按预计元素数分配空集合,使用默认负载因子。 */ + public ObjectOpenCustomCachedHashSet(final int expected, final Hash.Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** 使用给定散列策略和默认容量参数创建空集合。 */ + public ObjectOpenCustomCachedHashSet(final Hash.Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + /** 复制普通集合的元素,以指定负载因子分配容量。 */ + public ObjectOpenCustomCachedHashSet(final Collection c, final float f, final Hash.Strategy strategy) { + super(c.size(), f, strategy); + hash = new int[n + 1]; + addAll(c); + } + + /** 复制普通集合的元素,使用默认负载因子。 */ + public ObjectOpenCustomCachedHashSet(final Collection c, final Hash.Strategy strategy) { + this(c, DEFAULT_LOAD_FACTOR, strategy); + } + + /** 复制 fastutil 集合的元素,使用指定负载因子。 */ + public ObjectOpenCustomCachedHashSet(final ObjectCollection c, final float f, final Hash.Strategy strategy) { + super(c.size(), f, strategy); + hash = new int[n + 1]; + addAll(c); + } + + /** 复制 fastutil 集合的元素,使用默认负载因子。 */ + public ObjectOpenCustomCachedHashSet(final ObjectCollection c, final Hash.Strategy strategy) { + this(c, DEFAULT_LOAD_FACTOR, strategy); + } + + /** 消耗迭代器的剩余元素,使用指定负载因子。 */ + public ObjectOpenCustomCachedHashSet(final Iterator i, final float f, final Hash.Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, f, strategy); + hash = new int[n + 1]; + while (i.hasNext()) add(i.next()); + } + + /** 消耗迭代器的剩余元素,使用默认负载因子。 */ + public ObjectOpenCustomCachedHashSet(final Iterator i, final Hash.Strategy strategy) { + this(i, DEFAULT_LOAD_FACTOR, strategy); + } + + /** 复制数组的一段连续区间,使用指定负载因子。偏移和长度须在数组范围内。 */ + public ObjectOpenCustomCachedHashSet(final K[] a, final int offset, final int length, final float f, final Hash.Strategy strategy) { + super(Math.max(length, 0), f, strategy); + hash = new int[n + 1]; + ObjectArrays.ensureOffsetLength(a, offset, length); + for (int i = 0; i < length; i++) add(a[offset + i]); + } + + /** 复制数组的一段连续区间,使用默认负载因子。 */ + public ObjectOpenCustomCachedHashSet(final K[] a, final int offset, final int length, final Hash.Strategy strategy) { + this(a, offset, length, DEFAULT_LOAD_FACTOR, strategy); + } + + /** 复制整个数组,使用指定负载因子。 */ + public ObjectOpenCustomCachedHashSet(final K[] a, final float f, final Hash.Strategy strategy) { + this(a, 0, a.length, f, strategy); + } + + /** 复制整个数组,使用默认负载因子。 */ + public ObjectOpenCustomCachedHashSet(final K[] a, final Hash.Strategy strategy) { + this(a, 0, a.length, DEFAULT_LOAD_FACTOR, strategy); + } + + private int realSize() { + return containsNull ? size - 1 : size; + } + + @Override + public boolean add(final K k) { + if (strategy.equals(k, null)) { + if (containsNull) return false; + containsNull = true; + key[n] = k; + } else { + final int h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do { + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return false; + } while ((curr = key[pos = (pos + 1) & mask]) != null); + } + key[pos] = k; + hash[pos] = h; + } + if (size++ >= maxFill) rehash(HashCommon.arraySize(size + 1, f)); + return true; + } + + @Override + public K addOrGet(final K k) { + if (strategy.equals(k, null)) { + if (containsNull) return key[n]; + containsNull = true; + key[n] = k; + } else { + final int h = strategy.hashCode(k); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) != null) { + do { + if (hash[pos] == h && (k == curr || strategy.equals(k, curr))) return curr; + } while ((curr = key[pos = (pos + 1) & mask]) != null); + } + key[pos] = k; + hash[pos] = h; + } + if (size++ >= maxFill) rehash(HashCommon.arraySize(size + 1, f)); + return k; + } + + private boolean removeEntry(int pos) { + size--; + int last, slot, ch; + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + a: + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + break a; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + key[last] = curr; + hash[last] = ch; + } + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return true; + } + + private boolean removeNullEntry() { + containsNull = false; + key[n] = null; + hash[n] = 0; + size--; + if (n > minN && size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) rehash(n / 2); + return true; + } + + @Override + public boolean remove(final Object k) { + if (strategy.equals((K) k, null)) { + if (containsNull) return removeNullEntry(); + return false; + } + @SuppressWarnings("unchecked") + final K kk = (K) k; + final int h = strategy.hashCode(kk); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (kk == curr || strategy.equals(kk, curr))) return removeEntry(pos); + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (kk == curr || strategy.equals(kk, curr))) return removeEntry(pos); + } + } + + @Override + public boolean contains(final Object k) { + if (strategy.equals((K) k, null)) return containsNull; + @SuppressWarnings("unchecked") + final K kk = (K) k; + final int h = strategy.hashCode(kk); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return false; + if (hash[pos] == h && (kk == curr || strategy.equals(kk, curr))) return true; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return false; + if (hash[pos] == h && (kk == curr || strategy.equals(kk, curr))) return true; + } + } + + @Override + public K get(final Object k) { + if (strategy.equals((K) k, null)) return key[n]; + @SuppressWarnings("unchecked") + final K kk = (K) k; + final int h = strategy.hashCode(kk); + K curr; + final K[] key = this.key; + final int[] hash = this.hash; + int pos; + if ((curr = key[pos = HashCommon.mix(h) & mask]) == null) return null; + if (hash[pos] == h && (kk == curr || strategy.equals(kk, curr))) return curr; + while (true) { + if ((curr = key[pos = (pos + 1) & mask]) == null) return null; + if (hash[pos] == h && (kk == curr || strategy.equals(kk, curr))) return curr; + } + } + + @Override + public void clear() { + if (size == 0) return; + size = 0; + containsNull = false; + Arrays.fill(key, (null)); + Arrays.fill(hash, 0); + } + + @Override + public ObjectIterator iterator() { + return new SetIterator(); + } + + @Override + public ObjectSpliterator spliterator() { + return new SetSpliterator(); + } + + @Override + @SuppressWarnings("unchecked") + protected void rehash(final int newN) { + final K[] key = this.key; + final int[] hash = this.hash; + final int mask = newN - 1; + final K[] newKey = (K[]) new Object[newN + 1]; + final int[] newHash = new int[newN + 1]; + int i = n, pos, h; + K k; + for (int j = realSize(); j-- != 0;) { + while ((k = key[--i]) == null); + h = hash[i]; + pos = HashCommon.mix(h) & mask; + if (newKey[pos] != null) while ((newKey[pos = (pos + 1) & mask]) != null); + newKey[pos] = k; + newHash[pos] = h; + } + newKey[newN] = key[n]; + n = newN; + this.mask = mask; + maxFill = HashCommon.maxFill(n, f); + this.key = newKey; + this.hash = newHash; + } + + @Override + public ObjectOpenCustomCachedHashSet clone() { + ObjectOpenCustomCachedHashSet c = (ObjectOpenCustomCachedHashSet) super.clone(); + c.hash = hash.clone(); + return c; + } + + @Override + public int hashCode() { + int h = 0; + final K[] key = this.key; + final int[] hash = this.hash; + for (int j = realSize(), i = 0; j-- != 0;) { + while (key[i] == null) i++; + if (this != key[i]) h += hash[i]; + i++; + } + return h; + } + + private final class SetIterator implements ObjectIterator { + + int pos = n; + int last = -1; + int c = size; + boolean mustReturnNull = ObjectOpenCustomCachedHashSet.this.containsNull; + ObjectArrayList wrapped; + + @Override + public boolean hasNext() { + return c != 0; + } + + @Override + public K next() { + c--; + final K[] key = ObjectOpenCustomCachedHashSet.this.key; + if (mustReturnNull) { + mustReturnNull = false; + last = n; + return key[n]; + } + for (;;) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + return wrapped.get(-pos - 1); + } + if (key[pos] != null) return key[last = pos]; + } + } + + private void shiftKeys(int pos) { + int last, slot, ch; + K curr; + final K[] key = ObjectOpenCustomCachedHashSet.this.key; + final int[] hash = ObjectOpenCustomCachedHashSet.this.hash; + for (;;) { + pos = ((last = pos) + 1) & mask; + for (;;) { + if ((curr = key[pos]) == null) { + key[last] = null; + hash[last] = 0; + return; + } + ch = hash[pos]; + slot = HashCommon.mix(ch) & mask; + if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; + pos = (pos + 1) & mask; + } + if (pos < last) { + if (wrapped == null) wrapped = new ObjectArrayList<>(2); + wrapped.add(key[pos]); + } + key[last] = curr; + hash[last] = ch; + } + } + + @Override + public void remove() { + if (last == -1) throw new IllegalStateException(); + if (last == n) { + ObjectOpenCustomCachedHashSet.this.containsNull = false; + ObjectOpenCustomCachedHashSet.this.key[n] = null; + ObjectOpenCustomCachedHashSet.this.hash[n] = 0; + } else if (pos >= 0) shiftKeys(last); + else { + ObjectOpenCustomCachedHashSet.this.remove(wrapped.set(-pos - 1, null)); + last = -1; + return; + } + size--; + last = -1; + } + + @Override + public void forEachRemaining(final Consumer action) { + final K[] key = ObjectOpenCustomCachedHashSet.this.key; + if (mustReturnNull) { + mustReturnNull = false; + last = n; + action.accept(key[n]); + c--; + } + while (c != 0) { + if (--pos < 0) { + last = Integer.MIN_VALUE; + action.accept(wrapped.get(-pos - 1)); + c--; + } else if (key[pos] != null) { + action.accept(key[last = pos]); + c--; + } + } + } + } + + private final class SetSpliterator implements ObjectSpliterator { + + private static final int POST_SPLIT_CHARACTERISTICS = ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS & ~Spliterator.SIZED; + int pos = 0; + int max = n; + int c = 0; + boolean mustReturnNull = ObjectOpenCustomCachedHashSet.this.containsNull; + boolean hasSplit = false; + + SetSpliterator() {} + + SetSpliterator(int pos, int max, boolean mustReturnNull, boolean hasSplit) { + this.pos = pos; + this.max = max; + this.mustReturnNull = mustReturnNull; + this.hasSplit = hasSplit; + } + + @Override + public boolean tryAdvance(final Consumer action) { + if (mustReturnNull) { + mustReturnNull = false; + ++c; + action.accept(key[n]); + return true; + } + final K[] key = ObjectOpenCustomCachedHashSet.this.key; + while (pos < max) { + if (key[pos] != null) { + ++c; + action.accept(key[pos++]); + return true; + } else { + ++pos; + } + } + return false; + } + + @Override + public void forEachRemaining(final Consumer action) { + final K[] key = ObjectOpenCustomCachedHashSet.this.key; + if (mustReturnNull) { + mustReturnNull = false; + action.accept(key[n]); + ++c; + } + while (pos < max) { + if (key[pos] != null) { + action.accept(key[pos]); + ++c; + } + ++pos; + } + } + + @Override + public int characteristics() { + return hasSplit ? POST_SPLIT_CHARACTERISTICS : ObjectSpliterators.SET_SPLITERATOR_CHARACTERISTICS; + } + + @Override + public long estimateSize() { + if (!hasSplit) { + return size - c; + } else { + return Math.min(size - c, (long) (((double) realSize() / n) * (max - pos)) + (mustReturnNull ? 1 : 0)); + } + } + + @Override + public SetSpliterator trySplit() { + if (pos >= max - 1) return null; + int retLen = (max - pos) >> 1; + if (retLen <= 1) return null; + int myNewPos = pos + retLen; + int retPos = pos; + SetSpliterator split = new SetSpliterator(retPos, myNewPos, mustReturnNull, true); + this.pos = myNewPos; + this.mustReturnNull = false; + this.hasSplit = true; + return split; + } + + @Override + public long skip(long n) { + if (n == 0) return 0; + long skipped = 0; + if (mustReturnNull) { + mustReturnNull = false; + ++skipped; + --n; + } + final K[] key = ObjectOpenCustomCachedHashSet.this.key; + while (pos < max && n > 0) { + if (key[pos++] != null) { + ++skipped; + --n; + } + } + return skipped; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/data/CodecUtils.java b/src/main/java/com/modularmc/mmclutils/api/data/CodecUtils.java new file mode 100644 index 0000000..301f651 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/data/CodecUtils.java @@ -0,0 +1,180 @@ +package com.modularmc.mmclutils.api.data; + +import com.modularmc.mmclutils.api.function.Memoization; + +import com.mojang.datafixers.util.Either; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.PrimitiveCodec; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import it.unimi.dsi.fastutil.objects.ObjectList; + +import java.util.Collection; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Supplier; + +/** 为原版 Codec 提供数值范围、集合容器和映射编解码。 */ +public final class CodecUtils { + + /** 使用当前数据格式写入长整数。读取时拒绝小数与超出有符号 64 位范围的数值。 */ + public static final Codec EXACT_LONG = new PrimitiveCodec<>() { + + @Override + public DataResult read(DynamicOps ops, T input) { + return ops.getNumberValue(input).flatMap(number -> { + try { + return DataResult.success(Long.parseLong(number.toString())); + } catch (NumberFormatException invalid) { + return DataResult.error(() -> "数值必须是可精确读取的长整数 " + number); + } + }); + } + + @Override + public T write(DynamicOps ops, Long value) { + return ops.createLong(value); + } + + @Override + public String toString() { + return "ExactLong"; + } + }; + + /** 精确读取含零的非负长整数,拒绝超范围或非整数字面量。 */ + public static final Codec NON_NEGATIVE_LONG = longRangeWithMessage(0, Long.MAX_VALUE, + value -> "Value must be non-negative: " + value); + /** 精确读取严格大于零的长整数。 */ + public static final Codec POSITIVE_LONG = longRangeWithMessage(1, Long.MAX_VALUE, + value -> "Value must be positive: " + value); + + private CodecUtils() {} + + /** 以列表格式编解码元素,并在读取后分配可修改的列表。写入保留原迭代顺序。 */ + public static Codec> mutableList(Codec elements) { + return elements.listOf().xmap(ObjectArrayList::new, List::copyOf); + } + + /** 读取后按元素相等性去重,保留首次出现的顺序。写入时按集合迭代顺序编码为列表。 */ + public static Codec> set(Codec elements) { + return elements.listOf().xmap(ObjectLinkedOpenHashSet::new, List::copyOf); + } + + /** 以列表格式保存枚举集合。读取后去重并按枚举声明顺序迭代。 */ + public static > Codec> enumSet(Class type, Codec elements) { + return elements.listOf().xmap(values -> { + Set result = EnumSet.noneOf(type); + result.addAll(values); + return result; + }, List::copyOf); + } + + /** 解码后生成可修改的映射,保留底层数据格式提供的条目顺序。 */ + public static Codec> orderedMap(Codec keys, Codec values) { + return Codec.unboundedMap(keys, values).xmap(Object2ObjectLinkedOpenHashMap::new, map -> map); + } + + /** 解码后用枚举序号存储键,迭代顺序遵循枚举声明。 */ + public static , V> Codec> enumMap(Class type, Codec keys, Codec values) { + return Codec.unboundedMap(keys, values).xmap(encoded -> { + Map result = new EnumMap<>(type); + result.putAll(encoded); + return result; + }, map -> map); + } + + /** 调用方提供新容器,可选择原始类型集合、比较器、引用比较策略或插入顺序。 */ + public static > Codec collection(Codec elements, Supplier create) { + return elements.listOf().xmap(values -> { + C collection = create.get(); + collection.addAll(values); + return collection; + }, List::copyOf); + } + + /** 以条目序列编码 Map,可使用无法表示为 JSON 属性名的键。重复键由容器采用最后一个值。 */ + public static > Codec entries(Codec keys, Codec values, Supplier create) { + return Codec.pair(keys.fieldOf("key").codec(), values.fieldOf("value").codec()).listOf().xmap(entries -> { + M map = create.get(); + for (Pair entry : entries) map.put(entry.getFirst(), entry.getSecond()); + return map; + }, map -> { + var entries = new ObjectArrayList>(map.size()); + map.forEach((key, value) -> entries.add(Pair.of(key, value))); + return entries; + }); + } + + /** 用相同结构表示普通值与空值,可在 NBT 中保持集合元素类型统一。 */ + public static Codec> optionalElement(Codec codec) { + return codec.optionalFieldOf("value").codec(); + } + + /** 以普通列表编码,读取为 fastutil 的可修改对象列表。 */ + public static Codec> objectListCodec(Codec elementCodec) { + return elementCodec.listOf().xmap( + values -> new ObjectArrayList<>(values), + values -> values); + } + + /** + * 精确读取长整数,并在读写两端校验闭区间。 + * + * @param min 最小值 + * @param max 最大值 + * @param errorMessage 根据超范围整数生成错误说明 + * @return 带范围约束的长整数 Codec + */ + public static Codec longRangeWithMessage(long min, long max, Function errorMessage) { + return EXACT_LONG + .validate( + value -> value.compareTo(min) >= 0 && value.compareTo(max) <= 0 ? DataResult.success(value) : + DataResult.error(() -> errorMessage.apply(value))); + } + + /** 校验闭区间内的整数。 */ + public static Codec longRange(long min, long max) { + return longRangeWithMessage(min, max, value -> "数值 " + value + " 超出区间 [" + min + ", " + max + "]"); + } + + /** 读取两侧类型相同的任一分支。 */ + public static T unboxEither(Either either) { + return either.map(Function.identity(), Function.identity()); + } + + /** 在首次读取时解码并缓存结果,解码失败由该次读取抛出。供应器由调用线程持有。 */ + public static Codec> lazyParsingCodec(Codec delegate) { + return new LazyParsingCodec<>(delegate); + } + + /** 用给定 {@link DynamicOps} 和 MapCodec 构建一个独立映射值。合并映射的失败保留在结果中。 */ + public static DataResult encodeMap(T value, MapCodec codec, DynamicOps ops) { + return codec.encode(value, ops, ops.mapBuilder()).build(ops.empty()); + } + + private record LazyParsingCodec(Codec delegate) implements Codec> { + + @Override + public DataResult, T>> decode(DynamicOps ops, T input) { + Supplier lazyValue = Memoization.memoize(() -> delegate.decode(ops, input).map(Pair::getFirst).getOrThrow()); + return DataResult.success(Pair.of(lazyValue, input)); + } + + @Override + public DataResult encode(Supplier input, DynamicOps ops, T prefix) { + A value = input.get(); + return value == null ? DataResult.success(prefix) : delegate.encode(value, ops, prefix); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/data/FastSavedData.java b/src/main/java/com/modularmc/mmclutils/api/data/FastSavedData.java new file mode 100644 index 0000000..56afa88 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/data/FastSavedData.java @@ -0,0 +1,246 @@ +package com.modularmc.mmclutils.api.data; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.api.level.LevelStore; +import com.modularmc.mmclutils.api.schedule.SerialTaskExecutor; +import com.modularmc.mmclutils.utils.FileUtils; + +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.storage.LevelResource; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.level.LevelEvent; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; + +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +/** + * 按维度和稳定标识保存紧凑二进制数据。在所属服务器线程修改值,并在修改后调用 {@link #setDirty()}。 + * 保存时复制本次要写的数据。服务器的串行写入队列保序写盘,成功后仅确认本次提交的数据版本。 + * 常规世界保存异步排队,强制刷盘与世界卸载等待写入完成,失败时再尝试一次。 + * + * @param 存档值的类型 + */ +@NullMarked +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) +public final class FastSavedData { + + private static final LevelStore>> DATA = LevelStore.create(HashMap::new, entries -> entries.values().forEach(value -> value.save(true))); + private static final Map EXECUTORS = new IdentityHashMap<>(); + + private final Type type; + private final Path path; + private final T value; + private final SerialTaskExecutor executor; + private volatile long revision; + private volatile long savedRevision; + private CompletableFuture pending = CompletableFuture.completedFuture(null); + private long submitted; + + private FastSavedData(Type type, Path path, T value, SerialTaskExecutor executor) { + this.type = type; + this.path = path; + this.value = value; + this.executor = executor; + } + + /** + * 在服务器线程取得或读取该维度的存档。新文件缺失时尝试调用方指定的旧文件。 + * 只有两个文件都缺失时才调用默认值工厂,成功读取旧数据后会安排保存为新文件。 + * + * @param level 所属维度 + * @param type 由调用方长期持有的类型。同一维度中每个标识只能对应一种类型 + * @param 存档值的类型 + * @return 维度生命周期内复用的存档对象 + * @throws IOException 文件读取失败或数据格式无效 + * @throws IllegalStateException 从非所属服务器线程访问,或同标识已用于另一类型 + */ + public static FastSavedData get(ServerLevel level, Type type) throws IOException { + checkOwner(level); + var entries = DATA.get(level); + var existing = entries.get(type.id()); + if (existing != null) { + if (existing.type != type) throw new IllegalStateException("存档类型重复:" + type.id()); + // 同一个 Type 实例约束了存储项的值类型。 + @SuppressWarnings("unchecked") + FastSavedData typed = (FastSavedData) existing; + return typed; + } + Path worldRoot = level.getServer().getWorldPath(LevelResource.ROOT).toAbsolutePath().normalize(); + Path directory = DimensionType.getStorageFolder(level.dimension(), worldRoot).resolve("data/mmclutils").normalize(); + Path path = type.id().withSuffix(".bin").resolveAgainst(directory).normalize(); + if (!path.startsWith(directory)) throw new IllegalArgumentException("存档路径超出维度数据目录:" + type.id()); + + boolean imported = false; + T value; + if (!Files.notExists(path)) { + value = FileUtils.read(path, type.reader()); + } else { + LegacyFile legacy = type.legacy(); + Path oldFile = legacy == null ? null : worldRoot.resolve(legacy.relativePath()).normalize(); + if (oldFile != null && !oldFile.startsWith(worldRoot)) throw new IOException("旧存档路径超出世界目录:" + oldFile); + imported = oldFile != null && !Files.notExists(oldFile); + value = imported ? legacy.reader().read(level, oldFile) : type.factory().get(); + } + var data = new FastSavedData<>(type, path, value, executor(level.getServer())); + if (imported) data.setDirty(); + entries.put(type.id(), data); + return data; + } + + /** 取得服务器线程持有的存档值。修改其内容后须调用 {@link #setDirty()}。 */ + public T value() { + return value; + } + + /** 在所属服务器线程修改值后调用。已经提交的写盘操作可以完成,最新数据将在下一次保存中写入。 */ + public void setDirty() { + revision++; + } + + /** 查询是否还存在尚未成功写入的数据版本。 */ + public boolean isDirty() { + return revision != savedRevision; + } + + @SubscribeEvent + private static void onLevelSave(LevelEvent.Save event) { + if (event.getLevel() instanceof ServerLevel level) saveLevel(level, false); + } + + /** 在所属服务器线程提交全部待保存数据并等待写盘队列完成。写入失败时再尝试一次。 */ + @ApiStatus.Internal + public static void flush(ServerLevel level) { + checkOwner(level); + saveLevel(level, true); + } + + private static void saveLevel(ServerLevel level, boolean wait) { + var entries = DATA.getIfPresent(level); + if (entries != null) entries.values().forEach(value -> value.save(wait)); + } + + private void save(boolean wait) { + long writingRevision = revision; + queueWrite(writingRevision); + if (!wait || awaitWrite()) return; + // 常规保存可能在强制刷盘已经开始等待后才失败。 + queueWrite(writingRevision); + awaitWrite(); + } + + private void queueWrite(long writingRevision) { + if (writingRevision == savedRevision || submitted == writingRevision && !pending.isCompletedExceptionally()) return; + T valueToWrite = type.copyForWrite().apply(value); + submitted = writingRevision; + pending = executor.submit(() -> { + FileUtils.writeAtomically(path, valueToWrite, type.writer()); + // 写盘期间发生的修改留给下一次保存。 + savedRevision = writingRevision; + return null; + }); + pending.whenComplete((ignored, failure) -> { + if (failure != null) ModularMCLibUtils.LOGGER.error("写入二进制存档 {} 失败", path, failure); + }); + } + + private boolean awaitWrite() { + return pending.handle((ignored, failure) -> failure == null).join(); + } + + private static synchronized SerialTaskExecutor executor(MinecraftServer server) { + return EXECUTORS.computeIfAbsent(server, ignored -> new SerialTaskExecutor("mmclutils-save")); + } + + @SubscribeEvent + private static void onStopped(ServerStoppedEvent event) { + SerialTaskExecutor executor; + synchronized (FastSavedData.class) { + executor = EXECUTORS.remove(event.getServer()); + } + if (executor != null) executor.close(); + } + + private static void checkOwner(ServerLevel level) { + if (!level.getServer().isSameThread()) throw new IllegalStateException("存档须在所属服务器线程访问"); + } + + /** + * 定义一个存档的标识、复制方式和读写格式。 + * + * @param id 用于文件位置的稳定标识 + * @param factory 新旧文件均不存在时提供默认值 + * @param copyForWrite 在世界线程复制写入所需数据。返回值与继续在世界线程修改的状态独立 + * @param reader 在服务器线程解码当前格式 + * @param writer 在服务器的后台队列编码复制后的数据 + * @param legacy 仅在新文件缺失时使用的旧格式入口,可以为空 + * @param 存档值的类型 + */ + public record Type(Identifier id, Supplier factory, UnaryOperator copyForWrite, + FileUtils.Reader reader, FileUtils.Writer writer, + @Nullable LegacyFile legacy) { + + /** + * 定义只读取当前文件格式的存档类型。 + * + * @param id 用于文件位置的稳定标识 + * @param factory 文件不存在时提供默认值 + * @param copyForWrite 在世界线程复制写入所需数据 + * @param reader 解码当前文件 + * @param writer 在后台编码交付的数据 + */ + public Type(Identifier id, Supplier factory, UnaryOperator copyForWrite, + FileUtils.Reader reader, FileUtils.Writer writer) { + this(id, factory, copyForWrite, reader, writer, null); + } + } + + /** + * 指定可从旧布局导入的文件。在服务器线程使用,并可访问所属维度的注册表。 + * + * @param relativePath 相对整个世界根目录的路径 + * @param reader 文件存在时使用的旧格式读取器 + * @param 读取值的类型 + */ + public record LegacyFile(Path relativePath, LegacyReader reader) { + + /** 指定世界目录下的旧文件和读取器。路径须为相对路径。 */ + public LegacyFile { + if (relativePath.isAbsolute()) throw new IllegalArgumentException("旧存档路径须相对于世界目录"); + } + } + + /** + * 在服务器线程读取旧格式,仅在当前存档缺失时调用。 + * + * @param 读取得到的存档值的类型 + */ + @FunctionalInterface + public interface LegacyReader { + + /** + * 读取旧二进制或 NBT 文件,并关闭自行打开的流。 + * + * @param level 所属维度,可用于查询注册表 + * @param path 已确认存在的旧文件 + * @return 可由当前存档类型保存的非空值 + * @throws IOException 打开或读取文件失败,或者文件格式无效 + */ + T read(ServerLevel level, Path path) throws IOException; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/data/StreamCodecs.java b/src/main/java/com/modularmc/mmclutils/api/data/StreamCodecs.java new file mode 100644 index 0000000..4fc2e0e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/data/StreamCodecs.java @@ -0,0 +1,365 @@ +package com.modularmc.mmclutils.api.data; + +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; + +import com.mojang.datafixers.util.Function12; +import com.mojang.datafixers.util.Function13; +import com.mojang.datafixers.util.Function8; +import io.netty.buffer.ByteBuf; + +import java.util.Map; +import java.util.function.Function; +import java.util.function.IntFunction; + +/** + * 创建按键选择值编码器及按固定顺序组合多个字段的流编解码。 + * 组合编码器先依次写字段,解码时按相同顺序读取并传入构造函数。 + */ +public class StreamCodecs { + + /** + * 创建带条目数前缀的映射编解码器,每个值的编码器由其键选择。 + * 解码时将容量限制为不超过 65536 后交给映射工厂,重复键如何处理由映射实现决定。 + * + * @param 字节缓冲区类型 + * @param 映射键类型 + * @param 映射值类型 + * @param 目标映射类型 + * @param mapCreationFunction 根据初始容量创建空映射 + * @param keyCodec 键的编解码器 + * @param valueFunction 根据键选择对应值编解码器 + * @return 映射的流编解码器 + */ + public static > StreamCodec dispatchMap( + final IntFunction mapCreationFunction, + final StreamCodec keyCodec, + final Function> valueFunction) { + return new StreamCodec<>() { + + public void encode(B buf, M val) { + ByteBufCodecs.writeCount(buf, val.size(), Integer.MAX_VALUE); + val.forEach((key, value) -> { + keyCodec.encode(buf, key); + valueFunction.apply(key).encode(buf, value); + }); + } + + public M decode(B buf) { + int i = ByteBufCodecs.readCount(buf, Integer.MAX_VALUE); + M m = mapCreationFunction.apply(Math.min(i, 65536)); + + for (int j = 0; j < i; j++) { + K k = keyCodec.decode(buf); + V v = valueFunction.apply(k).decode(buf); + m.put(k, v); + } + + return m; + } + }; + } + + /** + * 创建包含八个字段的组合编解码器。 + * 字段按照参数顺序写入和读取,解码后的八个值按相同顺序传给构造函数。 + * + * @param 字节缓冲区类型 + * @param 编解码对象类型 + * @param 第一个字段类型 + * @param 第二个字段类型 + * @param 第三个字段类型 + * @param 第四个字段类型 + * @param 第五个字段类型 + * @param 第六个字段类型 + * @param 第七个字段类型 + * @param 第八个字段类型 + * @param codec1 第一个字段的编解码器 + * @param getter1 从对象取得第一个字段 + * @param codec2 第二个字段的编解码器 + * @param getter2 从对象取得第二个字段 + * @param codec3 第三个字段的编解码器 + * @param getter3 从对象取得第三个字段 + * @param codec4 第四个字段的编解码器 + * @param getter4 从对象取得第四个字段 + * @param codec5 第五个字段的编解码器 + * @param getter5 从对象取得第五个字段 + * @param codec6 第六个字段的编解码器 + * @param getter6 从对象取得第六个字段 + * @param codec7 第七个字段的编解码器 + * @param getter7 从对象取得第七个字段 + * @param codec8 第八个字段的编解码器 + * @param getter8 从对象取得第八个字段 + * @param constructor 根据解码出的字段构造对象 + * @return 八字段组合编解码器 + */ + public static StreamCodec composite( + final StreamCodec codec1, + final Function getter1, + final StreamCodec codec2, + final Function getter2, + final StreamCodec codec3, + final Function getter3, + final StreamCodec codec4, + final Function getter4, + final StreamCodec codec5, + final Function getter5, + final StreamCodec codec6, + final Function getter6, + final StreamCodec codec7, + final Function getter7, + final StreamCodec codec8, + final Function getter8, + final Function8 constructor) { + return new StreamCodec<>() { + + @Override + public C decode(B buffer) { + T1 t1 = codec1.decode(buffer); + T2 t2 = codec2.decode(buffer); + T3 t3 = codec3.decode(buffer); + T4 t4 = codec4.decode(buffer); + T5 t5 = codec5.decode(buffer); + T6 t6 = codec6.decode(buffer); + T7 t7 = codec7.decode(buffer); + T8 t8 = codec8.decode(buffer); + return constructor.apply(t1, t2, t3, t4, t5, t6, t7, t8); + } + + @Override + public void encode(B buffer, C object) { + codec1.encode(buffer, getter1.apply(object)); + codec2.encode(buffer, getter2.apply(object)); + codec3.encode(buffer, getter3.apply(object)); + codec4.encode(buffer, getter4.apply(object)); + codec5.encode(buffer, getter5.apply(object)); + codec6.encode(buffer, getter6.apply(object)); + codec7.encode(buffer, getter7.apply(object)); + codec8.encode(buffer, getter8.apply(object)); + } + }; + } + + /** + * 创建包含十二个字段的组合编解码器。 + * 字段按照参数顺序写入和读取,解码后的十二个值按相同顺序传给构造函数。 + * + * @param 字节缓冲区类型 + * @param 编解码对象类型 + * @param 第一个字段类型 + * @param 第二个字段类型 + * @param 第三个字段类型 + * @param 第四个字段类型 + * @param 第五个字段类型 + * @param 第六个字段类型 + * @param 第七个字段类型 + * @param 第八个字段类型 + * @param 第九个字段类型 + * @param 第十个字段类型 + * @param 第十一个字段类型 + * @param 第十二个字段类型 + * @param codec1 第一个字段的编解码器 + * @param getter1 从对象取得第一个字段 + * @param codec2 第二个字段的编解码器 + * @param getter2 从对象取得第二个字段 + * @param codec3 第三个字段的编解码器 + * @param getter3 从对象取得第三个字段 + * @param codec4 第四个字段的编解码器 + * @param getter4 从对象取得第四个字段 + * @param codec5 第五个字段的编解码器 + * @param getter5 从对象取得第五个字段 + * @param codec6 第六个字段的编解码器 + * @param getter6 从对象取得第六个字段 + * @param codec7 第七个字段的编解码器 + * @param getter7 从对象取得第七个字段 + * @param codec8 第八个字段的编解码器 + * @param getter8 从对象取得第八个字段 + * @param codec9 第九个字段的编解码器 + * @param getter9 从对象取得第九个字段 + * @param codec10 第十个字段的编解码器 + * @param getter10 从对象取得第十个字段 + * @param codec11 第十一个字段的编解码器 + * @param getter11 从对象取得第十一个字段 + * @param codec12 第十二个字段的编解码器 + * @param getter12 从对象取得第十二个字段 + * @param constructor 根据解码出的字段构造对象 + * @return 十二字段组合编解码器 + */ + public static StreamCodec composite( + final StreamCodec codec1, + final Function getter1, + final StreamCodec codec2, + final Function getter2, + final StreamCodec codec3, + final Function getter3, + final StreamCodec codec4, + final Function getter4, + final StreamCodec codec5, + final Function getter5, + final StreamCodec codec6, + final Function getter6, + final StreamCodec codec7, + final Function getter7, + final StreamCodec codec8, + final Function getter8, + final StreamCodec codec9, + final Function getter9, + final StreamCodec codec10, + final Function getter10, + final StreamCodec codec11, + final Function getter11, + final StreamCodec codec12, + final Function getter12, + final Function12 constructor) { + return new StreamCodec<>() { + + @Override + public C decode(B buffer) { + T1 t1 = codec1.decode(buffer); + T2 t2 = codec2.decode(buffer); + T3 t3 = codec3.decode(buffer); + T4 t4 = codec4.decode(buffer); + T5 t5 = codec5.decode(buffer); + T6 t6 = codec6.decode(buffer); + T7 t7 = codec7.decode(buffer); + T8 t8 = codec8.decode(buffer); + T9 t9 = codec9.decode(buffer); + T10 t10 = codec10.decode(buffer); + T11 t11 = codec11.decode(buffer); + T12 t12 = codec12.decode(buffer); + return constructor.apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); + } + + @Override + public void encode(B buffer, C object) { + codec1.encode(buffer, getter1.apply(object)); + codec2.encode(buffer, getter2.apply(object)); + codec3.encode(buffer, getter3.apply(object)); + codec4.encode(buffer, getter4.apply(object)); + codec5.encode(buffer, getter5.apply(object)); + codec6.encode(buffer, getter6.apply(object)); + codec7.encode(buffer, getter7.apply(object)); + codec8.encode(buffer, getter8.apply(object)); + codec9.encode(buffer, getter9.apply(object)); + codec10.encode(buffer, getter10.apply(object)); + codec11.encode(buffer, getter11.apply(object)); + codec12.encode(buffer, getter12.apply(object)); + } + }; + } + + /** + * 创建包含十三个字段的组合编解码器。 + * 字段按照参数顺序写入和读取,解码后的十三个值按相同顺序传给构造函数。 + * + * @param 字节缓冲区类型 + * @param 编解码对象类型 + * @param 第一个字段类型 + * @param 第二个字段类型 + * @param 第三个字段类型 + * @param 第四个字段类型 + * @param 第五个字段类型 + * @param 第六个字段类型 + * @param 第七个字段类型 + * @param 第八个字段类型 + * @param 第九个字段类型 + * @param 第十个字段类型 + * @param 第十一个字段类型 + * @param 第十二个字段类型 + * @param 第十三个字段类型 + * @param codec1 第一个字段的编解码器 + * @param getter1 从对象取得第一个字段 + * @param codec2 第二个字段的编解码器 + * @param getter2 从对象取得第二个字段 + * @param codec3 第三个字段的编解码器 + * @param getter3 从对象取得第三个字段 + * @param codec4 第四个字段的编解码器 + * @param getter4 从对象取得第四个字段 + * @param codec5 第五个字段的编解码器 + * @param getter5 从对象取得第五个字段 + * @param codec6 第六个字段的编解码器 + * @param getter6 从对象取得第六个字段 + * @param codec7 第七个字段的编解码器 + * @param getter7 从对象取得第七个字段 + * @param codec8 第八个字段的编解码器 + * @param getter8 从对象取得第八个字段 + * @param codec9 第九个字段的编解码器 + * @param getter9 从对象取得第九个字段 + * @param codec10 第十个字段的编解码器 + * @param getter10 从对象取得第十个字段 + * @param codec11 第十一个字段的编解码器 + * @param getter11 从对象取得第十一个字段 + * @param codec12 第十二个字段的编解码器 + * @param getter12 从对象取得第十二个字段 + * @param codec13 第十三个字段的编解码器 + * @param getter13 从对象取得第十三个字段 + * @param constructor 根据解码出的字段构造对象 + * @return 十三字段组合编解码器 + */ + public static StreamCodec composite( + final StreamCodec codec1, + final Function getter1, + final StreamCodec codec2, + final Function getter2, + final StreamCodec codec3, + final Function getter3, + final StreamCodec codec4, + final Function getter4, + final StreamCodec codec5, + final Function getter5, + final StreamCodec codec6, + final Function getter6, + final StreamCodec codec7, + final Function getter7, + final StreamCodec codec8, + final Function getter8, + final StreamCodec codec9, + final Function getter9, + final StreamCodec codec10, + final Function getter10, + final StreamCodec codec11, + final Function getter11, + final StreamCodec codec12, + final Function getter12, + final StreamCodec codec13, + final Function getter13, + final Function13 constructor) { + return new StreamCodec<>() { + + @Override + public C decode(B buffer) { + T1 t1 = codec1.decode(buffer); + T2 t2 = codec2.decode(buffer); + T3 t3 = codec3.decode(buffer); + T4 t4 = codec4.decode(buffer); + T5 t5 = codec5.decode(buffer); + T6 t6 = codec6.decode(buffer); + T7 t7 = codec7.decode(buffer); + T8 t8 = codec8.decode(buffer); + T9 t9 = codec9.decode(buffer); + T10 t10 = codec10.decode(buffer); + T11 t11 = codec11.decode(buffer); + T12 t12 = codec12.decode(buffer); + T13 t13 = codec13.decode(buffer); + return constructor.apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13); + } + + @Override + public void encode(B buffer, C object) { + codec1.encode(buffer, getter1.apply(object)); + codec2.encode(buffer, getter2.apply(object)); + codec3.encode(buffer, getter3.apply(object)); + codec4.encode(buffer, getter4.apply(object)); + codec5.encode(buffer, getter5.apply(object)); + codec6.encode(buffer, getter6.apply(object)); + codec7.encode(buffer, getter7.apply(object)); + codec8.encode(buffer, getter8.apply(object)); + codec9.encode(buffer, getter9.apply(object)); + codec10.encode(buffer, getter10.apply(object)); + codec11.encode(buffer, getter11.apply(object)); + codec12.encode(buffer, getter12.apply(object)); + codec13.encode(buffer, getter13.apply(object)); + } + }; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/data/TriState.java b/src/main/java/com/modularmc/mmclutils/api/data/TriState.java new file mode 100644 index 0000000..46bfcde --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/data/TriState.java @@ -0,0 +1,111 @@ +package com.modularmc.mmclutils.api.data; + +import net.minecraft.util.StringRepresentable; + +import com.mojang.datafixers.util.Either; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.Lifecycle; +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; + +import java.util.Locale; +import java.util.function.BooleanSupplier; +import java.util.function.Function; + +/** + * 包含真、假和使用默认值的三态布尔值。 + */ +public enum TriState implements StringRepresentable { + + /** + * 真。 + */ + TRUE, + /** + * 使用调用方指定的默认值。 + */ + DEFAULT, + /** + * 假。 + */ + FALSE; + + /** 接受布尔值和枚举名。显式真、假写作布尔值,默认状态写作枚举名。 */ + public static final Codec CODEC = Codec.either(Codec.BOOL, StringRepresentable.fromEnum(TriState::values)) + .xmap(either -> either.map(TriState::of, Function.identity()), + triState -> triState != DEFAULT ? Either.left(triState.isTrue()) : Either.right(DEFAULT)); + + /** 判断是否显式启用。 */ + public boolean isTrue() { + return this == TRUE; + } + + /** 判断是否应交由调用方决定具体布尔值。 */ + public boolean isDefault() { + return this == DEFAULT; + } + + /** 判断是否显式禁用。 */ + public boolean isFalse() { + return this == FALSE; + } + + /** 包装已确定的布尔值。 */ + public static TriState of(boolean value) { + return value ? TRUE : FALSE; + } + + /** 包装可空布尔值,缺失时使用 {@link #DEFAULT}。 */ + public static TriState of(@Nullable Boolean value) { + return value == null ? DEFAULT : of((boolean) value); + } + + /** 读取成功结果中的布尔值。解析错误或缺少值时使用 {@link #DEFAULT}。 */ + public static TriState of(DataResult value) { + if (value.result().isPresent()) return of(value.result().get()); + // 解析失败时采用默认值。 + else return DEFAULT; + } + + /** 将真和假转为装箱布尔值,默认状态返回空值。 */ + public @Nullable Boolean toBoolean() { + return switch (this) { + case TRUE -> Boolean.TRUE; + case FALSE -> Boolean.FALSE; + default -> null; + }; + } + + /** 将真和假转为成功结果,默认状态转为失败结果,供需要确定值的 Codec 使用。 */ + public DataResult toBooleanOrError() { + return switch (this) { + case TRUE -> DataResult.success(Boolean.TRUE); + case FALSE -> DataResult.success(Boolean.FALSE); + default -> DataResult.error(() -> "Default does not have a value", Lifecycle.stable()); + }; + } + + /** 取得显式布尔值,默认状态时使用调用方传入的值。 */ + public boolean toBooleanOrElse(final boolean other) { + return switch (this) { + case TRUE -> true; + case FALSE -> false; + default -> other; + }; + } + + /** 取得显式布尔值,只有默认状态才调用供应器。 */ + public boolean toBooleanOrElseGet(final @NonNull BooleanSupplier supplier) { + return switch (this) { + case TRUE -> true; + case FALSE -> false; + default -> supplier.getAsBoolean(); + }; + } + + @Override + public @NonNull String getSerializedName() { + return this.name().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/Accumulator.java b/src/main/java/com/modularmc/mmclutils/api/function/Accumulator.java new file mode 100644 index 0000000..99af41d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/Accumulator.java @@ -0,0 +1,26 @@ +package com.modularmc.mmclutils.api.function; + +import lombok.Getter; + +import java.util.function.BiFunction; +import java.util.function.Consumer; + +/** 按接收顺序将输入累积到一个值中,可用作顺序流的消费端。 */ +public final class Accumulator implements Consumer { + + private final BiFunction accumulate; + /** 当前累计值,可通过 {@code getValue()} 读取。 */ + @Getter + private T value; + + /** 用初值和结合函数创建累积器。每次接收输入时,将当前值与输入一起交给结合函数。 */ + public Accumulator(T initialValue, BiFunction accumulate) { + this.value = initialValue; + this.accumulate = accumulate; + } + + @Override + public void accept(U input) { + value = accumulate.apply(value, input); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/IntObjectConsumer.java b/src/main/java/com/modularmc/mmclutils/api/function/IntObjectConsumer.java new file mode 100644 index 0000000..e7fe0b1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/IntObjectConsumer.java @@ -0,0 +1,30 @@ +package com.modularmc.mmclutils.api.function; + +import java.util.function.BiConsumer; + +/** + * 接收原始 int 和对象的消费端。可直接用于按索引处理对象的循环,避免装箱。 + * 并发访问与输入是否可空由具体消费端的契约决定。 + */ +@FunctionalInterface +public interface IntObjectConsumer extends BiConsumer { + + /** + * 对两个输入执行消费动作。 + * + * @param t 第一个输入 + * @param u 第二个输入 + */ + void accept(int t, T u); + + /** + * {@inheritDoc} + * + * @deprecated 优先调用原始类型重载 + */ + @Deprecated + @Override + default void accept(Integer integer, T u) { + accept((int) integer, u); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/Memoization.java b/src/main/java/com/modularmc/mmclutils/api/function/Memoization.java new file mode 100644 index 0000000..41c4b8c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/Memoization.java @@ -0,0 +1,225 @@ +package com.modularmc.mmclutils.api.function; + +import com.modularmc.mmclutils.api.collection.cache.ConcurrentWeakIdentityHashMap; + +import com.google.common.base.Suppliers; +import lombok.Getter; +import org.apache.commons.lang3.function.TriFunction; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; +import org.jspecify.annotations.Nullable; + +import java.util.AbstractMap; +import java.util.AbstractSet; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; + +/** 为供应器和一元、多元函数构造按需计算的缓存包装。缓存策略决定参数的比较与保留方式。 */ +public class Memoization { + + /** + * 返回供单线程使用的记忆化 Supplier。并发访问时可使用 Guava 的 {@link Suppliers#memoize memoize}。 + * + * @param delegate 需要记忆化的 Supplier + * @return 记忆化后的 Supplier + */ + public static MemoizedSupplier memoize(Supplier delegate) { + return new MemoizedSupplier<>(delegate); + } + + /** + * 用弱身份键记忆化一元函数。 + * + * @param memoFunction 负责计算结果的函数,返回空值时不缓存该结果 + * @return 按参数对象身份查找且弱持有参数的函数 + */ + public static MemoizedFunction memoizeFunctionWeakIdent(final Function memoFunction) { + return new MemoizedFunction<>() { + + @Getter + private final Map cache = new ConcurrentWeakIdentityHashMap<>(); + + @Override + public R apply(T key) { + return this.cache.computeIfAbsent(key, memoFunction); + } + + @Override + public String toString() { + return "memoizeFunctionWeakIdent/1[function=" + memoFunction + ", size=" + this.cache.size() + "]"; + } + }; + } + + /** + * 用弱身份键记忆化二元函数。两个参数分别以引用身份比较,任一参数被回收后对应的值就不再可访问。 + * 缓存强持有结果,结果若引用参数会延长该参数的生命周期。 + * + * @param 第一个参数类型 + * @param 第二个参数类型 + * @param 结果类型 + * @param memoBiFunction 负责计算结果的函数,返回空值时不缓存该结果 + * @return 按两个参数对象身份查找的记忆化函数 + */ + public static MemoizedBiFunction memoizeFunctionWeakIdent(final BiFunction memoBiFunction) { + return new MemoizedBiFunction<>() { + + private final WeakIdentityPairCache cache = new WeakIdentityPairCache<>(); + + @Override + public Map, R> getCache() { + return cache; + } + + @Override + public R apply(T key1, U key2) { + return cache.computeIfAbsent(key1, key2, () -> memoBiFunction.apply(key1, key2)); + } + + @Override + public String toString() { + return "memoizeFunctionWeakIdent/2[function=" + memoBiFunction + ", size=" + this.cache.size() + "]"; + } + }; + } + + /** + * 用强键记忆化三元函数,参数元组按 {@link Triple} 的值相等性比较。 + * + * @param memoTriFunction 负责计算结果的函数,返回空值时不缓存该结果 + * @return 保留已使用参数元组的记忆化函数 + */ + public static MemoizedTriFunction memoize(final TriFunction memoTriFunction) { + return new MemoizedTriFunction<>() { + + @Getter + private final Map, R> cache = new ConcurrentHashMap<>(); + + @Override + public R apply(T key1, U key2, V key3) { + return this.cache.computeIfAbsent(Triple.of(key1, key2, key3), (cacheKey) -> { + return memoTriFunction.apply(cacheKey.getLeft(), cacheKey.getMiddle(), cacheKey.getRight()); + }); + } + + @Override + public String toString() { + return "memoize/3[function=" + memoTriFunction + ", size=" + this.cache.size() + "]"; + } + }; + } + + /** 通过按层嵌套的弱身份映射,为一对对象提供 Map 视图。 */ + private static final class WeakIdentityPairCache extends AbstractMap, R> { + + private final ConcurrentWeakIdentityHashMap> values = new ConcurrentWeakIdentityHashMap<>(); + + private R computeIfAbsent(T first, U second, Supplier factory) { + ConcurrentWeakIdentityHashMap entries = values.computeIfAbsent(first, ignored -> new ConcurrentWeakIdentityHashMap<>()); + return entries.computeIfAbsent(second, ignored -> factory.get()); + } + + @Override + public boolean containsKey(Object key) { + if (!(key instanceof Pair pair)) return false; + ConcurrentWeakIdentityHashMap entries = values.get(pair.getLeft()); + return entries != null && entries.containsKey(pair.getRight()); + } + + @Override + public R get(Object key) { + if (!(key instanceof Pair pair)) return null; + ConcurrentWeakIdentityHashMap entries = values.get(pair.getLeft()); + return entries == null ? null : entries.get(pair.getRight()); + } + + @Override + public R put(Pair key, R value) { + ConcurrentWeakIdentityHashMap entries = values.computeIfAbsent(key.getLeft(), ignored -> new ConcurrentWeakIdentityHashMap<>()); + return entries.put(key.getRight(), value); + } + + @Override + public R remove(Object key) { + if (!(key instanceof Pair pair)) return null; + ConcurrentWeakIdentityHashMap entries = values.get(pair.getLeft()); + return entries == null ? null : entries.remove(pair.getRight()); + } + + @Override + public int size() { + long size = 0; + for (ConcurrentWeakIdentityHashMap entries : values.values()) size += entries.size(); + return (int) Math.min(size, Integer.MAX_VALUE); + } + + @Override + public void clear() { + values.clear(); + } + + @Override + public Set, R>> entrySet() { + return new AbstractSet<>() { + + @Override + public Iterator, R>> iterator() { + Iterator>> outer = values.entrySet().iterator(); + return new Iterator<>() { + + private T first; + private Iterator> inner = Collections.emptyIterator(); + private @Nullable Pair lastKey; + + @Override + public boolean hasNext() { + while (!inner.hasNext() && outer.hasNext()) { + Map.Entry> entry = outer.next(); + first = entry.getKey(); + inner = entry.getValue().entrySet().iterator(); + } + return inner.hasNext(); + } + + @Override + public Map.Entry, R> next() { + if (!hasNext()) throw new NoSuchElementException(); + Map.Entry current = inner.next(); + Pair key = Pair.of(first, current.getKey()); + lastKey = key; + return new SimpleEntry<>(key, current.getValue()) { + + @Override + public R setValue(R value) { + R previous = WeakIdentityPairCache.this.put(getKey(), value); + super.setValue(value); + return previous; + } + }; + } + + @Override + public void remove() { + if (lastKey == null) throw new IllegalStateException(); + WeakIdentityPairCache.this.remove(lastKey); + lastKey = null; + } + }; + } + + @Override + public int size() { + return WeakIdentityPairCache.this.size(); + } + }; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/MemoizedBiFunction.java b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedBiFunction.java new file mode 100644 index 0000000..e44f92a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedBiFunction.java @@ -0,0 +1,25 @@ +package com.modularmc.mmclutils.api.function; + +import org.apache.commons.lang3.tuple.Pair; + +import java.util.Map; +import java.util.function.BiFunction; + +/** + * 对两个输入参数的函数提供可访问缓存的契约。 + * 参数对按 {@link Pair} 表示,缓存键的比较、引用强弱和线程安全由具体实现决定。 + * + * @param 第一个输入参数类型 + * @param 第二个输入参数类型 + * @param 计算结果类型 + */ +public interface MemoizedBiFunction extends BiFunction { + + /** + * 返回该函数实际使用的结果缓存。 + * 修改或清空此映射会影响后续调用,映射的并发安全由实现决定。 + * + * @return 参数对到计算结果的映射 + */ + Map, R> getCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/MemoizedFunction.java b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedFunction.java new file mode 100644 index 0000000..b9a1051 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedFunction.java @@ -0,0 +1,22 @@ +package com.modularmc.mmclutils.api.function; + +import java.util.Map; +import java.util.function.Function; + +/** + * 对函数结果提供可访问缓存的函数契约。 + * 缓存键的比较、引用强弱和线程安全由具体实现决定。 + * + * @param 输入参数类型 + * @param 计算结果类型 + */ +public interface MemoizedFunction extends Function { + + /** + * 返回该函数实际使用的结果缓存。 + * 修改或清空此映射会影响后续调用,映射的并发安全由实现决定。 + * + * @return 参数到计算结果的映射 + */ + Map getCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/MemoizedSupplier.java b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedSupplier.java new file mode 100644 index 0000000..836c7ea --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedSupplier.java @@ -0,0 +1,45 @@ +package com.modularmc.mmclutils.api.function; + +import java.util.function.Supplier; + +/** + * 首次取值后保留结果的 Supplier,可由调用方使缓存失效并重新计算。 + * 实例和缓存值须由一个线程访问,类本身不提供并发同步。 + * + * @param 供应的值类型 + */ +public class MemoizedSupplier implements Supplier { + + /** 最近一次成功计算得到的值,由 {@link #invalidate()} 清空。 */ + protected T value = null; + /** 记录委托是否已成功计算,允许把空值作为计算结果缓存。 */ + protected boolean initialized = false; + /** 缓存尚未建立时调用的供应器。 */ + protected final Supplier delegate; + + /** 包装延迟执行的委托。调用 {@link #get()} 前不会运行委托。 */ + protected MemoizedSupplier(Supplier delegate) { + this.delegate = delegate; + } + + /** 计算并返回缓存值,首次调用时委托给原始 Supplier。 */ + @Override + public T get() { + if (!initialized) { + value = delegate.get(); + initialized = true; + } + return value; + } + + /** 丢弃已有值,使下次 {@link #get()} 重新调用原始 Supplier。 */ + public void invalidate() { + initialized = false; + value = null; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(" + (initialized ? value : "Uninitialized") + ")"; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/MemoizedTriFunction.java b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedTriFunction.java new file mode 100644 index 0000000..1eb3d23 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/MemoizedTriFunction.java @@ -0,0 +1,26 @@ +package com.modularmc.mmclutils.api.function; + +import org.apache.commons.lang3.function.TriFunction; +import org.apache.commons.lang3.tuple.Triple; + +import java.util.Map; + +/** + * 对三个输入参数的函数提供可访问缓存的契约。 + * 参数组三元组按 {@link Triple} 表示,缓存键的比较、引用强弱和线程安全由具体实现决定。 + * + * @param 第一个输入参数类型 + * @param 第二个输入参数类型 + * @param 第三个输入参数类型 + * @param 计算结果类型 + */ +public interface MemoizedTriFunction extends TriFunction { + + /** + * 返回该函数实际使用的结果缓存。 + * 修改或清空此映射会影响后续调用,映射的并发安全由实现决定。 + * + * @return 参数三元组到计算结果的映射 + */ + Map, R> getCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/function/TriConsumer.java b/src/main/java/com/modularmc/mmclutils/api/function/TriConsumer.java new file mode 100644 index 0000000..5f70e7c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/function/TriConsumer.java @@ -0,0 +1,9 @@ +package com.modularmc.mmclutils.api.function; + +/** 接收三个参数的操作接口,用于避免在迭代中分配临时元组。 */ +@FunctionalInterface +public interface TriConsumer { + + /** 按声明顺序接收三个输入。空值约束和副作用由调用此接口的 API 定义。 */ + void accept(A a, B b, C c); +} diff --git a/src/main/java/com/modularmc/mmclutils/api/input/SyncedKeyMappings.java b/src/main/java/com/modularmc/mmclutils/api/input/SyncedKeyMappings.java new file mode 100644 index 0000000..9b12b07 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/input/SyncedKeyMappings.java @@ -0,0 +1,207 @@ +package com.modularmc.mmclutils.api.input; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; + +import io.netty.handler.codec.DecoderException; +import it.unimi.dsi.fastutil.objects.Object2BooleanLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2BooleanMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; +import org.jetbrains.annotations.ApiStatus; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +/** 使用共同的标识声明同步按键,按服务端玩家维护按下状态。 */ +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) +public final class SyncedKeyMappings { + + private static final ConcurrentHashMap KEYS = new ConcurrentHashMap<>(); + + private SyncedKeyMappings() {} + + /** 在模组初始化时于两端声明一次。标识应使用调用方的命名空间,重复声明会抛出异常。 */ + public static Key define(Identifier id) { + var key = new Key(id); + if (KEYS.putIfAbsent(id, key) != null) throw new IllegalArgumentException("同步按键已经声明 " + id); + return key; + } + + /** 将按键状态载荷登记到模组总线。 */ + @ApiStatus.Internal + public static void init(IEventBus modBus) { + modBus.addListener(SyncedKeyMappings::initPayload); + } + + private static void initPayload(RegisterPayloadHandlersEvent event) { + event.registrar("1").optional().playToServer(ChangeSet.TYPE, ChangeSet.CODEC, + (payload, context) -> apply((ServerPlayer) context.player(), payload.changes)); + } + + private static void apply(ServerPlayer player, Object2BooleanMap changes) { + var accepted = new Object2BooleanLinkedOpenHashMap(); + for (var change : changes.object2BooleanEntrySet()) { + Key key = KEYS.get(change.getKey()); + if (key == null) continue; + boolean pressed = change.getBooleanValue(); + if (key.setPressed(player, pressed)) accepted.put(key, pressed); + } + for (var change : accepted.object2BooleanEntrySet()) { + change.getKey().notifyListeners(player, change.getBooleanValue()); + } + } + + @SubscribeEvent + private static void clearOnLogout(PlayerEvent.PlayerLoggedOutEvent event) { + release((ServerPlayer) event.getEntity()); + } + + @SubscribeEvent + private static void clearReplacedPlayer(PlayerEvent.Clone event) { + if (event.getOriginal() instanceof ServerPlayer player) release(player); + } + + @SubscribeEvent + private static void clearStoppedServer(ServerStoppedEvent event) { + MinecraftServer server = event.getServer(); + for (Key key : KEYS.values()) { + key.pressed.removeIf(player -> player.level().getServer() == server); + key.playerListeners.keySet().removeIf(player -> player.level().getServer() == server); + } + } + + private static void release(ServerPlayer player) { + var released = new ReferenceOpenHashSet(); + for (Key key : KEYS.values()) { + if (key.setPressed(player, false)) released.add(key); + } + try { + for (Key key : released) key.notifyListeners(player, false); + } finally { + for (Key key : KEYS.values()) key.playerListeners.remove(player); + } + } + + /** 一个可被客户端绑定并由服务端读取的按键。状态和玩家监听仅在服务端线程访问。 */ + public static final class Key { + + private final Identifier id; + private final ReferenceOpenHashSet pressed = new ReferenceOpenHashSet<>(); + private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); + private final Reference2ObjectOpenHashMap> playerListeners = new Reference2ObjectOpenHashMap<>(); + + private Key(Identifier id) { + this.id = id; + } + + /** 返回两端共享的按键标识。 */ + public Identifier id() { + return id; + } + + /** 返回玩家最近同步的状态,可用于界面或操作选择。游戏条件仍由服务端判断。 */ + public boolean isDown(ServerPlayer player) { + return pressed.contains(player); + } + + /** 在服务端登记本键的全局状态监听,同一监听只登记一次。 */ + public void addListener(Listener listener) { + listeners.addIfAbsent(listener); + } + + /** 移除全局状态监听。 */ + public void removeListener(Listener listener) { + listeners.remove(listener); + } + + /** 添加只接收此玩家状态变化的监听。玩家退出或被替换时清理。 */ + public void addListener(ServerPlayer player, Listener listener) { + playerListeners.computeIfAbsent(player, ignored -> new CopyOnWriteArrayList<>()).addIfAbsent(listener); + } + + /** 移除指定玩家的状态监听,不影响此键的其他监听。 */ + public void removeListener(ServerPlayer player, Listener listener) { + var current = playerListeners.get(player); + if (current != null && current.remove(listener) && current.isEmpty()) playerListeners.remove(player); + } + + private boolean setPressed(ServerPlayer player, boolean down) { + return down ? pressed.add(player) : pressed.remove(player); + } + + private void notifyListeners(ServerPlayer player, boolean down) { + for (Listener listener : listeners) listener.changed(player, this, down); + var current = playerListeners.get(player); + if (current != null) { + for (Listener listener : current) listener.changed(player, this, down); + } + } + } + + /** 在服务端线程接收状态边沿,可在回调中查询同一批更新的其他按键。 */ + @FunctionalInterface + public interface Listener { + + /** + * 在状态已更新时收到通知。退出时仍处于按下状态的键会发出释放通知。 + * + * @param player 状态变化的服务端玩家 + * @param key 该玩家操作的按键 + * @param down 新状态,真为按下 + */ + void changed(ServerPlayer player, Key key, boolean down); + } + + /** + * 通过 NeoForge 传输一批本地按键状态变化。 + * + * @param changes 已登记按键的标识及其按下状态 + */ + @ApiStatus.Internal + public record ChangeSet(Object2BooleanMap changes) implements CustomPacketPayload { + + /** 单个载荷允许的最大变化条目数。 */ + public static final int MAX_CHANGES = 64; + /** 登记在连接上的载荷类型。 */ + public static final Type TYPE = new Type<>(ModularMCLibUtils.id("key_state")); + private static final StreamCodec CODEC = StreamCodec.of(ChangeSet::write, ChangeSet::read); + + private static ChangeSet read(FriendlyByteBuf buffer) { + int count = buffer.readVarInt(); + if (count < 1 || count > MAX_CHANGES) throw new DecoderException("同步按键数量超出范围 " + count); + var changes = new Object2BooleanLinkedOpenHashMap(count); + for (int i = 0; i < count; i++) { + Identifier id = Identifier.STREAM_CODEC.decode(buffer); + if (changes.containsKey(id)) throw new DecoderException("同步按键标识重复 " + id); + changes.put(id, buffer.readBoolean()); + } + return new ChangeSet(changes); + } + + private static void write(FriendlyByteBuf buffer, ChangeSet state) { + buffer.writeVarInt(state.changes.size()); + for (var change : state.changes.object2BooleanEntrySet()) { + Identifier.STREAM_CODEC.encode(buffer, change.getKey()); + buffer.writeBoolean(change.getBooleanValue()); + } + } + + @Override + public Type type() { + return TYPE; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/inventory/FluidStackStrategy.java b/src/main/java/com/modularmc/mmclutils/api/inventory/FluidStackStrategy.java new file mode 100644 index 0000000..4b64089 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/inventory/FluidStackStrategy.java @@ -0,0 +1,116 @@ +package com.modularmc.mmclutils.api.inventory; + +import net.neoforged.neoforge.fluids.FluidStack; + +import it.unimi.dsi.fastutil.Hash; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; + +/** + * 按流体、数量和数据组件配置流体栈的哈希与相等策略。 + * 用作哈希键期间,应保持参与比较的字段稳定。 + */ +public interface FluidStackStrategy extends Hash.Strategy { + + /** + * 选择参与散列和比较的栈字段。 + * + * @return 可组合比较字段的构建器 + */ + static FluidStackStrategy.FluidStackHashStrategyBuilder builder() { + return new FluidStackStrategy.FluidStackHashStrategyBuilder(); + } + + /** + * 对流体、数量和组件都进行比较。 + * + * @return 全字段比较策略 + */ + static FluidStackStrategy comparingAll() { + return builder().compareFluid(true) + .compareCount(true) + .compareComponents(true) + .build(); + } + + /** + * 仅比较流体和数据组件。 + * + * @return 忽略数量的比较策略 + */ + static FluidStackStrategy comparingAllButAmount() { + return builder().compareFluid(true) + .compareComponents(true) + .build(); + } + + /** + * 配置流体栈策略的比较字段。 + */ + class FluidStackHashStrategyBuilder { + + private boolean fluid, amount, components; + + /** + * 选择是否比较流体类型。 + * + * @param choice 是否参与比较 + * @return 当前构建器 + */ + public FluidStackStrategy.FluidStackHashStrategyBuilder compareFluid(boolean choice) { + fluid = choice; + return this; + } + + /** + * 选择是否比较流体量。 + * + * @param choice 是否参与比较 + * @return 当前构建器 + */ + public FluidStackStrategy.FluidStackHashStrategyBuilder compareCount(boolean choice) { + amount = choice; + return this; + } + + /** + * 选择是否比较数据组件。 + * + * @param choice 是否参与比较 + * @return 当前构建器 + */ + public FluidStackStrategy.FluidStackHashStrategyBuilder compareComponents(boolean choice) { + components = choice; + return this; + } + + /** + * 生成一个由已选择字段定义的策略。用于容器后保持构建器的字段选择稳定。 + * + * @return 按当前比较字段生成的流体栈策略 + */ + public FluidStackStrategy build() { + return new FluidStackStrategy() { + + @Override + public int hashCode(@Nullable FluidStack o) { + return o == null || o.isEmpty() ? 0 : Objects.hash( + fluid ? o.getFluid() : null, + amount ? o.getAmount() : null, + components ? o.getComponents() : null); + } + + @Override + public boolean equals(@Nullable FluidStack a, @Nullable FluidStack b) { + if (a == null || a.isEmpty()) return b == null || b.isEmpty(); + if (b == null || b.isEmpty()) return false; + + return (!fluid || a.getFluid() == b.getFluid()) && + (!amount || a.getAmount() == b.getAmount()) && + (!components || Objects.equals(a.getComponents(), b.getComponents())); + } + }; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/inventory/ItemStackStrategy.java b/src/main/java/com/modularmc/mmclutils/api/inventory/ItemStackStrategy.java new file mode 100644 index 0000000..45c2cef --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/inventory/ItemStackStrategy.java @@ -0,0 +1,125 @@ +package com.modularmc.mmclutils.api.inventory; + +import net.minecraft.world.item.ItemStack; + +import it.unimi.dsi.fastutil.Hash; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; + +/** + * 按物品、数量和数据组件配置物品栈的哈希与相等策略。 + * 用作哈希键期间,应保持参与比较的字段稳定。 + */ +public interface ItemStackStrategy extends Hash.Strategy { + + /** + * 选择参与散列和比较的栈字段。 + * + * @return 可组合比较字段的构建器 + */ + static ItemStackHashStrategyBuilder builder() { + return new ItemStackHashStrategyBuilder(); + } + + /** + * 对物品、数量和组件都进行比较。 + * + * @return 全字段比较策略 + */ + static ItemStackStrategy comparingAll() { + return ItemStackHashStrategyBuilder.ALL; + } + + /** + * 仅比较物品和数据组件。 + * + * @return 忽略数量的比较策略 + */ + static ItemStackStrategy comparingAllButCount() { + return ItemStackHashStrategyBuilder.ITEM_AND_TAG; + } + + /** 只按注册的物品比较,忽略堆叠大小和数据组件。 */ + static ItemStackStrategy comparingItem() { + return ItemStackHashStrategyBuilder.ITEM; + } + + /** + * 配置物品栈策略的比较字段。 + */ + class ItemStackHashStrategyBuilder { + + private static final ItemStackStrategy ALL = builder().compareItem(true) + .compareCount(true) + .compareComponents(true) + .build(); + private static final ItemStackStrategy ITEM_AND_TAG = builder().compareItem(true) + .compareComponents(true) + .build(); + private static final ItemStackStrategy ITEM = builder().compareItem(true).build(); + + private boolean item, count, components; + + /** + * 选择是否比较物品类型。 + * + * @param choice 是否参与比较 + * @return 当前构建器 + */ + public ItemStackHashStrategyBuilder compareItem(boolean choice) { + item = choice; + return this; + } + + /** + * 选择是否比较堆叠数量。 + * + * @param choice 是否参与比较 + * @return 当前构建器 + */ + public ItemStackHashStrategyBuilder compareCount(boolean choice) { + count = choice; + return this; + } + + /** + * 选择是否比较数据组件。 + * + * @param choice 是否参与比较 + * @return 当前构建器 + */ + public ItemStackHashStrategyBuilder compareComponents(boolean choice) { + components = choice; + return this; + } + + /** + * 生成一个由已选择字段定义的策略。用于容器后保持构建器的字段选择稳定。 + * + * @return 按当前比较字段生成的物品栈策略 + */ + public ItemStackStrategy build() { + return new ItemStackStrategy() { + + @Override + public int hashCode(@Nullable ItemStack o) { + return o == null || o.isEmpty() ? 0 : Objects.hash( + item ? o.getItem() : null, + count ? o.getCount() : null, + components ? o.getComponents() : null); + } + + @Override + public boolean equals(@Nullable ItemStack a, @Nullable ItemStack b) { + if (a == null || a.isEmpty()) return b == null || b.isEmpty(); + if (b == null || b.isEmpty()) return false; + + return (!item || a.getItem() == b.getItem()) && + (!count || a.getCount() == b.getCount()) && + (!components || Objects.equals(a.getComponents(), b.getComponents())); + } + }; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/inventory/ResourceTransferSimulation.java b/src/main/java/com/modularmc/mmclutils/api/inventory/ResourceTransferSimulation.java new file mode 100644 index 0000000..2e901da --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/inventory/ResourceTransferSimulation.java @@ -0,0 +1,99 @@ +package com.modularmc.mmclutils.api.inventory; + +import net.neoforged.neoforge.transfer.ResourceHandler; +import net.neoforged.neoforge.transfer.resource.Resource; +import net.neoforged.neoforge.transfer.transaction.Transaction; +import net.neoforged.neoforge.transfer.transaction.TransactionContext; + +import org.jspecify.annotations.Nullable; + +/** + * 在所属线程中仿真连续插入和提取,复用存储自身的规则。 + * 在关闭或重置前,同一线程通过原始存储能看到仿真中的数量。使用 try-with-resources 限定作用范围。 + * + * @param 存储的资源类型 + */ +public final class ResourceTransferSimulation implements AutoCloseable { + + private final ResourceHandler storage; + private final @Nullable TransactionContext parent; + private @Nullable Transaction transaction; + + /** 在独立的事务中打开仿真,仿真结束时回滚。 */ + public ResourceTransferSimulation(ResourceHandler storage) { + this(storage, null); + } + + /** 在指定外层事务的当前状态上开始仿真。外层为空时使用独立事务。 */ + public ResourceTransferSimulation(ResourceHandler storage, @Nullable TransactionContext parent) { + this.storage = storage; + this.parent = parent; + transaction = Transaction.open(parent); + } + + /** 返回存储的槽位数。 */ + public int size() { + return storage.size(); + } + + /** 查询指定槽位当前的资源,空槽由存储返回空资源。 */ + public R resource(int index) { + return storage.getResource(index); + } + + /** 返回指定槽位的当前数量,包含本轮仿真的改动。 */ + public long amount(int index) { + return storage.getAmountAsLong(index); + } + + /** + * 查询指定资源在此槽位的容量。该值由存储提供,可用于估算,实际插入仍由事务验证。 + * + * @param index 槽位索引 + * @param resource 待查询的资源,空资源查询槽位通用容量 + * @return 槽位容量 + */ + public long capacity(int index, R resource) { + return storage.getCapacityAsLong(index, resource); + } + + /** 按存储的插入顺序尝试插入,返回成功量。 */ + public int insert(R resource, int amount) { + return storage.insert(resource, amount, active()); + } + + /** 尝试向指定槽位插入非空资源,并返回本轮实际接受的数量。 */ + public int insert(int index, R resource, int amount) { + return storage.insert(index, resource, amount, active()); + } + + /** 按存储的提取顺序提取指定资源,并返回本轮实际提取的数量。 */ + public int extract(R resource, int amount) { + return storage.extract(resource, amount, active()); + } + + /** 从指定槽位提取资源,并返回本轮实际提取的数量。 */ + public int extract(int index, R resource, int amount) { + return storage.extract(index, resource, amount, active()); + } + + /** 回滚仿真中的所有改动,开启新一轮。 */ + public void reset() { + active().close(); + transaction = Transaction.open(parent); + } + + private Transaction active() { + if (transaction == null) throw new IllegalStateException("转移仿真已关闭"); + return transaction; + } + + /** 关闭事务,恢复仿真开始前的存储状态。 */ + @Override + public void close() { + if (transaction != null) { + transaction.close(); + transaction = null; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/AreaBlockActions.java b/src/main/java/com/modularmc/mmclutils/api/level/AreaBlockActions.java new file mode 100644 index 0000000..1bd0d5e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/AreaBlockActions.java @@ -0,0 +1,137 @@ +package com.modularmc.mmclutils.api.level; + +import com.modularmc.mmclutils.api.schedule.Cadence; +import com.modularmc.mmclutils.api.schedule.Schedulers; +import com.modularmc.mmclutils.api.schedule.Task; + +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.LevelChunk; + +import it.unimi.dsi.fastutil.longs.LongIterator; + +import java.util.function.LongPredicate; + +/** 在服务器线程操作已加载区域。通过回调决定方块操作及其原版更新规则。 */ +public final class AreaBlockActions { + + private AreaBlockActions() {} + + /** 在服务端线程访问两个方块位置构成的闭合立方体。返回回调报告成功的次数。 */ + public static long box(ServerLevel level, BlockPos first, BlockPos second, Action action) { + return visit(level, Math.min(first.getX(), second.getX()), Math.min(first.getY(), second.getY()), Math.min(first.getZ(), second.getZ()), + Math.max(first.getX(), second.getX()), Math.max(first.getY(), second.getY()), Math.max(first.getZ(), second.getZ()), pos -> true, action); + } + + /** 两角按区块坐标传入,覆盖其间所有区块的完整高度。 */ + public static long chunks(ServerLevel level, int firstX, int firstZ, int secondX, int secondZ, Action action) { + return visit(level, Math.multiplyExact(Math.min(firstX, secondX), 16), level.getMinY(), Math.multiplyExact(Math.min(firstZ, secondZ), 16), + Math.multiplyExact(Math.max(firstX, secondX), 16) + 15, level.getMaxY(), Math.multiplyExact(Math.max(firstZ, secondZ), 16) + 15, pos -> true, action); + } + + /** 按水平方向的圆形距离筛选指定高度区间的方块。负半径将被拒绝。 */ + public static long cylinder(ServerLevel level, BlockPos center, int radius, int minY, int maxY, Action action) { + if (radius < 0) throw new IllegalArgumentException("圆柱半径不能为负数"); + long radiusSquared = (long) radius * radius; + return visit(level, Math.subtractExact(center.getX(), radius), minY, Math.subtractExact(center.getZ(), radius), + Math.addExact(center.getX(), radius), maxY, Math.addExact(center.getZ(), radius), pos -> { + long dx = (long) BlockPos.getX(pos) - center.getX(); + long dz = (long) BlockPos.getZ(pos) - center.getZ(); + return dz * dz <= radiusSquared - dx * dx; + }, action); + } + + /** 访问到中心的欧氏距离不超过给定半径的格点。仅处理仍处于加载状态的方块。 */ + public static long sphere(ServerLevel level, BlockPos center, int radius, Action action) { + if (radius < 0) throw new IllegalArgumentException("球形半径不能为负数"); + long radiusSquared = (long) radius * radius; + return visit(level, Math.subtractExact(center.getX(), radius), Math.subtractExact(center.getY(), radius), Math.subtractExact(center.getZ(), radius), + Math.addExact(center.getX(), radius), Math.addExact(center.getY(), radius), Math.addExact(center.getZ(), radius), pos -> { + long dx = (long) BlockPos.getX(pos) - center.getX(); + long dy = (long) BlockPos.getY(pos) - center.getY(); + long dz = (long) BlockPos.getZ(pos) - center.getZ(); + return dz * dz <= radiusSquared - dx * dx - dy * dy; + }, action); + } + + /** 先完成连通搜索,再按发现顺序修改,避免操作改变本次搜索结果。 */ + public static long connected(ServerLevel level, BlockPos start, BlockSearch.EdgeFilter filter, + int resultLimit, int visitLimit, Action action) { + checkThread(level); + var positions = BlockSearch.conditionalPacked(start.asLong(), + (parent, pos, root) -> !level.isOutsideBuildHeight(BlockPos.getY(pos)) && LoadedChunks.chunk(level, BlockPos.getX(pos) >> 4, BlockPos.getZ(pos) >> 4) != null && filter.accept(parent, pos, root), resultLimit, visitLimit); + return apply(level, positions.iterator(), action); + } + + /** 从当前位置消耗打包方块坐标迭代器,跳过未加载或超出高度范围的位置。返回成功操作数。 */ + public static long apply(ServerLevel level, LongIterator positions, Action action) { + checkThread(level); + long count = 0; + var cursor = new BlockPos.MutableBlockPos(); + while (positions.hasNext()) { + if (applyAt(level, positions.nextLong(), cursor, action)) count++; + } + return count; + } + + /** 每轮最多消耗 limit 个位置。序列归任务独占,维度关闭时调度器回收任务。 */ + public static Task schedule(ServerLevel level, LongIterator positions, int limit, Action action) { + checkThread(level); + if (limit < 1) throw new IllegalArgumentException("每 Tick 的位置上限必须为正数"); + var cursor = new BlockPos.MutableBlockPos(); + return Schedulers.of(level).repeat(Cadence.every(1), positions, iterator -> { + for (int index = 0; index < limit && iterator.hasNext(); index++) { + applyAt(level, iterator.nextLong(), cursor, action); + } + }, iterator -> !iterator.hasNext()); + } + + private static long visit(ServerLevel level, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, + LongPredicate contains, Action action) { + checkThread(level); + minY = Math.max(minY, level.getMinY()); + maxY = Math.min(maxY, level.getMaxY()); + if (minY > maxY) return 0; + if (BlockPos.getX(BlockPos.asLong(minX, 0, 0)) != minX || BlockPos.getX(BlockPos.asLong(maxX, 0, 0)) != maxX || BlockPos.getZ(BlockPos.asLong(0, 0, minZ)) != minZ || BlockPos.getZ(BlockPos.asLong(0, 0, maxZ)) != maxZ) { + throw new IllegalArgumentException("区域超出可编码的方块坐标"); + } + long count = 0; + var cursor = new BlockPos.MutableBlockPos(); + for (int chunkZ = minZ >> 4; chunkZ <= maxZ >> 4; chunkZ++) { + for (int chunkX = minX >> 4; chunkX <= maxX >> 4; chunkX++) { + LevelChunk chunk = LoadedChunks.chunk(level, chunkX, chunkZ); + if (chunk == null) continue; + int x0 = Math.max(minX, chunkX << 4), x1 = Math.min(maxX, (chunkX << 4) + 15); + int z0 = Math.max(minZ, chunkZ << 4), z1 = Math.min(maxZ, (chunkZ << 4) + 15); + for (int y = minY; y <= maxY; y++) { + for (int z = z0; z <= z1; z++) { + for (int x = x0; x <= x1; x++) { + if (contains.test(BlockPos.asLong(x, y, z)) && action.apply(level, cursor.set(x, y, z), chunk.getBlockState(cursor))) count++; + } + } + } + } + } + return count; + } + + private static boolean applyAt(ServerLevel level, long position, BlockPos.MutableBlockPos cursor, Action action) { + cursor.set(BlockPos.getX(position), BlockPos.getY(position), BlockPos.getZ(position)); + if (level.isOutsideBuildHeight(cursor.getY())) return false; + LevelChunk chunk = LoadedChunks.chunk(level, cursor); + return chunk != null && action.apply(level, cursor, chunk.getBlockState(cursor)); + } + + private static void checkThread(ServerLevel level) { + if (!level.getServer().isSameThread()) throw new IllegalStateException("区域方块操作须在服务器线程运行"); + } + + /** 操作单个已加载方块。回调在服务器线程运行,坐标在返回后会被复用。 */ + @FunctionalInterface + public interface Action { + + /** 返回真计入成功数。异常由调用方或所属调度器处理。 */ + boolean apply(ServerLevel level, BlockPos position, BlockState state); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/BlockIndex.java b/src/main/java/com/modularmc/mmclutils/api/level/BlockIndex.java new file mode 100644 index 0000000..9d2f645 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/BlockIndex.java @@ -0,0 +1,295 @@ +package com.modularmc.mmclutils.api.level; + +import net.minecraft.core.BlockPos; + +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * 一个维度内按方块坐标登记对象的索引:世界按 256³ 的区域分片放进哈希表,每个区域一棵 {@link BlockOctree}, + * 查询只访问与范围相交的区域,树深 8 层而不是覆盖全世界的 26 层。功能: + *
    + *
  • {@link #put}:登记,同一坐标已有对象时替换;世界范围外的坐标不登记并返回 false
  • + *
  • {@link #remove(int, int, int)}:按坐标注销;{@link #remove(int, int, int, Object)}:只有该坐标登记的正是这个对象时才注销, + * 防止方块替换或区块重载时旧对象把新对象注销掉;区域清空后释放
  • + *
  • {@link #get}/{@link #query}/{@link #findAny}/{@link #findNearest}/{@link #forEach}:按坐标、按 + * {@link BlockRange}(球形或长方体)或对全部条目查询, + * 跨区域的结果与单棵树完全一致,最近查询的并列规则同 {@link BlockOctree#findNearest(int, int, int, BlockRange, Predicate)}
  • + *
  • {@link #version()}:每次登记内容变化加一,使用方据此判断自己缓存的查询结果是否过期
  • + *
  • 不是线程安全的,只在拥有该维度的线程上使用
  • + *
+ * + * @param 与方块坐标关联的非空对象类型 + */ +public final class BlockIndex { + + /** 原版方块坐标编码支持的最小 X、Z 坐标。 */ + public static final int MIN_XZ = -(1 << 25); + /** 原版方块坐标编码支持的最大 X、Z 坐标。 */ + public static final int MAX_XZ = (1 << 25) - 1; + /** 原版方块坐标编码支持的最小 Y 坐标。 */ + public static final int MIN_Y = -2048; + /** 原版方块坐标编码支持的最大 Y 坐标。 */ + public static final int MAX_Y = 2047; + + static final int REGION_SHIFT = 8; + static final int REGION_SIZE = 1 << REGION_SHIFT; + + private final Long2ObjectOpenHashMap> regions = new Long2ObjectOpenHashMap<>(); + private final ArrayList> scratch = new ArrayList<>(); + private int depth; + private int size; + private int version; + + private static long regionKey(int rx, int ry, int rz) { + return ((long) (rx + (1 << 17)) << 26) | ((long) (rz + (1 << 17)) << 8) | (ry + 128); + } + + private BlockOctree region(int x, int y, int z) { + return regions.get(regionKey(x >> REGION_SHIFT, y >> REGION_SHIFT, z >> REGION_SHIFT)); + } + + /** 检查坐标能否表示为原版打包方块位置。 */ + public boolean inBounds(int x, int y, int z) { + return x >= MIN_XZ && x <= MAX_XZ && z >= MIN_XZ && z <= MAX_XZ && y >= MIN_Y && y <= MAX_Y; + } + + /** 将非空值关联到方块坐标,已有值时替换。坐标超出打包范围时返回 {@code false}。 */ + public boolean put(int x, int y, int z, T value) { + if (!inBounds(x, y, z)) return false; + int rx = x >> REGION_SHIFT, ry = y >> REGION_SHIFT, rz = z >> REGION_SHIFT; + long key = regionKey(rx, ry, rz); + BlockOctree tree = regions.get(key); + if (tree == null) { + int ox = rx << REGION_SHIFT, oy = ry << REGION_SHIFT, oz = rz << REGION_SHIFT; + tree = new BlockOctree<>(ox, oy, oz, ox + REGION_SIZE - 1, oy + REGION_SIZE - 1, oz + REGION_SIZE - 1); + regions.put(key, tree); + } + T old = tree.get(x, y, z); + if (old == value) return true; + if (old != null) tree.remove(x, y, z); + else size++; + tree.insert(x, y, z, value); + version++; + return true; + } + + /** 使用原版位置对象写入索引。索引只提取坐标,不持有传入对象。 */ + public boolean put(BlockPos pos, T value) { + return put(pos.getX(), pos.getY(), pos.getZ(), value); + } + + /** 按坐标移除并返回旧值,未命中时返回空值。清空的区域从索引中移除。 */ + public T remove(int x, int y, int z) { + if (!inBounds(x, y, z)) return null; + long key = regionKey(x >> REGION_SHIFT, y >> REGION_SHIFT, z >> REGION_SHIFT); + BlockOctree tree = regions.get(key); + if (tree == null) return null; + T removed = tree.remove(x, y, z); + if (removed == null) return null; + size--; + version++; + if (tree.isEmpty()) regions.remove(key); + return removed; + } + + /** 按照方块位置移除值,位置未登记时返回空值。 */ + public T remove(BlockPos pos) { + return remove(pos.getX(), pos.getY(), pos.getZ()); + } + + /** 只有当前值与预期对象为同一引用时才删除。可用于避免迟到的清理操作删除新对象。 */ + public boolean remove(int x, int y, int z, T expected) { + if (expected == null || get(x, y, z) != expected) return false; + remove(x, y, z); + return true; + } + + /** 按位置和预期引用移除,替换后保留当前位置上的新值。 */ + public boolean remove(BlockPos pos, T expected) { + return remove(pos.getX(), pos.getY(), pos.getZ(), expected); + } + + /** 按整数坐标读取对应值。未登记或越界时返回空值。 */ + public T get(int x, int y, int z) { + if (!inBounds(x, y, z)) return null; + BlockOctree tree = region(x, y, z); + return tree == null ? null : tree.get(x, y, z); + } + + /** 按方块位置读取对应值。未登记或越界时返回空值。 */ + public T get(BlockPos pos) { + return get(pos.getX(), pos.getY(), pos.getZ()); + } + + private List> regionsIn(int x, int y, int z, BlockRange range) { + List> out = depth == 0 ? scratch : new ArrayList<>(); + out.clear(); + if (range.isEmpty() || size == 0) return out; + long minX = Math.max((long) x - range.radiusX(), MIN_XZ), maxX = Math.min((long) x + range.radiusX(), MAX_XZ); + long minY = Math.max((long) y - range.radiusY(), MIN_Y), maxY = Math.min((long) y + range.radiusY(), MAX_Y); + long minZ = Math.max((long) z - range.radiusZ(), MIN_XZ), maxZ = Math.min((long) z + range.radiusZ(), MAX_XZ); + if (minX > maxX || minY > maxY || minZ > maxZ) return out; + int rx0 = (int) minX >> REGION_SHIFT, rx1 = (int) maxX >> REGION_SHIFT; + int ry0 = (int) minY >> REGION_SHIFT, ry1 = (int) maxY >> REGION_SHIFT; + int rz0 = (int) minZ >> REGION_SHIFT, rz1 = (int) maxZ >> REGION_SHIFT; + long cells = (long) (rx1 - rx0 + 1) * (ry1 - ry0 + 1) * (rz1 - rz0 + 1); + if (cells > regions.size()) { + for (Long2ObjectMap.Entry> e : regions.long2ObjectEntrySet()) { + long k = e.getLongKey(); + int ry = (int) (k & 0xFF) - 128; + int rz = (int) ((k >>> 8) & 0x3FFFF) - (1 << 17); + int rx = (int) (k >>> 26) - (1 << 17); + if (rx >= rx0 && rx <= rx1 && ry >= ry0 && ry <= ry1 && rz >= rz0 && rz <= rz1) out.add(e.getValue()); + } + return out; + } + for (int rx = rx0; rx <= rx1; rx++) { + for (int rz = rz0; rz <= rz1; rz++) { + for (int ry = ry0; ry <= ry1; ry++) { + BlockOctree tree = regions.get(regionKey(rx, ry, rz)); + if (tree != null) out.add(tree); + } + } + } + return out; + } + + /** 将范围内通过筛选的值依次交给消费端。允许省略筛选,回调中不要修改索引。 */ + public void query(int x, int y, int z, BlockRange range, Predicate filter, Consumer sink) { + List> trees = regionsIn(x, y, z, range); + depth++; + try { + for (int i = 0, n = trees.size(); i < n; i++) trees.get(i).query(x, y, z, range, filter, sink); + } finally { + depth--; + } + } + + /** 将匹配值放入给定集合,返回集合实际增加的元素数。 */ + public int query(int x, int y, int z, BlockRange range, Predicate filter, Collection out) { + int before = out.size(); + List> trees = regionsIn(x, y, z, range); + depth++; + try { + for (int i = 0, n = trees.size(); i < n; i++) trees.get(i).query(x, y, z, range, filter, out); + } finally { + depth--; + } + return out.size() - before; + } + + /** 以方块位置为中心收集匹配值,返回集合实际增加的元素数。 */ + public int query(BlockPos center, BlockRange range, Predicate filter, Collection out) { + return query(center.getX(), center.getY(), center.getZ(), range, filter, out); + } + + /** 找到任意一个范围内的匹配值就提前结束。未命中时返回空值。 */ + public T findAny(int x, int y, int z, BlockRange range, Predicate filter) { + List> trees = regionsIn(x, y, z, range); + depth++; + try { + for (int i = 0, n = trees.size(); i < n; i++) { + T v = trees.get(i).findAny(x, y, z, range, filter); + if (v != null) return v; + } + return null; + } finally { + depth--; + } + } + + /** 以方块位置为中心查找任一匹配值,未命中时返回空值。 */ + public T findAny(BlockPos center, BlockRange range, Predicate filter) { + return findAny(center.getX(), center.getY(), center.getZ(), range, filter); + } + + /** + * 取得范围内欧氏距离最近的值。距离相等时依次取 X、Y、Z 坐标较小者。 + * + * @param x 中心方块的 X 坐标 + * @param y 中心方块的 Y 坐标 + * @param z 中心方块的 Z 坐标 + * @param range 围绕中心的查询范围 + * @param filter 值的筛选条件,可为空 + * @return 最近的匹配值,没有匹配项时为空 + */ + public T findNearest(int x, int y, int z, BlockRange range, Predicate filter) { + List> trees = regionsIn(x, y, z, range); + depth++; + try { + T best = null; + long bd2 = 0; + int bx = 0, by = 0, bz = 0; + for (int i = 0, n = trees.size(); i < n; i++) { + BlockOctree tree = trees.get(i); + T v = tree.findNearest(x, y, z, range, filter); + if (v == null) continue; + long d2 = tree.lastNearestD2(); + int vx = tree.lastNearestX(), vy = tree.lastNearestY(), vz = tree.lastNearestZ(); + if (best == null || d2 < bd2 || (d2 == bd2 && (vx != bx ? vx < bx : vy != by ? vy < by : vz < bz))) { + best = v; + bd2 = d2; + bx = vx; + by = vy; + bz = vz; + } + } + return best; + } finally { + depth--; + } + } + + /** 以方块位置为中心查找平方欧氏距离最短的匹配值,未命中时返回空值。 */ + public T findNearest(BlockPos center, BlockRange range, Predicate filter) { + return findNearest(center.getX(), center.getY(), center.getZ(), range, filter); + } + + /** 访问所有值。遍历顺序取决于内部区域顺序,遍历中不要修改索引。 */ + public void forEach(Consumer action) { + for (BlockOctree tree : regions.values()) tree.forEach(action); + } + + /** 跨区域查找第一个匹配值,未命中时返回空值。 */ + public T findAny(Predicate filter) { + for (BlockOctree tree : regions.values()) { + T v = tree.findAny(filter); + if (v != null) return v; + } + return null; + } + + /** 当前有值的位置数。 */ + public int size() { + return size; + } + + /** 判断索引中是否还有值。 */ + public boolean isEmpty() { + return size == 0; + } + + /** 返回结构修改版本。调用方可比较两次取得的值判断缓存是否需要刷新。 */ + public int version() { + return version; + } + + /** 丢弃全部数据。已有数据时推进修改版本。 */ + public void clear() { + if (size == 0) return; + regions.clear(); + size = 0; + version++; + } + + int regionCount() { + return regions.size(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/BlockOctree.java b/src/main/java/com/modularmc/mmclutils/api/level/BlockOctree.java new file mode 100644 index 0000000..b6aecb8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/BlockOctree.java @@ -0,0 +1,674 @@ +package com.modularmc.mmclutils.api.level; + +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * 按整数方块坐标存值的稀疏八叉树,每个坐标至多一个值,全部数据放在扁平数组里。功能: + *
    + *
  • {@link #insert}/{@link #get}/{@link #contains}/{@link #remove} 按坐标增删查,复杂度为 O(深度)。重复插入返回 false。越界返回 false 或 + * null
  • + *
  • {@link #query(int, int, int, BlockRange, Predicate, Consumer)} 与收集到 {@link Collection} 的重载:按 + * {@link BlockRange}(球形或长方体)查范围内全部值,可带过滤器,不分配内存; + * 与范围不相交的子树整棵跳过,整体落在范围内的子树不再逐个判距离
  • + *
  • {@link #findAny(int, int, int, BlockRange, Predicate)}:范围内找到第一个满足过滤器的值就返回
  • + *
  • {@link #findNearest(int, int, int, BlockRange, Predicate)}:范围内欧氏距离最近且满足过滤器的值,距离相同时取 x、y、z 依次最小的坐标
  • + *
  • {@link #findAny(Predicate)}/{@link #forEach}:遍历全树;{@link #size}/{@link #isEmpty} O(1);{@link #clear} + * 清空;{@link #inBounds} 判断坐标是否在树覆盖的立方体内
  • + *
  • {@link #compact()}:按 Z 序重排条目池并丢掉空洞,批量插入后调用可提升查询局部性
  • + *
  • 值不能为 null;不是线程安全的
  • + *
+ * + * @param 与坐标关联的非空值类型 + */ +@SuppressWarnings("unchecked") +public final class BlockOctree { + + /** 叶节点分裂前默认可以保存的位置数。 */ + public static final int DEFAULT_LEAF_CAPACITY = 32; + + private static final int INITIAL_LEAF_CAPACITY = 4; + private static final int NODE_INTS = 8; + private static final int LEAF = -1; + private static final int ROOT = 0; + private static final Object NOT_FOUND = new Object(); + + private final int originX, originY, originZ; + private final int shift; + private final int rootSize; + private final int leafCapacity; + private final int initialCapacity; + + private int[] nodes; + private int nodeTop; + private int freeNode; + + private int[] coords; + private Object[] values; + private int poolTop; + + private int[] freeStart; + private int[] freeCap; + private int freeTop; + + private int[] scratchCoords; + private Object[] scratchValues; + private int[] scratchOctant; + private int[] scratchCount; + private int[] scratchPrefix; + private int[] scratchCursor; + + private int allocatedCapacity; + + private int size; + + private long nearestD2; + private int nearestX, nearestY, nearestZ; + private Object nearestValue; + private long lastNearestD2; + private int lastNearestX, lastNearestY, lastNearestZ; + + /** 按 X、Z 共用的边界和独立 Y 边界创建索引,使用默认叶容量。 */ + public BlockOctree(int xzMin, int xzMax, int yMin, int yMax) { + this(xzMin, yMin, xzMin, xzMax, yMax, xzMax, DEFAULT_LEAF_CAPACITY); + } + + /** 使用给定的闭合包围盒和默认叶容量创建索引。 */ + public BlockOctree(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + this(minX, minY, minZ, maxX, maxY, maxZ, DEFAULT_LEAF_CAPACITY); + } + + /** 指定叶容量。边界转换为以最小坐标为原点、边长为二次幂的立方体,调用 {@link #inBounds} 查询实际范围。 */ + public BlockOctree(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int leafCapacity) { + if (maxX < minX || maxY < minY || maxZ < minZ) { + throw new IllegalArgumentException("max must be >= min"); + } + if (leafCapacity < 1) { + throw new IllegalArgumentException("leafCapacity must be >= 1"); + } + long span = Math.max((long) maxX - minX, Math.max((long) maxY - minY, (long) maxZ - minZ)) + 1L; + int s = 64 - Long.numberOfLeadingZeros(span - 1L); + if (s > 30) { + throw new IllegalArgumentException("region span too large: " + span); + } + int edge = 1 << s; + if ((long) minX + edge > Integer.MAX_VALUE + 1L || + (long) minY + edge > Integer.MAX_VALUE + 1L || + (long) minZ + edge > Integer.MAX_VALUE + 1L) { + throw new IllegalArgumentException("region origin + cube size overflows int"); + } + this.shift = s; + this.originX = minX; + this.originY = minY; + this.originZ = minZ; + this.leafCapacity = leafCapacity; + this.initialCapacity = Math.min(INITIAL_LEAF_CAPACITY, leafCapacity); + this.rootSize = edge; + + this.nodes = new int[NODE_INTS << 1]; + this.coords = new int[3 * initialCapacity]; + this.values = new Object[initialCapacity]; + this.freeStart = new int[2]; + this.freeCap = new int[2]; + + nodeTop = 1; + initLeaf(ROOT, initialCapacity); + } + + /** 在未占用的坐标插入非空值。已有值或坐标越界时返回 {@code false}。 */ + public boolean insert(int x, int y, int z, T value) { + if (value == null) throw new NullPointerException("value"); + int lx = x - originX, ly = y - originY, lz = z - originZ; + if (((lx | ly | lz) >>> shift) != 0) return false; + + int node = ROOT; + int s = shift; + for (;;) { + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + if (coords[j] == lx && coords[j + 1] == ly && coords[j + 2] == lz) return false; + } + if (count == leafCapacity) { + if (s == 0) return false; + split(node, s - 1); + base = node << 3; + } else { + if (count == nodes[base + 3]) start = growLeaf(node, count); + int j = (start + count) * 3; + coords[j] = lx; + coords[j + 1] = ly; + coords[j + 2] = lz; + values[start + count] = value; + nodes[base + 2] = count + 1; + size++; + return true; + } + } + int idx = ((lx >>> (s - 1)) & 1) | (((ly >>> (s - 1)) & 1) << 1) | (((lz >>> (s - 1)) & 1) << 2); + s--; + int enc = nodes[base + idx]; + if (enc == 0) { + int child = allocNode(); + initLeaf(child, initialCapacity); + nodes[base + idx] = child + 1; + node = child; + } else { + node = enc - 1; + } + } + } + + /** 读取给定坐标的值,缺失或越界时返回空值。 */ + public T get(int x, int y, int z) { + int lx = x - originX, ly = y - originY, lz = z - originZ; + if (((lx | ly | lz) >>> shift) != 0) return null; + int node = ROOT; + int s = shift; + for (;;) { + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + if (coords[j] == lx && coords[j + 1] == ly && coords[j + 2] == lz) { + return (T) values[start + i]; + } + } + return null; + } + if (s == 0) return null; + int idx = ((lx >>> (s - 1)) & 1) | (((ly >>> (s - 1)) & 1) << 1) | (((lz >>> (s - 1)) & 1) << 2); + s--; + int enc = nodes[base + idx]; + if (enc == 0) return null; + node = enc - 1; + } + } + + /** 检查给定坐标是否保存了值。 */ + public boolean contains(int x, int y, int z) { + return get(x, y, z) != null; + } + + /** 移除并返回原值,缺失或越界时返回空值。 */ + public T remove(int x, int y, int z) { + int lx = x - originX, ly = y - originY, lz = z - originZ; + if (((lx | ly | lz) >>> shift) != 0) return null; + Object removed = removeNode(ROOT, lx, ly, lz, shift); + if (removed == NOT_FOUND) return null; + size--; + return (T) removed; + } + + /** 返回八叉树中保存的值数量。 */ + public int size() { + return size; + } + + /** 判断是否还有任何值。 */ + public boolean isEmpty() { + return size == 0; + } + + /** 释放条目并重新初始化根节点。 */ + public void clear() { + Arrays.fill(values, 0, poolTop, null); + nodeTop = 1; + freeNode = 0; + poolTop = 0; + freeTop = 0; + size = 0; + initLeaf(ROOT, initialCapacity); + } + + /** 检查坐标是否在根节点覆盖的立方体内。 */ + public boolean inBounds(int x, int y, int z) { + return (((x - originX) | (y - originY) | (z - originZ)) >>> shift) == 0; + } + + /** 重新紧凑排列叶内条目的存储,返回写入新数组的条目数。 */ + public int compact() { + if (size == 0) return 0; + int slots = Math.max(64, size); + int[] newCoords = new int[slots * 3]; + Object[] newValues = new Object[slots]; + int written = repack(ROOT, newCoords, newValues, 0); + this.coords = newCoords; + this.values = newValues; + this.poolTop = written; + this.freeTop = 0; + return written; + } + + private int repack(int node, int[] newCoords, Object[] newValues, int write) { + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + if (count > 0) { + System.arraycopy(coords, start * 3, newCoords, write * 3, count * 3); + System.arraycopy(values, start, newValues, write, count); + nodes[base + 1] = write; + nodes[base + 3] = count; + return write + count; + } + nodes[base + 1] = write; + nodes[base + 3] = 0; + return write; + } + for (int i = 0; i < 8; i++) { + int enc = nodes[base + i]; + if (enc != 0) write = repack(enc - 1, newCoords, newValues, write); + } + return write; + } + + /** 将范围内通过筛选的条目交给消费端。筛选可为空,回调中不要修改树。 */ + public void query(int cx, int cy, int cz, BlockRange range, Predicate filter, Consumer sink) { + if (range.isEmpty() || size == 0) return; + query(ROOT, 0, 0, 0, rootSize, (long) cx - originX, (long) cy - originY, (long) cz - originZ, range, filter, sink, false); + } + + /** 向集合追加匹配值并返回实际新增项数。 */ + public int query(int cx, int cy, int cz, BlockRange range, Predicate filter, Collection out) { + if (range.isEmpty() || size == 0) return 0; + int before = out.size(); + query(ROOT, 0, 0, 0, rootSize, (long) cx - originX, (long) cy - originY, (long) cz - originZ, range, filter, out::add, false); + return out.size() - before; + } + + /** 找到任一范围内的匹配值便返回,没有符合项时返回空值。 */ + public T findAny(int cx, int cy, int cz, BlockRange range, Predicate filter) { + if (range.isEmpty() || size == 0) return null; + Object r = findAny(ROOT, 0, 0, 0, rootSize, (long) cx - originX, (long) cy - originY, (long) cz - originZ, range, filter, false); + return r == NOT_FOUND ? null : (T) r; + } + + /** 查找平方欧氏距离最短的范围内匹配值。此方法复用内部查询状态,不可从筛选回调再次调用。 */ + public T findNearest(int cx, int cy, int cz, BlockRange range, Predicate filter) { + if (range.isEmpty() || size == 0) return null; + nearestD2 = Long.MAX_VALUE; + nearestValue = null; + findNearest(ROOT, 0, 0, 0, rootSize, (long) cx - originX, (long) cy - originY, (long) cz - originZ, range, filter); + T result = (T) nearestValue; + nearestValue = null; + if (result != null) { + lastNearestD2 = nearestD2; + lastNearestX = nearestX + originX; + lastNearestY = nearestY + originY; + lastNearestZ = nearestZ + originZ; + } + return result; + } + + long lastNearestD2() { + return lastNearestD2; + } + + int lastNearestX() { + return lastNearestX; + } + + int lastNearestY() { + return lastNearestY; + } + + int lastNearestZ() { + return lastNearestZ; + } + + /** 跨全部叶节点查找任一匹配值。没有符合项时返回空值。 */ + public T findAny(Predicate filter) { + if (size == 0) return null; + Object r = findAnyAll(ROOT, filter); + return r == NOT_FOUND ? null : (T) r; + } + + /** 向使用方传递每个存储值。遍历期间不要结构性修改树。 */ + public void forEach(Consumer action) { + forEach(ROOT, action); + } + + private static int octant(int lx, int ly, int lz, int bit) { + return ((lx >>> bit) & 1) | (((ly >>> bit) & 1) << 1) | (((lz >>> bit) & 1) << 2); + } + + private int allocNode() { + int idx; + if (freeNode != 0) { + idx = freeNode - 1; + freeNode = nodes[idx << 3]; + } else { + idx = nodeTop++; + int needed = (idx + 1) << 3; + if (needed > nodes.length) { + nodes = Arrays.copyOf(nodes, Math.max(needed, nodes.length << 1)); + } + } + int base = idx << 3; + for (int i = 0; i < NODE_INTS; i++) nodes[base + i] = 0; + return idx; + } + + private void freeNode(int idx) { + int base = idx << 3; + nodes[base] = freeNode; + freeNode = idx + 1; + } + + private int allocBlock(int capacity) { + if (freeTop > 0) { + int top = freeTop - 1; + int available = freeCap[top]; + if (available >= capacity) { + freeTop = top; + allocatedCapacity = available; + return freeStart[top]; + } + } + int slots = coords.length / 3; + if (poolTop + capacity > slots) { + int grown = slots; + while (grown < poolTop + capacity) grown <<= 1; + coords = Arrays.copyOf(coords, grown * 3); + values = Arrays.copyOf(values, grown); + } + int start = poolTop; + poolTop = start + capacity; + allocatedCapacity = capacity; + return start; + } + + private void releaseBlock(int start, int capacity) { + if (freeTop == freeStart.length) { + freeStart = Arrays.copyOf(freeStart, freeTop << 1); + freeCap = Arrays.copyOf(freeCap, freeTop << 1); + } + freeStart[freeTop] = start; + freeCap[freeTop] = capacity; + freeTop++; + } + + private void initLeaf(int node, int capacity) { + int start = allocBlock(capacity); + int base = node << 3; + nodes[base] = LEAF; + nodes[base + 1] = start; + nodes[base + 2] = 0; + nodes[base + 3] = allocatedCapacity; + } + + private int growLeaf(int node, int count) { + int base = node << 3; + int oldStart = nodes[base + 1]; + int oldCapacity = nodes[base + 3]; + int wanted = Math.min(Math.max(count + 1, oldCapacity << 1), leafCapacity); + int start = allocBlock(wanted); + int capacity = allocatedCapacity; + System.arraycopy(coords, oldStart * 3, coords, start * 3, count * 3); + System.arraycopy(values, oldStart, values, start, count); + releaseBlock(oldStart, oldCapacity); + nodes[base + 1] = start; + nodes[base + 3] = capacity; + return start; + } + + private void split(int node, int childShift) { + int base = node << 3; + int start = nodes[base + 1]; + int count = nodes[base + 2]; + if (scratchCoords == null) { + scratchCoords = new int[leafCapacity * 3]; + scratchValues = new Object[leafCapacity]; + scratchOctant = new int[leafCapacity]; + scratchCount = new int[8]; + scratchPrefix = new int[8]; + scratchCursor = new int[8]; + } + int[] octantOf = scratchOctant; + int[] countByOctant = scratchCount; + Arrays.fill(countByOctant, 0); + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + int idx = octant(coords[j], coords[j + 1], coords[j + 2], childShift); + octantOf[i] = idx; + countByOctant[idx]++; + } + int[] prefix = scratchPrefix; + int sum = 0; + for (int i = 0; i < 8; i++) { + prefix[i] = sum; + sum += countByOctant[i]; + } + int[] cursor = scratchCursor; + System.arraycopy(prefix, 0, cursor, 0, 8); + int[] sortedCoords = scratchCoords; + Object[] sortedValues = scratchValues; + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + int pos = cursor[octantOf[i]]++; + sortedCoords[pos * 3] = coords[j]; + sortedCoords[pos * 3 + 1] = coords[j + 1]; + sortedCoords[pos * 3 + 2] = coords[j + 2]; + sortedValues[pos] = values[start + i]; + } + System.arraycopy(sortedCoords, 0, coords, start * 3, count * 3); + System.arraycopy(sortedValues, 0, values, start, count); + Arrays.fill(sortedValues, 0, count, null); + + for (int i = 0; i < 8; i++) { + int childCount = countByOctant[i]; + if (childCount == 0) { + nodes[base + i] = 0; + continue; + } + int child = allocNode(); + int childBase = child << 3; + nodes[childBase] = LEAF; + nodes[childBase + 1] = start + prefix[i]; + nodes[childBase + 2] = childCount; + nodes[childBase + 3] = childCount; + nodes[base + i] = child + 1; + } + } + + private Object removeNode(int node, int lx, int ly, int lz, int s) { + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + if (coords[j] == lx && coords[j + 1] == ly && coords[j + 2] == lz) { + Object old = values[start + i]; + int last = count - 1; + if (i != last) { + int lastCoord = (start + last) * 3; + coords[j] = coords[lastCoord]; + coords[j + 1] = coords[lastCoord + 1]; + coords[j + 2] = coords[lastCoord + 2]; + values[start + i] = values[start + last]; + } + values[start + last] = null; + nodes[base + 2] = last; + return old; + } + } + return NOT_FOUND; + } + if (s == 0) return NOT_FOUND; + int idx = ((lx >>> (s - 1)) & 1) | (((ly >>> (s - 1)) & 1) << 1) | (((lz >>> (s - 1)) & 1) << 2); + int enc = nodes[base + idx]; + if (enc == 0) return NOT_FOUND; + int child = enc - 1; + Object removed = removeNode(child, lx, ly, lz, s - 1); + if (removed != NOT_FOUND) { + int childBase = child << 3; + if (nodes[childBase] == LEAF && nodes[childBase + 2] == 0) { + releaseBlock(nodes[childBase + 1], nodes[childBase + 3]); + freeNode(child); + nodes[base + idx] = 0; + } + } + return removed; + } + + private static long gap(long c, int lo, int hi) { + return c < lo ? lo - c : (c > hi ? c - hi : 0); + } + + private static long far(long c, int lo, int hi) { + return Math.max(Math.abs(c - lo), Math.abs(c - hi)); + } + + private void query(int node, int ox, int oy, int oz, int size, long cx, long cy, long cz, BlockRange range, + Predicate filter, Consumer sink, boolean inside) { + int hiX = ox | (size - 1), hiY = oy | (size - 1), hiZ = oz | (size - 1); + if (!inside) { + if (!range.reaches(gap(cx, ox, hiX), gap(cy, oy, hiY), gap(cz, oz, hiZ))) return; + inside = range.reaches(far(cx, ox, hiX), far(cy, oy, hiY), far(cz, oz, hiZ)); + } + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + if (inside) { + for (int i = 0; i < count; i++) { + T v = (T) values[start + i]; + if (filter == null || filter.test(v)) sink.accept(v); + } + } else { + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + if (!range.reaches(Math.abs(coords[j] - cx), Math.abs(coords[j + 1] - cy), Math.abs(coords[j + 2] - cz))) continue; + T v = (T) values[start + i]; + if (filter == null || filter.test(v)) sink.accept(v); + } + } + return; + } + int half = size >>> 1; + for (int i = 0; i < 8; i++) { + int enc = nodes[base + i]; + if (enc == 0) continue; + query(enc - 1, + ox + ((i & 1) == 0 ? 0 : half), + oy + ((i & 2) == 0 ? 0 : half), + oz + ((i & 4) == 0 ? 0 : half), + half, cx, cy, cz, range, filter, sink, inside); + } + } + + private Object findAny(int node, int ox, int oy, int oz, int size, long cx, long cy, long cz, BlockRange range, + Predicate filter, boolean inside) { + int hiX = ox | (size - 1), hiY = oy | (size - 1), hiZ = oz | (size - 1); + if (!inside) { + if (!range.reaches(gap(cx, ox, hiX), gap(cy, oy, hiY), gap(cz, oz, hiZ))) return NOT_FOUND; + inside = range.reaches(far(cx, ox, hiX), far(cy, oy, hiY), far(cz, oz, hiZ)); + } + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + if (!inside && !range.reaches(Math.abs(coords[j] - cx), Math.abs(coords[j + 1] - cy), Math.abs(coords[j + 2] - cz))) continue; + Object v = values[start + i]; + if (filter == null || filter.test((T) v)) return v; + } + return NOT_FOUND; + } + int half = size >>> 1; + for (int i = 0; i < 8; i++) { + int enc = nodes[base + i]; + if (enc == 0) continue; + Object r = findAny(enc - 1, + ox + ((i & 1) == 0 ? 0 : half), + oy + ((i & 2) == 0 ? 0 : half), + oz + ((i & 4) == 0 ? 0 : half), + half, cx, cy, cz, range, filter, inside); + if (r != NOT_FOUND) return r; + } + return NOT_FOUND; + } + + private void findNearest(int node, int ox, int oy, int oz, int size, long cx, long cy, long cz, BlockRange range, + Predicate filter) { + int hiX = ox | (size - 1), hiY = oy | (size - 1), hiZ = oz | (size - 1); + long mx = gap(cx, ox, hiX), my = gap(cy, oy, hiY), mz = gap(cz, oz, hiZ); + if (!range.reaches(mx, my, mz)) return; + if (mx * mx + my * my + mz * mz > nearestD2) return; + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + for (int i = 0, j = start * 3; i < count; i++, j += 3) { + int x = coords[j], y = coords[j + 1], z = coords[j + 2]; + long dx = Math.abs(x - cx), dy = Math.abs(y - cy), dz = Math.abs(z - cz); + if (!range.reaches(dx, dy, dz)) continue; + long d2 = dx * dx + dy * dy + dz * dz; + if (d2 > nearestD2) continue; + if (d2 == nearestD2 && nearestValue != null && !lexLess(x, y, z)) continue; + T v = (T) values[start + i]; + if (filter != null && !filter.test(v)) continue; + nearestD2 = d2; + nearestX = x; + nearestY = y; + nearestZ = z; + nearestValue = v; + } + return; + } + int half = size >>> 1; + for (int i = 0; i < 8; i++) { + int enc = nodes[base + i]; + if (enc == 0) continue; + findNearest(enc - 1, + ox + ((i & 1) == 0 ? 0 : half), + oy + ((i & 2) == 0 ? 0 : half), + oz + ((i & 4) == 0 ? 0 : half), + half, cx, cy, cz, range, filter); + } + } + + private boolean lexLess(int x, int y, int z) { + if (x != nearestX) return x < nearestX; + if (y != nearestY) return y < nearestY; + return z < nearestZ; + } + + private Object findAnyAll(int node, Predicate filter) { + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + for (int i = 0; i < count; i++) { + Object v = values[start + i]; + if (filter == null || filter.test((T) v)) return v; + } + return NOT_FOUND; + } + for (int i = 0; i < 8; i++) { + int enc = nodes[base + i]; + if (enc != 0) { + Object r = findAnyAll(enc - 1, filter); + if (r != NOT_FOUND) return r; + } + } + return NOT_FOUND; + } + + private void forEach(int node, Consumer action) { + int base = node << 3; + if (nodes[base] == LEAF) { + int start = nodes[base + 1]; + int count = nodes[base + 2]; + for (int i = 0; i < count; i++) action.accept((T) values[start + i]); + return; + } + for (int i = 0; i < 8; i++) { + int enc = nodes[base + i]; + if (enc != 0) forEach(enc - 1, action); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/BlockRange.java b/src/main/java/com/modularmc/mmclutils/api/level/BlockRange.java new file mode 100644 index 0000000..687f78f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/BlockRange.java @@ -0,0 +1,251 @@ +package com.modularmc.mmclutils.api.level; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; +import net.minecraft.world.level.LevelHeightAccessor; +import net.minecraft.world.phys.AABB; + +/** + * 以某个方块为中心的查询范围,供 {@link BlockOctree} 和 {@link BlockIndex} 使用。功能: + *
    + *
  • {@link #sphere(int)}:球形,方块坐标差的平方和 ≤ r²;{@link #sphereSq(long)} 直接给平方半径, + * 例如原版 {@code closerThan} 的"严格小于 r"写成 {@code sphereSq(r * r - 1)}
  • + *
  • {@link #box(int)} / {@link #box(int, int, int)}:立方体或长方体,各轴坐标差的绝对值 ≤ 对应半径
  • + *
  • {@link #contains(int, int, int)}:判断坐标差是否落在范围内
  • + *
  • {@link #reaches(long, long, long)}:给定三轴的最小距离,判断一个区域是否可能与范围相交,也用于判断区域是否整体落在范围内
  • + *
  • 半径为负的范围是空范围,什么都不包含
  • + *
  • 0~64 的球形与立方体半径返回预建的共享实例,不分配内存;实例不可变,可放心复用
  • + *
+ */ +public final class BlockRange { + + /** 范围使用的几何形状。 */ + public enum Shape { + /** 三轴平方距离之和不超过半径平方。 */ + SPHERE, + /** 三轴距离分别不超过各自半径。 */ + BOX + } + + private static final int CACHED = 64; + private static final BlockRange EMPTY_SPHERE = new BlockRange(Shape.SPHERE, -1, -1, -1, -1); + private static final BlockRange EMPTY_BOX = new BlockRange(Shape.BOX, -1, -1, -1, -1); + private static final BlockRange[] SPHERES = new BlockRange[CACHED + 1]; + private static final BlockRange[] BOXES = new BlockRange[CACHED + 1]; + + static { + for (int r = 0; r <= CACHED; r++) { + SPHERES[r] = new BlockRange(Shape.SPHERE, r, r, r, (long) r * r); + BOXES[r] = new BlockRange(Shape.BOX, r, r, r, -1); + } + } + + private final Shape shape; + private final int rx, ry, rz; + private final long radiusSq; + + private BlockRange(Shape shape, int rx, int ry, int rz, long radiusSq) { + this.shape = shape; + this.rx = rx; + this.ry = ry; + this.rz = rz; + this.radiusSq = radiusSq; + } + + /** 以方块为单位创建闭球范围。负半径表示空范围。 */ + public static BlockRange sphere(int radius) { + if (radius < 0) return EMPTY_SPHERE; + if (radius <= CACHED) return SPHERES[radius]; + return sphereSq((long) radius * radius); + } + + /** 直接使用平方半径,便于表示严格距离条件。负值表示空范围,各轴外包半径最多为 {@link Integer#MAX_VALUE}。 */ + public static BlockRange sphereSq(long radiusSq) { + if (radiusSq < 0) return EMPTY_SPHERE; + int r = (int) Math.sqrt((double) radiusSq); + while ((long) r * r > radiusSq) r--; + while (r < Integer.MAX_VALUE && (r + 1L) * (r + 1L) <= radiusSq) r++; + return new BlockRange(Shape.SPHERE, r, r, r, radiusSq); + } + + /** 创建三轴半径相同的闭立方体。负半径表示空范围。 */ + public static BlockRange box(int radius) { + return box(radius, radius, radius); + } + + /** 分别指定三轴半径,任一轴为负时返回空范围。 */ + public static BlockRange box(int rx, int ry, int rz) { + if (rx < 0 || ry < 0 || rz < 0) return EMPTY_BOX; + if (rx == ry && ry == rz && rx <= CACHED) return BOXES[rx]; + return new BlockRange(Shape.BOX, rx, ry, rz, -1); + } + + /** + * 以方块中心为基准创建区块覆盖范围,水平方向每增加一圈就在两侧各扩展一个区块宽度。 + * + * @param center 原版压缩坐标可表示的中心方块 + * @param chunkRadius 水平方向的区块圈数,零圈覆盖一个区块宽度 + * @param below 向下覆盖的方块数 + * @param above 向上覆盖的方块数 + * @return 可用于位置判断、区块索引和渲染的范围 + * @throws IllegalArgumentException 圈数或任一高度为负 + */ + public static ChunkCoverage chunkCoverage(BlockPos center, int chunkRadius, int below, int above) { + return new ChunkCoverage(center.asLong(), chunkRadius, below, above); + } + + /** 返回相交测试所使用的形状。 */ + public Shape shape() { + return shape; + } + + /** 返回外包范围在 X 轴的半径,空范围时返回负值。 */ + public int radiusX() { + return rx; + } + + /** 返回外包范围在 Y 轴的半径,空范围时返回负值。 */ + public int radiusY() { + return ry; + } + + /** 返回外包范围在 Z 轴的半径,空范围时返回负值。 */ + public int radiusZ() { + return rz; + } + + /** 返回球形范围的平方半径。盒形或空范围返回 {@code -1}。 */ + public long radiusSq() { + return radiusSq; + } + + /** 判断范围是否排除所有位置,零半径仍包含中心。 */ + public boolean isEmpty() { + return rx < 0; + } + + /** 判断带符号的三轴坐标差是否落在范围内,边界计入。 */ + public boolean contains(int dx, int dy, int dz) { + return reaches(Math.abs((long) dx), Math.abs((long) dy), Math.abs((long) dz)); + } + + /** 用三个非负的轴向最小距离判断范围是否与区域相交。 */ + public boolean reaches(long ax, long ay, long az) { + if (rx < 0) return false; + if (shape == Shape.BOX) return ax <= rx && ay <= ry && az <= rz; + if (ax > rx || ay > ry || az > rz) return false; + return az * az <= radiusSq - ax * ax - ay * ay; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof BlockRange other)) return false; + return shape == other.shape && rx == other.rx && ry == other.ry && rz == other.rz && radiusSq == other.radiusSq; + } + + @Override + public int hashCode() { + int h = shape.hashCode(); + h = 31 * h + rx; + h = 31 * h + ry; + h = 31 * h + rz; + return 31 * h + Long.hashCode(radiusSq); + } + + @Override + public String toString() { + return shape == Shape.SPHERE ? "BlockRange.sphereSq(" + radiusSq + ")" : "BlockRange.box(" + rx + ", " + ry + ", " + rz + ")"; + } + + /** + * 以方块中心对齐的水平正方形和不对称的竖直范围。可在线程之间共享。 + * + * @param center 用 {@link BlockPos#asLong()} 编码的中心方块 + * @param chunkRadius 从中心向外扩展的区块圈数,须非负 + * @param below 从中心方块向下覆盖的方块数,须非负 + * @param above 从中心方块向上覆盖的方块数,须非负 + */ + public record ChunkCoverage(long center, int chunkRadius, int below, int above) { + + /** @throws IllegalArgumentException 圈数或任一高度为负 */ + public ChunkCoverage { + if (chunkRadius < 0 || below < 0 || above < 0) { + throw new IllegalArgumentException("区块圈数和覆盖高度须非负"); + } + } + + /** 判断方块中心是否在范围内,水平最小边界计入,最大边界排除。 */ + public boolean contains(BlockPos pos) { + return contains(pos.getX(), pos.getY(), pos.getZ()); + } + + /** 判断原版压缩坐标对应的方块中心是否在范围内。 */ + public boolean contains(long pos) { + return contains(BlockPos.getX(pos), BlockPos.getY(pos), BlockPos.getZ(pos)); + } + + private boolean contains(int x, int y, int z) { + long halfWidth = halfWidth(); + long dx = (long) x - BlockPos.getX(center); + long dy = (long) y - BlockPos.getY(center); + long dz = (long) z - BlockPos.getZ(center); + return dx >= -halfWidth && dx < halfWidth && dz >= -halfWidth && dz < halfWidth && dy >= -below && dy <= above; + } + + /** 返回未裁切的世界坐标包围盒。最大高度位于最高一层方块的顶面。 */ + public AABB bounds() { + int y = BlockPos.getY(center); + return bounds((double) y - below, (double) y + above + 1); + } + + /** 将包围盒裁切到世界的建造高度。完全落在世界外时,返回贴在相邻边界的零高包围盒。 */ + public AABB bounds(LevelHeightAccessor height) { + int y = BlockPos.getY(center); + int minY = height.getMinY(); + double endY = (double) height.getMaxY() + 1; + return bounds(Math.clamp((double) y - below, minY, endY), Math.clamp((double) y + above + 1, minY, endY)); + } + + /** 返回包围盒相交的最小区块 X 坐标。 */ + public int minChunkX() { + return chunkAt(BlockPos.getX(center) - halfWidth()); + } + + /** 返回包围盒相交的最大区块 X 坐标。 */ + public int maxChunkX() { + return chunkAt(BlockPos.getX(center) + halfWidth()); + } + + /** 返回包围盒相交的最小区块 Z 坐标。 */ + public int minChunkZ() { + return chunkAt(BlockPos.getZ(center) - halfWidth()); + } + + /** 返回包围盒相交的最大区块 Z 坐标。 */ + public int maxChunkZ() { + return chunkAt(BlockPos.getZ(center) + halfWidth()); + } + + /** 返回按覆盖宽度折算的区块数,未计入边缘部分相交的区块。超出 {@code long} 时抛出算术异常。 */ + public long nominalChunkCount() { + long diameter = 2L * chunkRadius + 1; + return Math.multiplyExact(diameter, diameter); + } + + private long halfWidth() { + return ((long) chunkRadius << SectionPos.SECTION_BITS) + SectionPos.SECTION_HALF_SIZE; + } + + private static int chunkAt(long block) { + return Math.toIntExact(block >> SectionPos.SECTION_BITS); + } + + private AABB bounds(double minY, double maxY) { + double x = BlockPos.getX(center) + 0.5; + double z = BlockPos.getZ(center) + 0.5; + long halfWidth = halfWidth(); + return new AABB(x - halfWidth, minY, z - halfWidth, x + halfWidth, maxY, z + halfWidth); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/BlockSearch.java b/src/main/java/com/modularmc/mmclutils/api/level/BlockSearch.java new file mode 100644 index 0000000..297b78a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/BlockSearch.java @@ -0,0 +1,198 @@ +package com.modularmc.mmclutils.api.level; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.common.util.TriPredicate; + +import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue; +import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongSet; +import it.unimi.dsi.fastutil.objects.ObjectArrayFIFOQueue; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import org.jspecify.annotations.Nullable; + +import java.util.List; +import java.util.Set; +import java.util.function.BiPredicate; +import java.util.function.LongFunction; +import java.util.function.LongPredicate; +import java.util.function.Predicate; +import java.util.function.ToLongFunction; + +/** 在六个相邻面上进行有界的广度优先搜索,结果按发现顺序返回。 */ +public final class BlockSearch { + + private static final Direction[] SIDES = Direction.values(); + + private BlockSearch() {} + + /** + * 经过未命中的位置,找到匹配位置时停止从该位置继续扩展。 + * + * @param start 原版打包的起点坐标 + * @param matches 匹配条件,可由调用方决定如何读取位置数据 + * @param resultLimit 匹配位置数的上限 + * @param visitLimit 尝试位置数的上限 + * @return 按发现顺序返回的打包坐标集合 + */ + public static LongSet searchPacked(long start, LongPredicate matches, int resultLimit, int visitLimit) { + var results = new LongLinkedOpenHashSet(); + var visited = new LongOpenHashSet(); + var pending = new LongArrayFIFOQueue(); + visited.add(start); + pending.enqueue(start); + for (int visits = 0; visits < visitLimit && results.size() < resultLimit && !pending.isEmpty(); visits++) { + long pos = pending.dequeueLong(); + if (matches.test(pos)) { + results.add(pos); + } else { + for (Direction side : SIDES) { + long neighbor = BlockPos.offset(pos, side); + if (visited.add(neighbor)) pending.enqueue(neighbor); + } + } + } + return results; + } + + /** 以方块坐标调用 {@link #searchPacked},返回独立的方块坐标。 */ + public static Set search(Predicate predicate, BlockPos start, int resultLimit, int visitLimit) { + return unpack(searchPacked(start.asLong(), pos -> predicate.test(BlockPos.of(pos)), resultLimit, visitLimit)); + } + + /** 按原版方向枚举顺序返回与指定位置共面的六个坐标。 */ + public static List getNeighbors(BlockPos pos) { + var result = new ObjectArrayList(SIDES.length); + for (Direction side : SIDES) result.add(pos.relative(side)); + return result; + } + + /** + * 仅从通过筛选的位置继续访问相邻位置。被拒绝的位置仍可经其他路径进入。 + * 每次筛选占一个尝试名额,已经接受的位置跳过。 + * + * @param start 原版打包的起点坐标 + * @param filter 按到达方向筛选的条件,起点以自身为父位置 + * @param resultLimit 接受位置数的上限 + * @param visitLimit 筛选次数的上限 + * @return 按发现顺序返回的打包坐标集合 + */ + public static LongSet conditionalPacked(long start, EdgeFilter filter, int resultLimit, int visitLimit) { + var accepted = new LongLinkedOpenHashSet(); + var positions = new LongArrayFIFOQueue(); + var parents = new LongArrayFIFOQueue(); + positions.enqueue(start); + parents.enqueue(start); + int visits = 0; + while (visits < visitLimit && accepted.size() < resultLimit && !positions.isEmpty()) { + long next = positions.dequeueLong(); + long from = parents.dequeueLong(); + if (accepted.contains(next)) continue; + visits++; + if (!filter.accept(from, next, visits == 1)) continue; + accepted.add(next); + for (Direction side : SIDES) { + long neighbor = BlockPos.offset(next, side); + if (!accepted.contains(neighbor)) { + positions.enqueue(neighbor); + parents.enqueue(next); + } + } + } + return accepted; + } + + /** 使用方块坐标筛选广度优先搜索的每条边。访问起点时父位置为空值。 */ + public static Set conditionalBlockPosSearch(BlockPos start, BiPredicate<@Nullable BlockPos, BlockPos> filter, + int resultLimit, int visitLimit) { + return unpack(conditionalPacked(start.asLong(), + (parent, pos, first) -> filter.test(first ? null : BlockPos.of(parent), BlockPos.of(pos)), + resultLimit, visitLimit)); + } + + /** + * 在已加载区块内查找相邻方块实体。应在世界所属的逻辑线程调用,起点没有所属世界时返回空集合。 + * + * @param type 允许进入搜索的方块实体类型 + * @param start 搜索起点 + * @param filter 筛选路径,起点的来源实体和方向为空值 + * @param resultLimit 接受实体数的上限 + * @param visitLimit 筛选次数的上限 + * @param 方块实体类型 + * @return 按发现顺序返回的方块实体集合 + */ + public static Set conditionalBlockEntitySearch(Class type, T start, + TriPredicate<@Nullable T, T, @Nullable Direction> filter, + int resultLimit, int visitLimit) { + Level level = start.getLevel(); + if (level == null) return Set.of(); + var cursor = new BlockPos.MutableBlockPos(); + return conditionalSearch(start, value -> value.getBlockPos().asLong(), pos -> { + BlockEntity neighbor = LoadedChunks.blockEntity(level, cursor.set(pos)); + return type.isInstance(neighbor) ? type.cast(neighbor) : null; + }, filter, resultLimit, visitLimit); + } + + /** + * 在调用方提供的坐标索引中沿六面搜索。仅从已接受的节点继续扩展。 + * 同一节点可以从多个方向接受筛选,直到其中一次通过。 + * + * @param start 起点 + * @param position 获取节点的原版打包方块坐标 + * @param lookup 按坐标查询节点,无节点时返回空值 + * @param filter 接收来源节点、目标节点及相对方向,起点的来源和方向为空值 + * @param resultLimit 接受节点数的上限 + * @param visitLimit 筛选次数的上限 + * @param 节点类型 + * @return 按发现顺序返回的节点集合 + */ + public static Set conditionalSearch(T start, ToLongFunction position, LongFunction lookup, + TriPredicate<@Nullable T, T, @Nullable Direction> filter, int resultLimit, int visitLimit) { + var accepted = new ObjectLinkedOpenHashSet(); + var pending = new ObjectArrayFIFOQueue>(); + pending.enqueue(new Step<>(null, start, null)); + int visits = 0; + while (visits < visitLimit && accepted.size() < resultLimit && !pending.isEmpty()) { + Step step = pending.dequeue(); + if (accepted.contains(step.target)) continue; + visits++; + if (!filter.test(step.source, step.target, step.side)) continue; + accepted.add(step.target); + long center = position.applyAsLong(step.target); + for (Direction side : SIDES) { + T neighbor = lookup.apply(BlockPos.offset(center, side)); + if (neighbor != null && !accepted.contains(neighbor)) { + pending.enqueue(new Step<>(step.target, neighbor, side)); + } + } + } + return accepted; + } + + private static Set unpack(LongSet positions) { + var result = new ObjectLinkedOpenHashSet(positions.size()); + for (var iterator = positions.iterator(); iterator.hasNext();) result.add(BlockPos.of(iterator.nextLong())); + return result; + } + + /** 根位置的 root 为真,其他位置提供打包后的父坐标与目标坐标。 */ + @FunctionalInterface + public interface EdgeFilter { + + /** + * 判断搜索是否可经过当前边并记录目标位置。 + * + * @param parent 已访问位置的打包坐标 + * @param position 候选位置的打包坐标 + * @param root 此次调用是否检查起点 + * @return 是否接受候选位置 + */ + boolean accept(long parent, long position, boolean root); + } + + private record Step(@Nullable T source, T target, @Nullable Direction side) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/LevelBlockIndex.java b/src/main/java/com/modularmc/mmclutils/api/level/LevelBlockIndex.java new file mode 100644 index 0000000..40ec4fe --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/LevelBlockIndex.java @@ -0,0 +1,44 @@ +package com.modularmc.mmclutils.api.level; + +import com.modularmc.mmclutils.api.blockentity.BlockEntityIndex; + +import net.minecraft.world.level.Level; + +import org.jspecify.annotations.Nullable; + +/** + * 由使用方自己登记、注销的按维度索引:每个维度实例各有一份 {@link BlockIndex},存放在 {@link LevelStore} 里,通常声明成静态常量。 + * 成员由条件决定(成型、入网等)时用它;成员只由方块实体类型决定时改用自动维护的 {@link BlockEntityIndex}。功能: + *
    + *
  • {@link #create()}:新建一类索引
  • + *
  • {@link #get}:取该维度的索引,没有就创建;{@link #getIfPresent}:只读,没有时返回 null,不创建
  • + *
  • {@link #release}:丢弃该维度的索引。维度卸载时通过 {@link LevelStore#releaseAll} 统一释放
  • + *
  • 索引随维度实例一起回收,不经过全局表;单个 {@link BlockIndex} 只在拥有该维度的线程上使用
  • + *
+ */ +public final class LevelBlockIndex { + + private final LevelStore> store = LevelStore.create(BlockIndex::new); + + private LevelBlockIndex() {} + + /** 为通用方块位置索引分配维度存储槽。每个维度实例持有独立索引。 */ + public static LevelBlockIndex create() { + return new LevelBlockIndex<>(); + } + + /** 读取指定维度的索引,首次访问时创建。 */ + public BlockIndex get(Level level) { + return store.get(level); + } + + /** 查询已经建立的索引,未建立时返回空值。 */ + public @Nullable BlockIndex getIfPresent(Level level) { + return store.getIfPresent(level); + } + + /** 丢弃本维度的索引,后续首次读取时可重新创建。 */ + public void release(Level level) { + store.release(level); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/LevelSections.java b/src/main/java/com/modularmc/mmclutils/api/level/LevelSections.java new file mode 100644 index 0000000..17d7d43 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/LevelSections.java @@ -0,0 +1,208 @@ +package com.modularmc.mmclutils.api.level; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.EmptyLevelChunk; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.LevelChunkSection; + +import org.jspecify.annotations.Nullable; + +import java.util.Collection; +import java.util.function.Predicate; + +/** + * 把维度的方块状态按区段交给 {@link SectionScan}。功能: + *
    + *
  • 默认只读已加载的区块。未加载、高度范围外与空区块整段是虚空空气,全空气区段整段是空气, + * 其余区段用调色板判断能否跳过,调试世界退回逐格读取
  • + *
  • {@link #betweenClosed}/{@link #inRange}/{@link #withinManhattan}:对某维度直接做 {@link SectionScan} 的三种扫描,betweenClosed + * 的角点顺序随意, + * 同 {@code BlockPos.betweenClosed(a, b)}
  • + *
  • 通过 {@link Unloaded} 显式选择未加载区块的处理。传入 {@link Unloaded#LOAD} 时允许请求加载区块。
  • + *
+ * 实例在扫描期间复用当前区块和区段,只在拥有该维度的线程上使用。 + */ +public final class LevelSections implements SectionScan.Sections { + + /** 指定区块扫描遇到未加载区块时的处理方式。 */ + public enum Unloaded { + /** 查询时允许由原版加载所需区块。 */ + LOAD, + /** 不加载区块,将未加载区域视为虚空空气。 */ + SKIP + } + + private final Level level; + private final boolean skipUnloaded; + private final boolean debug; + private final BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); + private int chunkX, chunkZ; + private boolean chunkCached; + private @Nullable LevelChunk chunk; + private @Nullable LevelChunkSection section; + private int baseX, baseY, baseZ; + + /** 创建只读取已加载区块的区段访问器。 */ + public LevelSections(Level level) { + this(level, Unloaded.SKIP); + } + + /** + * 创建一次扫描使用的区段访问器。 + * + * @param level 要读取的维度 + * @param unloaded 遇到未加载区块的处理方式 + */ + public LevelSections(Level level, Unloaded unloaded) { + this.level = level; + this.skipUnloaded = unloaded == Unloaded.SKIP; + this.debug = level.isDebug(); + } + + /** 按原版坐标顺序扫描两角之间的闭区间,未加载区块视为虚空空气。 */ + public static int betweenClosed(Level level, BlockPos a, BlockPos b, Predicate match, int limit, Collection out) { + return betweenClosed(level, Unloaded.SKIP, a, b, match, (state, pos) -> true, limit, out); + } + + /** 扫描闭区间并允许匹配条件读取坐标,未加载区块视为虚空空气。 */ + public static int betweenClosed(Level level, BlockPos a, BlockPos b, Predicate palette, + SectionScan.CellTest test, int limit, Collection out) { + return betweenClosed(level, Unloaded.SKIP, a, b, palette, test, limit, out); + } + + /** 按指定的区块加载策略扫描闭区间,匹配条件仅依赖方块状态。 */ + public static int betweenClosed(Level level, Unloaded unloaded, BlockPos a, BlockPos b, Predicate match, int limit, + Collection out) { + return betweenClosed(level, unloaded, a, b, match, (state, pos) -> true, limit, out); + } + + /** + * 按原版遍历顺序扫描闭区间并追加匹配坐标。 + * + * @param level 要扫描的维度 + * @param unloaded 遇到未加载区块的处理方式 + * @param a 闭区间的一个角点 + * @param b 另一角点,各轴顺序任意 + * @param palette 状态筛选条件,用于跳过无候选状态的区段 + * @param test 对候选方块执行的检查,回调内的坐标在下一次检查时可能被复用 + * @param limit 最多接受的匹配数,非正数时返回零 + * @param out 用于接收匹配坐标的可修改集合 + * @return 本次扫描接受的匹配数 + */ + public static int betweenClosed(Level level, Unloaded unloaded, BlockPos a, BlockPos b, Predicate palette, + SectionScan.CellTest test, int limit, Collection out) { + return SectionScan.betweenClosed(new LevelSections(level, unloaded), Math.min(a.getX(), b.getX()), Math.min(a.getY(), b.getY()), Math.min(a.getZ(), b.getZ()), + Math.max(a.getX(), b.getX()), Math.max(a.getY(), b.getY()), Math.max(a.getZ(), b.getZ()), palette, test, limit, out); + } + + /** 在球形或盒形范围内匹配方块状态,未加载区块视为虚空空气。 */ + public static int inRange(Level level, BlockPos center, BlockRange range, Predicate match, int limit, Collection out) { + return inRange(level, Unloaded.SKIP, center, range, match, (state, pos) -> true, limit, out); + } + + /** 在指定范围内按状态和坐标筛选,未加载区块视为虚空空气。 */ + public static int inRange(Level level, BlockPos center, BlockRange range, Predicate palette, + SectionScan.CellTest test, int limit, Collection out) { + return inRange(level, Unloaded.SKIP, center, range, palette, test, limit, out); + } + + /** 在指定范围内按状态筛选,可显式选择区块加载策略。 */ + public static int inRange(Level level, Unloaded unloaded, BlockPos center, BlockRange range, Predicate match, int limit, + Collection out) { + return inRange(level, unloaded, center, range, match, (state, pos) -> true, limit, out); + } + + /** + * 在球形或盒形范围内追加匹配坐标。整段不与范围相交时跳过该区段。 + * + * @param level 要扫描的维度 + * @param unloaded 遇到未加载区块的处理方式 + * @param center 范围中心 + * @param range 以中心为原点的扫描范围,空范围返回零 + * @param palette 状态筛选条件 + * @param test 对候选方块状态与坐标执行的检查 + * @param limit 最多接受的匹配数,非正数时返回零 + * @param out 用于接收匹配坐标的可修改集合 + * @return 本次扫描接受的匹配数 + */ + public static int inRange(Level level, Unloaded unloaded, BlockPos center, BlockRange range, Predicate palette, + SectionScan.CellTest test, int limit, Collection out) { + return SectionScan.inRange(new LevelSections(level, unloaded), center.getX(), center.getY(), center.getZ(), range, palette, test, limit, out); + } + + /** 按原版曼哈顿距离顺序匹配状态,未加载区块视为虚空空气。 */ + public static int withinManhattan(Level level, BlockPos center, int rx, int ry, int rz, Predicate match, int limit, + Collection out) { + return withinManhattan(level, Unloaded.SKIP, center, rx, ry, rz, match, (state, pos) -> true, limit, out); + } + + /** 按曼哈顿距离顺序筛选状态和坐标,未加载区块视为虚空空气。 */ + public static int withinManhattan(Level level, BlockPos center, int rx, int ry, int rz, Predicate palette, + SectionScan.CellTest test, int limit, Collection out) { + return withinManhattan(level, Unloaded.SKIP, center, rx, ry, rz, palette, test, limit, out); + } + + /** 按曼哈顿距离顺序匹配状态,可显式选择区块加载策略。 */ + public static int withinManhattan(Level level, Unloaded unloaded, BlockPos center, int rx, int ry, int rz, Predicate match, + int limit, Collection out) { + return withinManhattan(level, unloaded, center, rx, ry, rz, match, (state, pos) -> true, limit, out); + } + + /** + * 在三轴半径限定的盒形范围内,沿原版的曼哈顿距离顺序收集方块。 + * + * @param level 要扫描的维度 + * @param unloaded 遇到未加载区块的处理方式 + * @param center 范围中心 + * @param rx X 轴半径 + * @param ry Y 轴半径 + * @param rz Z 轴半径 + * @param palette 状态筛选条件 + * @param test 对候选方块状态与坐标执行的检查 + * @param limit 最多接受的匹配数,非正数时返回零 + * @param out 用于接收匹配坐标的可修改集合 + * @return 本次扫描接受的匹配数 + */ + public static int withinManhattan(Level level, Unloaded unloaded, BlockPos center, int rx, int ry, int rz, Predicate palette, + SectionScan.CellTest test, int limit, Collection out) { + return SectionScan.withinManhattan(new LevelSections(level, unloaded), center.getX(), center.getY(), center.getZ(), rx, ry, rz, palette, test, limit, out); + } + + @Override + public @Nullable BlockState seek(int sectionX, int sectionY, int sectionZ) { + if (level.isOutsideBuildHeight(sectionY << 4)) return Blocks.VOID_AIR.defaultBlockState(); + if (!chunkCached || chunkX != sectionX || chunkZ != sectionZ) { + chunk = skipUnloaded ? LoadedChunks.chunk(level, sectionX, sectionZ) : level.getChunk(sectionX, sectionZ); + chunkX = sectionX; + chunkZ = sectionZ; + chunkCached = true; + } + if (chunk == null || chunk instanceof EmptyLevelChunk) return Blocks.VOID_AIR.defaultBlockState(); + baseX = sectionX << 4; + baseY = sectionY << 4; + baseZ = sectionZ << 4; + if (debug) { + section = null; + return null; + } + LevelChunkSection s = chunk.getSection(chunk.getSectionIndexFromSectionY(sectionY)); + if (s.hasOnlyAir()) return Blocks.AIR.defaultBlockState(); + section = s; + return null; + } + + @Override + @SuppressWarnings("unchecked") + public boolean mayContain(Predicate palette) { + return section == null || section.maybeHas((Predicate) palette); + } + + @Override + public BlockState get(int localX, int localY, int localZ) { + if (section == null) return level.getBlockState(cursor.set(baseX + localX, baseY + localY, baseZ + localZ)); + return section.getBlockState(localX, localY, localZ); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/LevelStore.java b/src/main/java/com/modularmc/mmclutils/api/level/LevelStore.java new file mode 100644 index 0000000..c72dde8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/LevelStore.java @@ -0,0 +1,233 @@ +package com.modularmc.mmclutils.api.level; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.world.level.Level; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.level.LevelEvent; + +import com.mojang.logging.LogUtils; +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * 按维度实例存放一份对象:对象直接挂在 {@link Level} 实例上的槽位数组里,随维度实例一起回收,不经过任何全局表。功能: + *
    + *
  • {@link #create}/{@link #createWithLevel}:新建一种存放,分配一个全局唯一的槽位号,可带释放回调;通常声明成静态常量,任何时候都能创建
  • + *
  • {@link #get}:取该维度的对象,没有就用工厂创建,多个线程同时首次访问也只创建一份;{@link #getIfPresent}:只读,没有时返回 null,不创建
  • + *
  • {@link #set}:直接放入或清空(传 null)该维度的对象,不调用释放回调
  • + *
  • {@link #release}:丢弃该维度的这一份并调用释放回调;{@link #releaseAll}:维度卸载时逐个调用释放回调后丢弃全部,之后 {@link #isReleased} + * 为真
  • + *
  • 按维度实例区分,客户端和服务端的维度互不影响;任何线程都能读写,存放的对象本身是否线程安全由使用方负责
  • + *
+ */ +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) +public final class LevelStore { + + private static final Logger LOGGER = LogUtils.getLogger(); + private static final VarHandle SLOT = MethodHandles.arrayElementVarHandle(Object[].class); + private static final AtomicInteger SLOTS = new AtomicInteger(); + private static volatile LevelStore[] stores = new LevelStore[0]; + + private final int slot; + private final Function factory; + private final @Nullable Consumer onRelease; + + private LevelStore(Function factory, @Nullable Consumer onRelease) { + this.factory = Objects.requireNonNull(factory, "factory"); + this.onRelease = onRelease; + synchronized (LevelStore.class) { + this.slot = SLOTS.getAndIncrement(); + LevelStore[] grown = Arrays.copyOf(stores, slot + 1); + grown[slot] = this; + stores = grown; + } + } + + /** 分配一个可复用的维度槽。工厂只在首次读取空槽时调用,须返回非空值。 */ + public static LevelStore create(Supplier factory) { + Objects.requireNonNull(factory, "factory"); + return new LevelStore<>(holder -> factory.get(), null); + } + + /** 分配带释放回调的槽。维度卸载或显式释放此槽时,回调接收原值。 */ + public static LevelStore create(Supplier factory, Consumer onRelease) { + Objects.requireNonNull(factory, "factory"); + return new LevelStore<>(holder -> factory.get(), Objects.requireNonNull(onRelease, "onRelease")); + } + + /** 分配维度槽,并把发生首次读取的世界实例交给工厂。 */ + public static LevelStore createWithLevel(Function factory) { + Objects.requireNonNull(factory, "factory"); + return new LevelStore<>(holder -> factory.apply((Level) holder), null); + } + + /** 分配维度槽,工厂接收世界实例,释放回调接收被移除的值。 */ + public static LevelStore createWithLevel(Function factory, Consumer onRelease) { + Objects.requireNonNull(factory, "factory"); + return new LevelStore<>(holder -> factory.apply((Level) holder), Objects.requireNonNull(onRelease, "onRelease")); + } + + /** 取得本维度的值,首次访问空槽时同步创建。 */ + public T get(Level level) { + return forHolder((SlotHolder) level); + } + + /** 只查询现有值,空槽时返回空值。 */ + public @Nullable T getIfPresent(Level level) { + return forHolderIfPresent((SlotHolder) level); + } + + /** 替换值,传入空值可清空槽。此操作不会调用释放回调。 */ + public void set(Level level, @Nullable T value) { + setHolder((SlotHolder) level, value); + } + + /** 清空指定维度的本槽,并在调用线程释放原值。 */ + public void release(Level level) { + releaseHolder((SlotHolder) level); + } + + /** 释放维度的全部现有槽,并标记该实例已经卸载。 */ + public static void releaseAll(Level level) { + releaseAllHolder((SlotHolder) level); + } + + @SubscribeEvent + private static void onUnload(LevelEvent.Unload event) { + if (event.getLevel() instanceof Level level) releaseAll(level); + } + + /** 查询世界是否已收到存储释放标记。 */ + public static boolean isReleased(Level level) { + return ((SlotHolder) level).mmclutils$released(); + } + + /** 供注入代码使用,按槽读取并初始化持有者的值。 */ + @ApiStatus.Internal + @SuppressWarnings("unchecked") + public T forHolder(SlotHolder holder) { + Object[] slots = holder.mmclutils$slots(); + if (slots != null && slot < slots.length) { + Object value = SLOT.getAcquire(slots, slot); + if (value != null) return (T) value; + } + return createIn(holder); + } + + /** 供注入代码读取已发布的槽内容。槽未分配或无值时返回空值。 */ + @ApiStatus.Internal + @SuppressWarnings("unchecked") + public @Nullable T forHolderIfPresent(SlotHolder holder) { + Object[] slots = holder.mmclutils$slots(); + return slots != null && slot < slots.length ? (T) SLOT.getAcquire(slots, slot) : null; + } + + /** 供注入代码替换或清空槽内容。替换时由调用处决定旧值的释放。 */ + @ApiStatus.Internal + public void setHolder(SlotHolder holder, @Nullable T value) { + synchronized (holder) { + if (value == null) { + Object[] slots = holder.mmclutils$slots(); + if (slots != null && slot < slots.length) SLOT.setRelease(slots, slot, (Object) null); + return; + } + SLOT.setRelease(capacity(holder), slot, (Object) value); + } + } + + /** 从持有者取走现有值,离开持有者的锁后执行释放回调。 */ + @ApiStatus.Internal + @SuppressWarnings("unchecked") + public void releaseHolder(SlotHolder holder) { + Object value; + synchronized (holder) { + Object[] slots = holder.mmclutils$slots(); + if (slots == null || slot >= slots.length) return; + value = SLOT.getAcquire(slots, slot); + SLOT.setRelease(slots, slot, (Object) null); + } + if (value != null) notifyRelease((T) value); + } + + /** 摘除持有者的槽数组,再逐槽执行各自的释放回调。 */ + @ApiStatus.Internal + public static void releaseAllHolder(SlotHolder holder) { + Object[] slots; + synchronized (holder) { + slots = holder.mmclutils$slots(); + holder.mmclutils$setSlots(null); + holder.mmclutils$setReleased(true); + } + if (slots == null) return; + LevelStore[] all = stores; + for (int i = 0; i < slots.length && i < all.length; i++) { + Object value = SLOT.getAcquire(slots, i); + if (value != null) all[i].notifyReleaseUnchecked(value); + } + } + + @SuppressWarnings("unchecked") + private T createIn(SlotHolder holder) { + synchronized (holder) { + Object[] slots = capacity(holder); + Object value = SLOT.getAcquire(slots, slot); + if (value != null) return (T) value; + T created = Objects.requireNonNull(factory.apply(holder), "factory returned null"); + SLOT.setRelease(capacity(holder), slot, (Object) created); + return created; + } + } + + private Object[] capacity(SlotHolder holder) { + Object[] slots = holder.mmclutils$slots(); + if (slots != null && slot < slots.length) return slots; + Object[] grown = new Object[Math.max(slot + 1, SLOTS.get())]; + if (slots != null) System.arraycopy(slots, 0, grown, 0, slots.length); + holder.mmclutils$setSlots(grown); + return grown; + } + + @SuppressWarnings("unchecked") + private void notifyReleaseUnchecked(Object value) { + notifyRelease((T) value); + } + + private void notifyRelease(T value) { + if (onRelease == null) return; + try { + onRelease.accept(value); + } catch (Throwable t) { + LOGGER.error("维度存储的释放回调失败", t); + } + } + + /** 由维度实例持有的存储槽及卸载状态。写入由 LevelStore 负责。 */ + @ApiStatus.Internal + public interface SlotHolder { + + /** 初次分配前返回空值。 */ + @Nullable + Object[] mmclutils$slots(); + + /** 分配、扩容或释放时发布槽数组。 */ + void mmclutils$setSlots(@Nullable Object[] slots); + + /** 查询该维度实例是否已经释放。 */ + boolean mmclutils$released(); + + /** 在卸载时发布该维度实例的释放状态。 */ + void mmclutils$setReleased(boolean released); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/LoadedChunks.java b/src/main/java/com/modularmc/mmclutils/api/level/LoadedChunks.java new file mode 100644 index 0000000..e0852d2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/LoadedChunks.java @@ -0,0 +1,113 @@ +package com.modularmc.mmclutils.api.level; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkSource; +import net.minecraft.world.level.chunk.LevelChunk; + +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; + +/** + * 只读已加载完成的区块,绝不触发加载,也不阻塞主线程。功能: + *
    + *
  • {@link #chunk}:取已加载的区块,没有就返回 null;服务端在主线程上同原版 getChunkNow,在其它线程上读区块表的可见副本,并用最近 4 个区块的缓存加速
  • + *
  • {@link #isLoaded}:该格所在的区块是否已加载
  • + *
  • {@link #blockState}:未加载或在高度范围外时返回虚空空气
  • + *
  • {@link #blockEntity}:未加载、没有或已移除时返回 null,不创建待加载的方块实体
  • + *
  • 任何线程都能调用;在非主线程上读到的是某一时刻的值,可能和主线程的写入交错,需要强一致时应在主线程上取
  • + *
+ */ +public final class LoadedChunks { + + /** 区块未加载或位置超出建造高度时使用的虚空空气状态。 */ + public static final BlockState UNLOADED = Blocks.VOID_AIR.defaultBlockState(); + + private LoadedChunks() {} + + /** 按区块坐标查询已经存在的区块,缺失时返回空值。 */ + public static @Nullable LevelChunk chunk(Level level, int chunkX, int chunkZ) { + ChunkSource source = level.getChunkSource(); + if (source instanceof Source loaded) return loaded.mmclutils$loadedChunk(chunkX, chunkZ); + return source.getChunk(chunkX, chunkZ, false); + } + + /** 将方块位置换算成区块坐标,查询已加载区块。缺失时返回空值。 */ + public static @Nullable LevelChunk chunk(Level level, BlockPos pos) { + return chunk(level, pos.getX() >> 4, pos.getZ() >> 4); + } + + /** 检查该位置所属区块是否已加载。此方法只检查区块平面坐标。 */ + public static boolean isLoaded(Level level, BlockPos pos) { + return chunk(level, pos.getX() >> 4, pos.getZ() >> 4) != null; + } + + /** 读取已加载区块中的方块。位置超出建造高度或区块缺失时返回 {@link #UNLOADED}。 */ + public static BlockState blockState(Level level, BlockPos pos) { + if (level.isOutsideBuildHeight(pos.getY())) return UNLOADED; + LevelChunk chunk = chunk(level, pos.getX() >> 4, pos.getZ() >> 4); + return chunk == null ? UNLOADED : chunk.getBlockState(pos); + } + + /** 读取已经创建且仍有效的方块实体。区块、条目缺失或实体已经移除时返回空值。 */ + public static @Nullable BlockEntity blockEntity(Level level, BlockPos pos) { + LevelChunk chunk = chunk(level, pos.getX() >> 4, pos.getZ() >> 4); + if (chunk == null) return null; + BlockEntity be = chunk.getBlockEntities().get(pos); + return be == null || be.isRemoved() ? null : be; + } + + /** 区块源提供的只读查询。未加载或尚未完成时返回空值。 */ + @ApiStatus.Internal + public interface Source { + + /** 查询指定区块坐标,调用期间不会加载区块。 */ + @Nullable + LevelChunk mmclutils$loadedChunk(int chunkX, int chunkZ); + } + + /** + * 最近取过的 4 个区块的缓存,供多个线程无锁共用。功能: + *
    + *
  • {@link #get}:按打包坐标找,命中返回缓存的值,否则返回 null
  • + *
  • {@link #put}:轮流覆盖 4 个槽位;坐标和值放在同一个不可变对象里,并发读写时只会读到某一次完整写入的坐标和值,不会读到错位的一对
  • + *
  • {@link #clear}:清空全部槽位
  • + *
+ */ + @ApiStatus.Internal + public static final class RecentChunks { + + private record Slot(long key, C value) {} + + @SuppressWarnings("unchecked") + private final Slot[] slots = new Slot[4]; + private int next; + + /** 按打包的区块坐标查询,缓存未命中时返回空值。 */ + public @Nullable C get(long key) { + Slot[] s = slots; + for (int i = 0; i < 4; i++) { + Slot slot = s[i]; + if (slot != null && slot.key == key) return slot.value; + } + return null; + } + + /** 覆盖轮换位置的键和值。并发读者始终从同一个缓存条目读取键和值。 */ + public void put(long key, C value) { + int i = next; + next = (i + 1) & 3; + slots[i] = new Slot<>(key, value); + } + + /** 清空所有缓存条目,下一次查询将重新读取区块源。 */ + public void clear() { + Arrays.fill(slots, null); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/level/SectionScan.java b/src/main/java/com/modularmc/mmclutils/api/level/SectionScan.java new file mode 100644 index 0000000..bbdd93e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/level/SectionScan.java @@ -0,0 +1,399 @@ +package com.modularmc.mmclutils.api.level; + +import net.minecraft.core.BlockPos; + +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Predicate; + +/** + * 在长方体范围里找满足条件的格子:先用 16³ 区段的调色板排除不可能命中的区段,只逐格读剩下的,结果顺序与原版逐格遍历相同。功能: + *
    + *
  • {@link #betweenClosed}:按 {@code BlockPos.betweenClosed} 的顺序收集前 limit 个命中的格子,够数后不再读 z 更靠后的区段层
  • + *
  • {@link #inRange}:同 betweenClosed,范围换成以某格为中心的 {@link BlockRange}(球形或长方体),只判断落在范围内的格子,整段在范围外的区段不读, + * 顺序是范围外接长方体的 betweenClosed 顺序
  • + *
  • {@link #withinManhattan}:按 {@code BlockPos.withinManhattan} 的顺序收集前 limit 个命中的格子,区段按到中心的最小曼哈顿距离由近到远处理, + * 够数后更远的区段不再读;limit 有限时按距离分段推进(8、16、32……),每段只读落在该段距离内的格子,够数就停
  • + *
  • {@link Sections#seek} 返回非 null 表示整个区段都是这个值(高度范围外、空区块、全空气区段),palette 与 test 都只对它判断,不逐格读
  • + *
  • palette 必须对所有可能命中的值成立:区段不含满足 palette 的值就整段跳过;格子的值不满足 palette 时不调用 test
  • + *
  • test 拿到的坐标是复用的可变坐标,只在调用期间有效;收集到的坐标是新建的不可变坐标,按顺序追加到 out,返回追加的个数
  • + *
  • betweenClosed、inRange 在 limit 有限时先按原版顺序逐格看最前面的 1024 格,够数就停(目标常见时和原版一样早停),不够再按区段扫剩下的部分
  • + *
  • limit 小于 1、任一半径为负或最小角大于最大角时什么都不收集;范围大到排序键放不下时退回逐格遍历,结果相同
  • + *
+ */ +public final class SectionScan { + + /** + * 为区段扫描提供统一值跳过、调色板筛选和单格读取入口。 + * 实现负责保证 {@link #get} 接收有效的局部坐标。 + * + * @param 区段单格值类型 + */ + public interface Sections { + + /** + * 获取指定区段的统一值,或以空值表示需逐格读取。 + * + * @param sectionX 区段 X 坐标 + * @param sectionY 区段 Y 坐标 + * @param sectionZ 区段 Z 坐标 + * @return 表示整个区段内容的值,空值表示没有可跳过的统一值 + */ + @Nullable + T seek(int sectionX, int sectionY, int sectionZ); + + /** 判断区段调色板是否可能含有满足筛选条件的值。 */ + boolean mayContain(Predicate palette); + + /** 按 0~15 的区段局部坐标取得单格值。 */ + T get(int localX, int localY, int localZ); + } + + /** 对已读取的单格值和当前可变方块坐标执行最终匹配。 */ + public interface CellTest { + + /** + * 检查一个单格值。 + * + * @param value 单格方块状态或统一区段值 + * @param pos 扫描器复用的坐标,只在本次调用期间有效 + * @return 是否收集该坐标 + */ + boolean test(T value, BlockPos pos); + } + + private static final int MAX_SECTIONS = 1 << 24; + private static final int HEAD_CELLS = 1024; + private static final int FIRST_BAND = 8; + + private SectionScan() {} + + /** 按原版闭合区间遍历顺序收集匹配坐标。调色板筛选可整段跳过,结果使用不可变坐标,最多收集指定数量。 */ + public static int betweenClosed(Sections sections, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, + Predicate palette, CellTest test, int limit, Collection out) { + return closed(sections, minX, minY, minZ, maxX, maxY, maxZ, null, 0, 0, 0, palette, test, limit, out); + } + + /** 在指定几何范围内按原版闭合区间的顺序收集匹配坐标。空范围立即返回零。 */ + public static int inRange(Sections sections, int cx, int cy, int cz, BlockRange range, + Predicate palette, CellTest test, int limit, Collection out) { + if (range.isEmpty()) return 0; + int minX = clamp((long) cx - range.radiusX()), maxX = clamp((long) cx + range.radiusX()); + int minY = clamp((long) cy - range.radiusY()), maxY = clamp((long) cy + range.radiusY()); + int minZ = clamp((long) cz - range.radiusZ()), maxZ = clamp((long) cz + range.radiusZ()); + return closed(sections, minX, minY, minZ, maxX, maxY, maxZ, range, cx, cy, cz, palette, test, limit, out); + } + + private static int closed(Sections sections, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, + @Nullable BlockRange range, int cx, int cy, int cz, + Predicate palette, CellTest test, int limit, Collection out) { + if (limit < 1 || minX > maxX || minY > maxY || minZ > maxZ) return 0; + int bx = bits((long) maxX - minX), by = bits((long) maxY - minY), bz = bits((long) maxZ - minZ); + long count = (long) ((maxX >> 4) - (minX >> 4) + 1) * ((maxY >> 4) - (minY >> 4) + 1) * ((maxZ >> 4) - (minZ >> 4) + 1); + if (bx + by + bz > 63 || count > MAX_SECTIONS) { + return closedBrute(sections, minX, minY, minZ, maxX, maxY, maxZ, range, cx, cy, cz, palette, test, limit, out); + } + Keys keys = new Keys(limit); + BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); + int shiftZ = bx + by; + long head = -1; + if (limit != Integer.MAX_VALUE) { + int budget = HEAD_CELLS; + boolean complete = true; + scan: + for (long z = minZ; z <= maxZ; z++) { + for (long y = minY; y <= maxY; y++) { + long lo = minX, hi = maxX; + if (range != null) { + long half = rowHalfWidth(range, y - cy, z - cz); + if (half < 0) continue; + lo = Math.max(minX, cx - half); + hi = Math.min(maxX, cx + half); + } + for (long x = lo; x <= hi; x++) { + if (budget-- == 0) { + complete = false; + break scan; + } + long key = ((z - minZ) << shiftZ) | ((y - minY) << bx) | (x - minX); + T v = valueAt(sections, (int) x, (int) y, (int) z); + if (palette.test(v) && test.test(v, cursor.set((int) x, (int) y, (int) z))) { + keys.add(key); + if (keys.size >= limit) break scan; + } + head = key; + } + } + } + if (complete || keys.size >= limit) return emitClosed(keys, minX, minY, minZ, bx, by, out); + } + for (int sz = minZ >> 4, sz1 = maxZ >> 4; sz <= sz1; sz++) { + int z0 = Math.max(minZ, sz << 4), z1 = Math.min(maxZ, (sz << 4) + 15); + if (keys.size >= limit && ((long) (z0 - minZ) << shiftZ) > keys.bound()) break; + for (int sy = minY >> 4, sy1 = maxY >> 4; sy <= sy1; sy++) { + int y0 = Math.max(minY, sy << 4), y1 = Math.min(maxY, (sy << 4) + 15); + for (int sx = minX >> 4, sx1 = maxX >> 4; sx <= sx1; sx++) { + int x0 = Math.max(minX, sx << 4), x1 = Math.min(maxX, (sx << 4) + 15); + if (range != null && !range.reaches(axisDistance(cx, x0, x1), axisDistance(cy, y0, y1), axisDistance(cz, z0, z1))) continue; + if ((((long) (z1 - minZ) << shiftZ) | ((long) (y1 - minY) << bx) | (x1 - minX)) <= head) continue; + T uniform = sections.seek(sx, sy, sz); + boolean dense = uniform == null; + if (dense ? !sections.mayContain(palette) : !palette.test(uniform)) continue; + for (int z = z0; z <= z1; z++) { + for (int y = y0; y <= y1; y++) { + int lo = x0, hi = x1; + if (range != null) { + long half = rowHalfWidth(range, (long) y - cy, (long) z - cz); + if (half < 0) continue; + lo = (int) Math.max(x0, cx - half); + hi = (int) Math.min(x1, cx + half); + } + for (int x = lo; x <= hi; x++) { + long key = ((long) (z - minZ) << shiftZ) | ((long) (y - minY) << bx) | (x - minX); + if (key <= head) continue; + T v = uniform; + if (dense) { + v = sections.get(x & 15, y & 15, z & 15); + if (!palette.test(v)) continue; + } + if (test.test(v, cursor.set((int) x, (int) y, (int) z))) { + keys.add(key); + } + } + } + } + } + } + } + return emitClosed(keys, minX, minY, minZ, bx, by, out); + } + + private static int emitClosed(Keys keys, int minX, int minY, int minZ, int bx, int by, Collection out) { + keys.compact(); + long maskX = (1L << bx) - 1, maskY = (1L << by) - 1; + for (int i = 0; i < keys.size; i++) { + long k = keys.data[i]; + out.add(new BlockPos(minX + (int) (k & maskX), minY + (int) ((k >>> bx) & maskY), minZ + (int) (k >>> (bx + by)))); + } + return keys.size; + } + + /** 按原版曼哈顿遍历顺序收集坐标。区段按距离推进,达到上限即停止读取更远的区段。 */ + public static int withinManhattan(Sections sections, int cx, int cy, int cz, int rx, int ry, int rz, + Predicate palette, CellTest test, int limit, Collection out) { + if (limit < 1 || rx < 0 || ry < 0 || rz < 0) return 0; + int bx = bits(2L * rx), by = bits(2L * ry), bz = bits(2L * rz), bd = bits((long) rx + ry + rz); + long minX = (long) cx - rx, maxX = (long) cx + rx, minY = (long) cy - ry, maxY = (long) cy + ry, minZ = (long) cz - rz, maxZ = (long) cz + rz; + long nx = (maxX >> 4) - (minX >> 4) + 1, ny = (maxY >> 4) - (minY >> 4) + 1, nz = (maxZ >> 4) - (minZ >> 4) + 1; + if (bd + bx + by + bz > 63 || nx * ny * nz > MAX_SECTIONS || minX < Integer.MIN_VALUE || maxX > Integer.MAX_VALUE || + minY < Integer.MIN_VALUE || maxY > Integer.MAX_VALUE || minZ < Integer.MIN_VALUE || maxZ > Integer.MAX_VALUE) { + return withinManhattanBrute(sections, cx, cy, cz, rx, ry, rz, palette, test, limit, out); + } + int sx0 = (int) (minX >> 4), sy0 = (int) (minY >> 4), sz0 = (int) (minZ >> 4); + int cnx = (int) nx, cny = (int) ny, cnz = (int) nz; + long[] order = new long[cnx * cny * cnz]; + int n = 0; + for (int iz = 0; iz < cnz; iz++) { + long dz = axisDistance(cz, Math.max(minZ, (long) (sz0 + iz) << 4), Math.min(maxZ, ((long) (sz0 + iz) << 4) + 15)); + for (int iy = 0; iy < cny; iy++) { + long dy = axisDistance(cy, Math.max(minY, (long) (sy0 + iy) << 4), Math.min(maxY, ((long) (sy0 + iy) << 4) + 15)); + for (int ix = 0; ix < cnx; ix++) { + long dx = axisDistance(cx, Math.max(minX, (long) (sx0 + ix) << 4), Math.min(maxX, ((long) (sx0 + ix) << 4) + 15)); + order[n] = (dx + dy + dz) << 24 | n; + n++; + } + } + } + Arrays.sort(order); + Keys keys = new Keys(limit); + BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); + int shiftD = bx + by + bz, shiftX = by + bz; + long reach = (long) rx + ry + rz; + long lo = -1, hi = limit == Integer.MAX_VALUE ? reach : Math.min(reach, FIRST_BAND); + while (true) { + for (long o : order) { + long nearest = o >>> 24; + if (nearest > hi) break; + if (keys.size >= limit && nearest > (keys.bound() >>> shiftD)) break; + int idx = (int) (o & 0xFFFFFF); + int sx = sx0 + idx % cnx, sy = sy0 + (idx / cnx) % cny, sz = sz0 + idx / (cnx * cny); + int x0 = (int) Math.max(minX, sx << 4), x1 = (int) Math.min(maxX, (sx << 4) + 15); + int y0 = (int) Math.max(minY, sy << 4), y1 = (int) Math.min(maxY, (sy << 4) + 15); + int z0 = (int) Math.max(minZ, sz << 4), z1 = (int) Math.min(maxZ, (sz << 4) + 15); + if (axisReach(cx, x0, x1) + axisReach(cy, y0, y1) + axisReach(cz, z0, z1) <= lo) continue; + T uniform = sections.seek(sx, sy, sz); + boolean dense = uniform == null; + if (dense ? !sections.mayContain(palette) : !palette.test(uniform)) continue; + for (int z = z0; z <= z1; z++) { + int dz = z - cz; + for (int y = y0; y <= y1; y++) { + int dy = y - cy; + long base = (long) Math.abs(dy) + Math.abs(dz); + long far = hi - base; + if (far < 0) continue; + long near = Math.max(0, lo + 1 - base); + if (near > far) continue; + if (near == 0) { + scanRow(sections, uniform, (int) Math.max(x0, cx - far), (int) Math.min(x1, cx + far), y, z, cx, dy, dz, rx, ry, rz, bz, shiftX, shiftD, palette, test, cursor, keys); + } else { + scanRow(sections, uniform, (int) Math.max(x0, cx - far), (int) Math.min(x1, cx - near), y, z, cx, dy, dz, rx, ry, rz, bz, shiftX, shiftD, palette, test, cursor, keys); + scanRow(sections, uniform, (int) Math.max(x0, cx + near), (int) Math.min(x1, cx + far), y, z, cx, dy, dz, rx, ry, rz, bz, shiftX, shiftD, palette, test, cursor, keys); + } + } + } + } + if (keys.size >= limit || hi >= reach) break; + lo = hi; + hi = Math.min(reach, hi * 2); + } + return emitManhattan(keys, cx, cy, cz, rx, ry, rz, bx, by, bz, out); + } + + private static void scanRow(Sections sections, @Nullable T uniform, int from, int to, int y, int z, int cx, int dy, int dz, int rx, int ry, int rz, + int bz, int shiftX, int shiftD, Predicate palette, CellTest test, BlockPos.MutableBlockPos cursor, Keys keys) { + int ly = y & 15, lz = z & 15; + long rowKey = (long) (dy + ry) << bz | (rz - dz); + long rowDistance = (long) Math.abs(dy) + Math.abs(dz); + for (int x = from; x <= to; x++) { + T v = uniform; + if (v == null) { + v = sections.get(x & 15, ly, lz); + if (!palette.test(v)) continue; + } + if (test.test(v, cursor.set(x, y, z))) { + int dx = x - cx; + keys.add((rowDistance + Math.abs(dx)) << shiftD | (long) (dx + rx) << shiftX | rowKey); + } + } + } + + private static int emitManhattan(Keys keys, int cx, int cy, int cz, int rx, int ry, int rz, int bx, int by, int bz, Collection out) { + int shiftX = by + bz; + keys.compact(); + long maskX = (1L << bx) - 1, maskY = (1L << by) - 1, maskZ = (1L << bz) - 1; + for (int i = 0; i < keys.size; i++) { + long k = keys.data[i]; + int dx = (int) ((k >>> shiftX) & maskX) - rx, dy = (int) ((k >>> bz) & maskY) - ry, dz = rz - (int) (k & maskZ); + out.add(new BlockPos(cx + dx, cy + dy, cz + dz)); + } + return keys.size; + } + + static int betweenClosedBrute(Sections sections, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, + Predicate palette, CellTest test, int limit, Collection out) { + return closedBrute(sections, minX, minY, minZ, maxX, maxY, maxZ, null, 0, 0, 0, palette, test, limit, out); + } + + static int inRangeBrute(Sections sections, int cx, int cy, int cz, BlockRange range, + Predicate palette, CellTest test, int limit, Collection out) { + if (range.isEmpty()) return 0; + return closedBrute(sections, clamp((long) cx - range.radiusX()), clamp((long) cy - range.radiusY()), clamp((long) cz - range.radiusZ()), + clamp((long) cx + range.radiusX()), clamp((long) cy + range.radiusY()), clamp((long) cz + range.radiusZ()), range, cx, cy, cz, + palette, test, limit, out); + } + + private static int closedBrute(Sections sections, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, + @Nullable BlockRange range, int cx, int cy, int cz, + Predicate palette, CellTest test, int limit, Collection out) { + if (limit < 1 || minX > maxX || minY > maxY || minZ > maxZ) return 0; + int found = 0; + BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); + for (long z = minZ; z <= maxZ; z++) { + for (long y = minY; y <= maxY; y++) { + for (long x = minX; x <= maxX; x++) { + if (range != null && !range.reaches(Math.abs(x - cx), Math.abs(y - cy), Math.abs(z - cz))) continue; + T v = valueAt(sections, (int) x, (int) y, (int) z); + if (palette.test(v) && test.test(v, cursor.set((int) x, (int) y, (int) z))) { + out.add(cursor.immutable()); + if (++found >= limit) return found; + } + } + } + } + return found; + } + + static int withinManhattanBrute(Sections sections, int cx, int cy, int cz, int rx, int ry, int rz, + Predicate palette, CellTest test, int limit, Collection out) { + if (limit < 1 || rx < 0 || ry < 0 || rz < 0) return 0; + int found = 0; + for (BlockPos p : BlockPos.withinManhattan(new BlockPos(cx, cy, cz), rx, ry, rz)) { + T v = valueAt(sections, p.getX(), p.getY(), p.getZ()); + if (palette.test(v) && test.test(v, p)) { + out.add(p.immutable()); + if (++found >= limit) break; + } + } + return found; + } + + private static T valueAt(Sections sections, int x, int y, int z) { + T uniform = sections.seek(x >> 4, y >> 4, z >> 4); + return uniform != null ? uniform : sections.get(x & 15, y & 15, z & 15); + } + + private static long rowHalfWidth(BlockRange range, long dy, long dz) { + long ay = Math.abs(dy), az = Math.abs(dz); + if (ay > range.radiusY() || az > range.radiusZ()) return -1; + if (range.shape() == BlockRange.Shape.BOX) return range.radiusX(); + long rest = range.radiusSq() - ay * ay - az * az; + if (rest < 0) return -1; + long h = (long) Math.sqrt((double) rest); + while (h * h > rest) h--; + while ((h + 1) * (h + 1) <= rest) h++; + return Math.min(h, range.radiusX()); + } + + private static int clamp(long v) { + return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, v)); + } + + private static long axisReach(long center, long lo, long hi) { + return Math.max(Math.abs(lo - center), Math.abs(hi - center)); + } + + private static long axisDistance(long center, long lo, long hi) { + return center < lo ? lo - center : center > hi ? center - hi : 0; + } + + private static int bits(long span) { + return 64 - Long.numberOfLeadingZeros(span); + } + + private static final class Keys { + + final int limit; + long[] data = new long[16]; + int size; + boolean sorted = true; + + Keys(int limit) { + this.limit = limit; + } + + void add(long key) { + if (sorted && size >= limit && key > data[limit - 1]) return; + if (size == data.length) { + if (size >= limit) compact(); + if (size == data.length) data = Arrays.copyOf(data, size * 2); + } + data[size++] = key; + sorted = false; + } + + long bound() { + compact(); + return data[limit - 1]; + } + + void compact() { + if (!sorted) { + Arrays.sort(data, 0, size); + sorted = true; + } + if (size > limit) size = limit; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/recipe/IngredientMatching.java b/src/main/java/com/modularmc/mmclutils/api/recipe/IngredientMatching.java new file mode 100644 index 0000000..7d4727d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/recipe/IngredientMatching.java @@ -0,0 +1,321 @@ +package com.modularmc.mmclutils.api.recipe; + +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectList; +import it.unimi.dsi.fastutil.objects.ObjectLists; +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.function.BiFunction; + +/** + * 将带计数的物品需求匹配到实际输入槽。 + * + *

+ * 先按相同物品及组件归并,再将消耗量分配回来源槽位。 + * 每个非空输入都须至少命中一项需求。 + * 某类物品的需求由其它槽位满足时,允许其余匹配的物品保留在原槽。 + *

+ */ +public final class IngredientMatching { + + private IngredientMatching() {} + + /** + * 匹配全部需求,并返回各来源槽实际应消耗的数量。 + * + * @return 匹配成功时返回分配结果。双方均为空时返回空列表,匹配失败时返回 {@code null} + */ + public static @Nullable ObjectList match( + Iterable requirements, + ObjectList inputs) { + ObjectList normalized = new ObjectArrayList<>(); + for (CountedRequirement requirement : requirements) { + normalized.add(requirement); + } + ObjectList aggregatedInputs = aggregate(inputs); + if (normalized.isEmpty()) { + return aggregatedInputs.isEmpty() ? ObjectLists.emptyList() : null; + } + if (aggregatedInputs.isEmpty()) { + return null; + } + + for (AggregatedInput input : aggregatedInputs) { + if (!acceptsAny(normalized, input.stack)) { + return null; + } + } + + int source = 0; + int requirementStart = 1; + int inputStart = requirementStart + normalized.size(); + int sink = inputStart + aggregatedInputs.size(); + FlowNetwork network = new FlowNetwork(sink + 1); + int requiredAmount = 0; + for (int requirementIndex = 0; requirementIndex < normalized.size(); requirementIndex++) { + CountedRequirement requirement = normalized.get(requirementIndex); + requiredAmount = Math.addExact(requiredAmount, requirement.count()); + network.addEdge(source, requirementStart + requirementIndex, requirement.count()); + for (int inputIndex = 0; inputIndex < aggregatedInputs.size(); inputIndex++) { + AggregatedInput input = aggregatedInputs.get(inputIndex); + if (requirement.ingredient().test(input.stack)) { + network.addEdge(requirementStart + requirementIndex, + inputStart + inputIndex, + input.count); + } + } + } + + ObjectList inputCapacityEdges = new ObjectArrayList<>(aggregatedInputs.size()); + for (int inputIndex = 0; inputIndex < aggregatedInputs.size(); inputIndex++) { + inputCapacityEdges.add(network.addEdge( + inputStart + inputIndex, + sink, + aggregatedInputs.get(inputIndex).count)); + } + + if (network.maxFlow(source, sink) != requiredAmount) { + return null; + } + + ObjectList assignments = new ObjectArrayList<>(); + for (int inputIndex = 0; inputIndex < aggregatedInputs.size(); inputIndex++) { + int remaining = inputCapacityEdges.get(inputIndex).flow(); + if (remaining <= 0) { + continue; + } + + for (PhysicalInput physicalInput : aggregatedInputs.get(inputIndex).physicalInputs) { + if (remaining <= 0) { + break; + } + int amount = Math.min(remaining, physicalInput.amount); + assignments.add(new Assignment(physicalInput.index, amount)); + remaining -= amount; + } + if (remaining != 0) { + throw new IllegalStateException("Aggregated item input could not be mapped to physical slots"); + } + } + + assignments.sort(Comparator.comparingInt(Assignment::inputIndex)); + return ObjectLists.unmodifiable(assignments); + } + + /** + * 匹配一项需求,数量可来自多个输入槽。 + */ + public static @Nullable ObjectList match(Ingredient ingredient, int count, + ObjectList inputs) { + return match(ObjectLists.singleton(new Requirement(ingredient, count)), inputs); + } + + /** 一步把实际槽位分配映射成配方使用的类型。 */ + public static @Nullable ObjectList mapAssignments( + @Nullable ObjectList assignments, + BiFunction factory) { + if (assignments == null) { + return null; + } + ObjectList mapped = new ObjectArrayList<>(assignments.size()); + for (Assignment assignment : assignments) { + mapped.add(factory.apply(assignment.inputIndex(), assignment.amount())); + } + return ObjectLists.unmodifiable(mapped); + } + + private static boolean acceptsAny(ObjectList requirements, ItemStack stack) { + for (CountedRequirement requirement : requirements) { + if (requirement.ingredient().test(stack)) { + return true; + } + } + return false; + } + + /** 匹配器用物品条件与正数消耗量计算各槽位的分配。实现方负责校验输入。 */ + public interface CountedRequirement { + + /** 提供对归并后物品栈生效的匹配条件。 */ + Ingredient ingredient(); + + /** 返回消耗的物品数量。 */ + int count(); + } + + /** 一项物品谓词及其需求总数。 */ + public record Requirement(Ingredient ingredient, int count) implements CountedRequirement { + + /** 创建带数量的原版配料需求。数量须为正数。 */ + public Requirement { + if (ingredient.isEmpty()) { + throw new IllegalArgumentException("Counted item requirement must not be empty"); + } + if (count <= 0) { + throw new IllegalArgumentException("Counted item requirement count must be positive: " + count); + } + } + } + + /** + * 一个输入槽位及其消耗的物品数量。 + */ + public record Assignment(int inputIndex, int amount) { + + /** 将一部分输入分配给需求。输入索引从零开始,分配数量须为正数。 */ + public Assignment { + if (inputIndex < 0) { + throw new IllegalArgumentException("Input slot index must not be negative: " + inputIndex); + } + if (amount <= 0) { + throw new IllegalArgumentException("Input assignment amount must be positive: " + amount); + } + } + } + + private static ObjectList aggregate(ObjectList inputs) { + ObjectList aggregated = new ObjectArrayList<>(); + for (int index = 0; index < inputs.size(); index++) { + ItemStack stack = inputs.get(index); + if (stack.isEmpty()) { + continue; + } + + AggregatedInput existing = null; + for (AggregatedInput candidate : aggregated) { + if (ItemStack.isSameItemSameComponents(candidate.stack, stack)) { + existing = candidate; + break; + } + } + if (existing == null) { + aggregated.add(new AggregatedInput(stack, index)); + } else { + existing.add(stack, index); + } + } + return aggregated; + } + + private static final class AggregatedInput { + + private final ItemStack stack; + private final ObjectList physicalInputs = new ObjectArrayList<>(); + private int count; + + private AggregatedInput(ItemStack stack, int index) { + this.stack = stack.copy(); + this.count = stack.getCount(); + this.physicalInputs.add(new PhysicalInput(index, stack.getCount())); + } + + private void add(ItemStack stack, int index) { + this.count = Math.addExact(this.count, stack.getCount()); + this.stack.setCount(this.count); + this.physicalInputs.add(new PhysicalInput(index, stack.getCount())); + } + } + + private record PhysicalInput(int index, int amount) {} + + private static final class FlowNetwork { + + private final ObjectList> graph; + private final int[] levels; + private final int[] cursors; + + private FlowNetwork(int nodeCount) { + this.graph = new ObjectArrayList<>(nodeCount); + for (int index = 0; index < nodeCount; index++) { + this.graph.add(new ObjectArrayList<>()); + } + this.levels = new int[nodeCount]; + this.cursors = new int[nodeCount]; + } + + private Edge addEdge(int from, int to, int capacity) { + Edge forward = new Edge(to, capacity, this.graph.get(to).size()); + Edge reverse = new Edge(from, 0, this.graph.get(from).size()); + this.graph.get(from).add(forward); + this.graph.get(to).add(reverse); + return forward; + } + + private int maxFlow(int source, int sink) { + int result = 0; + while (buildLevels(source, sink)) { + Arrays.fill(this.cursors, 0); + int pushed; + while ((pushed = push(source, sink, Integer.MAX_VALUE)) > 0) { + result = Math.addExact(result, pushed); + } + } + return result; + } + + private boolean buildLevels(int source, int sink) { + Arrays.fill(this.levels, -1); + int[] queue = new int[this.graph.size()]; + int head = 0; + int tail = 0; + queue[tail++] = source; + this.levels[source] = 0; + while (head < tail) { + int node = queue[head++]; + for (Edge edge : this.graph.get(node)) { + if (edge.capacity > 0 && this.levels[edge.to] < 0) { + this.levels[edge.to] = this.levels[node] + 1; + queue[tail++] = edge.to; + } + } + } + return this.levels[sink] >= 0; + } + + private int push(int node, int sink, int amount) { + if (node == sink) { + return amount; + } + ObjectList edges = this.graph.get(node); + for (; this.cursors[node] < edges.size(); this.cursors[node]++) { + Edge edge = edges.get(this.cursors[node]); + if (edge.capacity <= 0 || this.levels[edge.to] != this.levels[node] + 1) { + continue; + } + int pushed = push(edge.to, sink, Math.min(amount, edge.capacity)); + if (pushed <= 0) { + continue; + } + edge.capacity -= pushed; + Edge reverse = this.graph.get(edge.to).get(edge.reverseIndex); + reverse.capacity += pushed; + return pushed; + } + return 0; + } + + private static final class Edge { + + private final int to; + private final int originalCapacity; + private int capacity; + private final int reverseIndex; + + private Edge(int to, int capacity, int reverseIndex) { + this.to = to; + this.capacity = capacity; + this.originalCapacity = capacity; + this.reverseIndex = reverseIndex; + } + + private int flow() { + return this.originalCapacity - this.capacity; + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/recipe/ShapedRecipePatterns.java b/src/main/java/com/modularmc/mmclutils/api/recipe/ShapedRecipePatterns.java new file mode 100644 index 0000000..ff1267c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/recipe/ShapedRecipePatterns.java @@ -0,0 +1,101 @@ +package com.modularmc.mmclutils.api.recipe; + +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.ShapedRecipePattern; + +import it.unimi.dsi.fastutil.chars.Char2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.chars.Char2ObjectMaps; +import it.unimi.dsi.fastutil.objects.Object2CharOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.ToIntFunction; + +/** 将原版有序材料表转换为带稳定字符键的配方图案。 */ +public final class ShapedRecipePatterns { + + private ShapedRecipePatterns() {} + + /** + * 将原版有序配方输入转换为稳定字符表和行。 + * + * @param pattern 原版有序配方图案 + * @return 按材料首次出现顺序分配字符的图案 + */ + public static Pattern of(ShapedRecipePattern pattern) { + return of(pattern.ingredients(), pattern.width(), pattern.height()); + } + + /** + * 按材料首次出现顺序从 A 开始分配字符并构建配方行。 + * + * @param ingredients 按行排列的可选材料 + * @param width 配方宽度 + * @param height 配方高度 + * @return 稳定的配方行与只读字符表 + * @throws IllegalArgumentException 配方尺寸无效,或不同材料多于可用字符数 + */ + public static Pattern of(List> ingredients, int width, int height) { + var symbols = new Object2CharOpenHashMap(); + var keys = new Char2ObjectLinkedOpenHashMap(); + ToIntFunction nextSymbol = ingredient -> { + int symbol = 'A' + keys.size(); + if (symbol > Character.MAX_VALUE) throw new IllegalArgumentException("配方中的不同材料超出可用字符数量"); + keys.put((char) symbol, ingredient); + return symbol; + }; + List rows = buildRows(ingredients, width, height, ingredient -> symbols.computeIfAbsent(ingredient, nextSymbol)); + return new Pattern(rows, Char2ObjectMaps.unmodifiable(keys)); + } + + /** + * 用已有字符表重建配方行。同一材料对应多个字符时使用映射迭代顺序中最先出现的字符。 + * + * @param ingredients 按行排列的可选材料 + * @param width 配方宽度 + * @param height 配方高度 + * @param keys 字符到材料的映射,空格字符保留给空槽 + * @return 按配方行顺序生成的字符串列表 + * @throws IllegalArgumentException 配方尺寸无效、字符表包含空格键或缺少材料映射 + */ + public static List rows(List> ingredients, int width, int height, Map keys) { + var symbols = new Object2CharOpenHashMap(keys.size()); + symbols.defaultReturnValue(' '); + keys.forEach((symbol, ingredient) -> { + if (symbol == ' ') throw new IllegalArgumentException("空格保留给配方图案中的空槽"); + symbols.putIfAbsent(ingredient, symbol.charValue()); + }); + return buildRows(ingredients, width, height, ingredient -> { + char symbol = symbols.getChar(ingredient); + if (symbol == ' ') throw new IllegalArgumentException("配方字符表缺少材料 " + ingredient); + return symbol; + }); + } + + private static List buildRows(List> ingredients, int width, int height, ToIntFunction symbol) { + if (width <= 0 || height <= 0 || (long) width * height != ingredients.size()) { + throw new IllegalArgumentException("配方尺寸与材料数量不匹配"); + } + var inputs = ingredients.iterator(); + List rows = new ObjectArrayList<>(height); + for (int y = 0; y < height; y++) { + var line = new StringBuilder(width); + for (int x = 0; x < width; x++) { + var input = inputs.next(); + line.append(input.isEmpty() ? ' ' : (char) symbol.applyAsInt(input.orElseThrow())); + } + rows.add(line.toString()); + } + return List.copyOf(rows); + } + + /** + * 有序配方行及其字符到材料的映射。 + * + * @param rows 每行一个字符串,空槽以空格表示 + * @param keys 字符到非空材料的映射 + */ + public record Pattern(List rows, Map keys) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/AsyncLane.java b/src/main/java/com/modularmc/mmclutils/api/schedule/AsyncLane.java new file mode 100644 index 0000000..be34687 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/AsyncLane.java @@ -0,0 +1,175 @@ +package com.modularmc.mmclutils.api.schedule; + +import com.modularmc.mmclutils.api.level.LevelStore; + +import net.minecraft.world.level.Level; + +import com.mojang.logging.LogUtils; +import org.slf4j.Logger; + +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.Executor; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 将一个维度的调度轮次提交到指定 Executor,并在同一维度上跳过尚未完成的轮次。 + * 调度任务在传入的执行器线程运行,除提交线程安全的调度操作外,不应直接读取游戏线程状态。 + * 执行器由创建方管理,本类只在维度卸载时关闭该维度的调度器。 + */ +public final class AsyncLane { + + private static final Logger LOGGER = LogUtils.getLogger(); + private static volatile AsyncLane[] lanes = new AsyncLane[0]; + + /** 使用库默认后台线程池的异步车道。 */ + public static final AsyncLane DEFAULT = create("mmclutils:default", defaultExecutor()); + + private final String id; + private final Executor executor; + private final LevelStore runners; + + private AsyncLane(String id, Executor executor) { + this.id = id; + this.executor = executor; + this.runners = LevelStore.createWithLevel(level -> new Runner(this), Runner::close); + } + + /** + * 创建并登记全局唯一标识的异步车道。 + * + * @param id 用于诊断和区分车道的标识 + * @param executor 提交异步调度轮次的执行器,生命周期由调用方管理 + * @return 新登记的车道 + * @throws NullPointerException 标识或执行器为空 + * @throws IllegalArgumentException 已有车道使用相同标识 + */ + public static synchronized AsyncLane create(String id, Executor executor) { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(executor, "executor"); + for (AsyncLane lane : lanes) { + if (lane.id.equals(id)) throw new IllegalArgumentException("duplicate async lane " + id); + } + AsyncLane lane = new AsyncLane(id, executor); + AsyncLane[] grown = Arrays.copyOf(lanes, lanes.length + 1); + grown[lanes.length] = lane; + lanes = grown; + return lane; + } + + /** + * 创建带指定名称前缀的守护型低优先级工作线程。 + * + * @param name 线程名前缀 + * @return 用于异步车道的线程工厂 + */ + public static ThreadFactory threadFactory(String name) { + AtomicInteger count = new AtomicInteger(); + return r -> { + Thread t = new Worker(r, name + "-" + count.getAndIncrement()); + t.setDaemon(true); + t.setPriority(Thread.MIN_PRIORITY); + return t; + }; + } + + /** 判断当前线程是否由 {@link #threadFactory(String)} 创建。 */ + public static boolean isWorkerThread() { + return Thread.currentThread() instanceof Worker; + } + + /** 返回该车道的诊断标识。 */ + public String id() { + return id; + } + + TickScheduler scheduler(Level level) { + if (LevelStore.isReleased(level)) return TickScheduler.CLOSED; + return runners.get(level).scheduler; + } + + static void kickAll(Level level) { + for (AsyncLane lane : lanes) { + Runner runner = lane.runners.getIfPresent(level); + if (runner != null) runner.kick(); + } + } + + private static Executor defaultExecutor() { + int threads = Math.max(1, Runtime.getRuntime().availableProcessors() - 1); + ThreadPoolExecutor executor = new ThreadPoolExecutor(threads, threads, 30, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(), threadFactory("mmclutils-async")); + executor.allowCoreThreadTimeOut(true); + return executor; + } + + @Override + public String toString() { + return id; + } + + private static final class Worker extends Thread { + + Worker(Runnable r, String name) { + super(r, name); + } + } + + private static final class Runner implements Runnable { + + final AsyncLane lane; + final TickScheduler scheduler; + final AtomicBoolean running = new AtomicBoolean(); + long skipped; + + Runner(AsyncLane lane) { + this.lane = lane; + this.scheduler = new TickScheduler(false, (error, owner) -> LOGGER.error("异步调度 {} 执行任务失败,所有者为 {}", lane.id, owner, error)); + } + + void kick() { + if (scheduler.isClosed() || !running.compareAndSet(false, true)) { + if (!scheduler.isClosed()) skipped++; + return; + } + if (scheduler.advanceIfIdle()) { + running.set(false); + return; + } + try { + lane.executor.execute(this); + } catch (RejectedExecutionException e) { + running.set(false); + LOGGER.warn("异步车道 {} 拒绝执行本轮任务", lane.id, e); + } + } + + @Override + public void run() { + try { + scheduler.runRound(); + } finally { + running.set(false); + } + } + + void close() { + scheduler.close(); + if (running.compareAndSet(false, true)) { + scheduler.clear(); + running.set(false); + } + } + + @Override + public String toString() { + return lane.id + " skipped=" + skipped; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/BatchProgress.java b/src/main/java/com/modularmc/mmclutils/api/schedule/BatchProgress.java new file mode 100644 index 0000000..5f22988 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/BatchProgress.java @@ -0,0 +1,44 @@ +package com.modularmc.mmclutils.api.schedule; + +/** + * 计算状态维持不变的一段推进量,并在本次完成边界处停下。 + */ +public final class BatchProgress { + + private BatchProgress() {} + + /** + * 推进到可用 Tick 用完或本轮完成。 + * + * @param progress 当前进度,范围为 {@code [0, duration)} + * @param duration 完成一次所需的正数 Tick 数 + * @param availableTicks 本批次可用的正数 Tick 数 + * @return 消耗的 Tick 数、推进后的进度及是否到达完成边界 + */ + public static Segment advanceToBoundary(int progress, int duration, int availableTicks) { + if (duration <= 0) { + throw new IllegalArgumentException("duration must be positive"); + } + if (progress < 0 || progress >= duration) { + throw new IllegalArgumentException("progress must be within [0, duration)"); + } + if (availableTicks <= 0) { + throw new IllegalArgumentException("availableTicks must be positive"); + } + + int ticksToBoundary = duration - progress; + if (availableTicks < ticksToBoundary) { + return new Segment(availableTicks, progress + availableTicks, false); + } + return new Segment(ticksToBoundary, 0, true); + } + + /** + * 一次状态连续的推进结果。 + * + * @param elapsedTicks 本次消耗的 Tick 数 + * @param progress 推进后的进度,到达完成边界时归零 + * @param reachedBoundary 是否完成了当前周期 + */ + public record Segment(int elapsedTicks, int progress, boolean reachedBoundary) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/BoundedVirtualTaskQueue.java b/src/main/java/com/modularmc/mmclutils/api/schedule/BoundedVirtualTaskQueue.java new file mode 100644 index 0000000..35a9976 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/BoundedVirtualTaskQueue.java @@ -0,0 +1,265 @@ +package com.modularmc.mmclutils.api.schedule; + +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import lombok.Getter; +import org.jspecify.annotations.Nullable; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +/** + * 由所属线程提交、轮询和取消虚拟线程任务。结果队列有容量限制,计算线程只使用 Work 上下文。 + * 结果发出后归队列所有,轮询交付后由调用方释放。 + * 作废结果可能在计算线程或所属线程释放。释放动作须支持并发调用,并可脱离 GPU 上下文执行。 + * + * @param 从计算线程交付的结果值类型 + */ +public final class BoundedVirtualTaskQueue implements AutoCloseable { + + private final int parallelism; + private final Consumer release; + private final ExecutorService executor; + private final Semaphore workers; + private final Semaphore resultSlots; + private final Object handoff = new Object(); + private final ConcurrentLinkedQueue> results = new ConcurrentLinkedQueue<>(); + private final Long2ObjectOpenHashMap tasks = new Long2ObjectOpenHashMap<>(); + private long generation; + private boolean closed; + + /** + * 建立由调用线程维护的队列。 + * + * @param threadPrefix 后台虚拟线程名称的前缀 + * @param parallelism 最多同时运行的计算数 + * @param resultCapacity 等待领取的结果数上限,包含终止结果 + * @param release 释放已作废结果的操作,须支持并发调用 + * @throws IllegalArgumentException 并发数或结果容量小于一 + */ + public BoundedVirtualTaskQueue(String threadPrefix, int parallelism, int resultCapacity, Consumer release) { + if (parallelism < 1 || resultCapacity < 1) throw new IllegalArgumentException("Task queue limits must be positive"); + this.parallelism = parallelism; + this.release = release; + workers = new Semaphore(parallelism); + resultSlots = new Semaphore(resultCapacity); + executor = Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name(threadPrefix, 0).factory()); + } + + /** 在所属线程查询提交容量。已完成的任务在终止结果被取走之前仍占用名额。 */ + public boolean hasCapacity() { + return !closed && tasks.size() < parallelism && workers.availablePermits() > 0; + } + + /** 查询指定原始类型键当前是否有任务。 */ + public boolean contains(long key) { + return tasks.containsKey(key); + } + + /** + * 在所属线程提交任务。每个键在终止结果被取走或任务取消后可复用。 + * + * @param key 用于取消和关联结果的任务键 + * @param calculation 在后台线程执行的计算,可以通过工作上下文交付多条结果 + * @throws IllegalStateException 队列已关闭、没有空余任务名额或键已在使用 + */ + public void submit(long key, Consumer> calculation) { + if (!hasCapacity() || tasks.containsKey(key) || !workers.tryAcquire()) throw new IllegalStateException("No task slot or duplicate task key: " + key); + var ticket = new Ticket(key, generation); + var work = new Work<>(this, ticket); + FutureTask future = new FutureTask<>(() -> { + try { + work.checkCancelled(); + calculation.accept(work); + work.publish(null, null, true); + } catch (RuntimeException | Error failure) { + if (ticket.cancelled.get() || Thread.currentThread().isInterrupted()) ticket.cancelled.set(true); + else { + try { + work.publish(null, failure, true); + } catch (CancellationException stopped) { + ticket.cancelled.set(true); + } + } + } + return Boolean.TRUE; + }); + ticket.future = future; + tasks.put(key, ticket); + try { + executor.execute(() -> { + if (!ticket.started.compareAndSet(false, true)) return; + try { + future.run(); + } finally { + workers.release(); + } + }); + } catch (RuntimeException | Error failure) { + tasks.remove(key); + if (ticket.started.compareAndSet(false, true)) workers.release(); + throw failure; + } + } + + /** + * 在所属线程轮询结果。普通结果一经返回,调用方负责释放其值。 + * 终止结果可以携带计算异常。已取消或作废的结果由队列释放。 + * + * @return 下一条有效结果,暂时没有可领结果时返回空值 + */ + public @Nullable Result poll() { + Envelope envelope; + while ((envelope = results.poll()) != null) { + resultSlots.release(); + Ticket ticket = envelope.ticket(); + Result result = envelope.result(); + if (ticket.generation != generation || !tasks.containsKey(ticket.key) || tasks.get(ticket.key) != ticket) { + if (result.value() != null) release.accept(result.value()); + continue; + } + if (result.terminal()) tasks.remove(ticket.key); + return result; + } + var iterator = tasks.long2ObjectEntrySet().fastIterator(); + while (iterator.hasNext()) { + var entry = iterator.next(); + Ticket ticket = entry.getValue(); + if (ticket.cancelled.get() && ticket.future.isDone()) { + long key = entry.getLongKey(); + iterator.remove(); + return new Result<>(key, null, new CancellationException("Worker stopped without publishing a result"), true); + } + } + return null; + } + + /** 作废指定键并中断计算,立即释放尚未取走的结果。 */ + public void cancel(long key) { + if (!tasks.containsKey(key)) return; + Ticket ticket = tasks.remove(key); + synchronized (handoff) { + ticket.cancelled.set(true); + ticket.future.cancel(true); + if (ticket.started.compareAndSet(false, true)) workers.release(); + results.removeIf(envelope -> { + if (envelope.ticket() != ticket) return false; + if (envelope.result().value() != null) release.accept(envelope.result().value()); + resultSlots.release(); + return true; + }); + } + } + + /** 切换到下一代,取消全部任务并释放队列中的结果。 */ + public void clear() { + generation++; + for (long key : tasks.keySet().toLongArray()) cancel(key); + } + + /** 关闭任务入口并中断计算线程。所属线程可立即返回。 */ + @Override + public void close() { + clear(); + closed = true; + executor.shutdownNow(); + } + + /** + * 为后台计算提供取消状态和结果交付入口。工作上下文仅在本次计算期间使用。 + * + * @param 本次计算交付的结果值类型 + */ + public static final class Work { + + private final BoundedVirtualTaskQueue owner; + private final Ticket ticket; + /** 与提交时相同的任务键。 */ + @Getter + private final long key; + + private Work(BoundedVirtualTaskQueue owner, Ticket ticket) { + this.owner = owner; + this.ticket = ticket; + key = ticket.key; + } + + /** 供计算循环检查取消或中断状态。 */ + public boolean cancelled() { + return ticket.cancelled.get() || Thread.currentThread().isInterrupted(); + } + + /** 任务作废或计算线程中断时抛出取消异常。 */ + public void checkCancelled() { + if (cancelled()) throw new CancellationException(); + } + + /** + * 交付一个非空结果,队列满时可中断地等待。结果一经传入即转交所有权。 + * 若交付因取消或其它异常失败,由该方法释放结果。 + * + * @param value 由计算线程交出的结果值 + * @throws CancellationException 任务已取消或计算线程被中断 + */ + public void emit(T value) { + try { + publish(value, null, false); + } catch (RuntimeException | Error failure) { + owner.release.accept(value); + throw failure; + } + } + + private void publish(@Nullable T value, @Nullable Throwable failure, boolean terminal) { + checkCancelled(); + try { + owner.resultSlots.acquire(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new CancellationException(); + } + boolean transferred = false; + try { + synchronized (owner.handoff) { + checkCancelled(); + owner.results.add(new Envelope<>(ticket, new Result<>(key, value, failure, terminal))); + transferred = true; + } + } finally { + if (!transferred) owner.resultSlots.release(); + } + } + } + + /** + * 由所属线程接收的任务数据或终止通知。 + * + * @param 普通结果的值类型 + * @param key 提交任务时的键 + * @param value 普通结果的非空值,终止时为空 + * @param failure 终止原因,计算成功时为空 + * @param terminal 本条结果是否标记任务结束 + */ + public record Result(long key, @Nullable T value, @Nullable Throwable failure, boolean terminal) {} + + private record Envelope(Ticket ticket, Result result) {} + + private static final class Ticket { + + private final long key; + private final long generation; + private final AtomicBoolean cancelled = new AtomicBoolean(); + private final AtomicBoolean started = new AtomicBoolean(); + private FutureTask future = new FutureTask<>(() -> Boolean.FALSE); + + private Ticket(long key, long generation) { + this.key = key; + this.generation = generation; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/Cadence.java b/src/main/java/com/modularmc/mmclutils/api/schedule/Cadence.java new file mode 100644 index 0000000..8884cf3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/Cadence.java @@ -0,0 +1,81 @@ +package com.modularmc.mmclutils.api.schedule; + +/** + * 以 Tick 为单位的周期与相位设置,供 {@link TickScheduler} 创建周期任务。 + * 自动相位会轮流分配任务在各周期中的执行 Tick。 + */ +public final class Cadence { + + private static final int AUTO = -1; + private static final Cadence[] CACHED = new Cadence[129]; + + static { + for (int p = 1; p < CACHED.length; p++) CACHED[p] = new Cadence(p, AUTO); + } + + /** 每个 Tick 执行一次的周期设置。 */ + public static final Cadence EVERY_TICK = CACHED[1]; + + private final int period; + private final int phase; + + private Cadence(int period, int phase) { + this.period = period; + this.phase = phase; + } + + /** + * 创建指定周期并采用自动相位的设置。周期小于一时按一处理。 + * + * @param period 周期 Tick 数 + * @return 可供周期任务使用的设置 + */ + public static Cadence every(int period) { + int p = Math.max(1, period); + return p < CACHED.length ? CACHED[p] : new Cadence(p, AUTO); + } + + /** + * 返回使用指定相位的设置,相位会规范化到 {@code [0, period)}。 + * + * @param phase 周期内的执行相位 + * @return 具有规范化固定相位的新设置 + */ + public Cadence phase(int phase) { + return new Cadence(period, Math.floorMod(phase, period)); + } + + /** 返回每次执行之间的 Tick 数,至少为一。 */ + public int period() { + return period; + } + + /** 判断此设置是否让调度器自动分配周期相位。 */ + public boolean isAutoPhase() { + return phase == AUTO; + } + + /** + * 返回固定相位,自动相位时返回内部标记值。 + * + * @return 固定相位或自动相位标记 + */ + public int phase() { + return phase; + } + + @Override + public boolean equals(Object o) { + return o instanceof Cadence c && c.period == period && c.phase == phase; + } + + @Override + public int hashCode() { + return period * 31 + phase; + } + + @Override + public String toString() { + return phase == AUTO ? "every " + period : "every " + period + " at " + phase; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/Cell.java b/src/main/java/com/modularmc/mmclutils/api/schedule/Cell.java new file mode 100644 index 0000000..03be085 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/Cell.java @@ -0,0 +1,149 @@ +package com.modularmc.mmclutils.api.schedule; + +import org.jspecify.annotations.Nullable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.Objects; + +/** + * 带值的依赖信号:读即追踪、写即触发,不必手写成对的 {@link Signal#track} 与 {@link Signal#emit}。功能: + *
    + *
  • {@link #get}:取值;在派生函数求值期间调用时自动成为该派生的依赖;派生以外的每 tick 热路径用 {@link #peek}
  • + *
  • {@link #peek}:取值但不成为依赖
  • + *
  • {@link #set}:按 equals 比较,值变了才写入并触发,返回是否变了;在订阅方车道以外的线程上调用时照 {@link Signal#emit} 的规矩转投并记一次误用
  • + *
  • {@link #post}:可从任意线程写入:在订阅方车道的线程上等同 {@link #set};在别的线程上把值暂存并转投到车道,同一轮里多次写入只生效最后一个,不记误用;车道线程上的 post + * 会作废还没生效的暂存值;车道已关闭时直接写入、不触发
  • + *
  • 还没有订阅者时任何线程上的 post + * 都直接写入;与另一条车道上"先读值、后订阅"的派生同时发生时不会丢:订阅方在首次订阅时发现被别的线程写过,就在下一轮补一次触发,写入方在写完后发现已有订阅,就向订阅方车道转投一次触发
  • + *
  • 暂存后车道关闭、暂存值没来得及生效时,下一个首次订阅把它落进值里并在下一轮触发
  • + *
  • {@link #changed}:值变化时触发的信号,供 {@link Scope#listen} 使用
  • + *
+ */ +public final class Cell { + + private static final Object NONE = new Object(); + private static final VarHandle PENDING; + + static { + try { + PENDING = MethodHandles.lookup().findVarHandle(Cell.class, "pending", Object.class); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + private final Changed changed = new Changed(this); + private T value; + @SuppressWarnings("unused") + private volatile Object pending = NONE; + private volatile @Nullable TickScheduler relay; + private volatile boolean unseen; + + private Cell(T value) { + this.value = value; + } + + /** 以给定初始值创建状态单元。需要跨线程更新时使用 {@link #post}。 */ + public static Cell of(T initial) { + return new Cell<>(initial); + } + + /** 读取当前值。若正在计算派生值,同时把此读取登记到依赖列表。 */ + public T get() { + changed.track(); + return value; + } + + /** 读取当前值而跳过依赖跟踪。 */ + public T peek() { + return value; + } + + /** 同步更新状态。值变化时发出变更信号并返回 {@code true}。 */ + public boolean set(T next) { + if (Objects.equals(value, next)) return false; + value = next; + changed.emit(); + return true; + } + + /** 从任意线程投递更新。跨线程投递由所属调度器合并,同一轮使用最后投递的值。 */ + public void post(T next) { + TickScheduler lane = changed.home(); + if (lane == null) { + postUnsubscribed(next); + return; + } + if (!lane.foreign()) { + if (pending != NONE) PENDING.setVolatile(this, NONE); + set(next); + return; + } + if (lane.isClosed()) { + PENDING.setVolatile(this, NONE); + value = next; + return; + } + if (PENDING.getAndSet(this, next) != NONE) { + TickScheduler queued = relay; + if (queued != null && !queued.isClosed()) return; + } + relay = lane; + lane.schedule(0, null, this::flush); + } + + private void postUnsubscribed(T next) { + if (pending != NONE) PENDING.setVolatile(this, NONE); + if (Objects.equals(value, next)) return; + value = next; + unseen = true; + TickScheduler lane = changed.home(); + if (lane == null) return; + if (lane.foreign()) lane.schedule(0, null, changed::emit); + else changed.emit(); + } + + @SuppressWarnings("unchecked") + private void flush() { + Object next = PENDING.getAndSet(this, NONE); + if (next != NONE) set((T) next); + } + + @SuppressWarnings("unchecked") + private void subscribed(TickScheduler lane) { + boolean dirty = false; + if (unseen) { + unseen = false; + dirty = true; + } + if (pending != NONE) { + Object next = PENDING.getAndSet(this, NONE); + if (next != NONE && !Objects.equals(value, next)) { + value = (T) next; + dirty = true; + } + } + if (dirty) lane.schedule(0, null, changed::emit); + } + + /** 取得此状态单元共用的变更信号。 */ + public Signal changed() { + return changed; + } + + static final class Changed extends Signal { + + private final Cell cell; + + Changed(Cell cell) { + this.cell = cell; + } + + @Override + void firstSubscribed() { + TickScheduler lane = home(); + if (lane != null) cell.subscribed(lane); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/CoalescedTask.java b/src/main/java/com/modularmc/mmclutils/api/schedule/CoalescedTask.java new file mode 100644 index 0000000..1acc68d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/CoalescedTask.java @@ -0,0 +1,98 @@ +package com.modularmc.mmclutils.api.schedule; + +import org.jspecify.annotations.Nullable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.Objects; + +/** + * 可重复提交而在任一时刻只排队一次的任务。 + * 实例可跨线程提交和取消,但其动作始终在所属 {@link TickScheduler} 的驱动线程运行。 + */ +public final class CoalescedTask { + + private static final VarHandle QUEUED; + + static { + try { + QUEUED = MethodHandles.lookup().findVarHandle(CoalescedTask.class, "queuedIn", TickScheduler.class); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + private final @Nullable Object owner; + private final Runnable action; + volatile TickScheduler.Entry entry; + boolean lagging; + @SuppressWarnings("unused") + private volatile @Nullable TickScheduler queuedIn; + + /** 创建无所有者的合并任务。 */ + public CoalescedTask(Runnable action) { + this(null, action); + } + + /** + * 创建带所有者的合并任务,供崩溃报告识别任务来源。 + * + * @param owner 可选任务所有者 + * @param action 被调度的操作 + * @throws NullPointerException 操作为空 + */ + public CoalescedTask(@Nullable Object owner, Runnable action) { + this.owner = owner; + this.action = Objects.requireNonNull(action, "action"); + this.entry = TickScheduler.coalescedEntry(this, owner, action); + } + + /** 查询此任务是否已进入尚未关闭的调度器队列。 */ + public boolean isQueued() { + TickScheduler s = queuedIn(); + return s != null && !s.isClosed(); + } + + /** 取消当前排队的执行;之后仍可重新提交此任务。 */ + public void cancel() { + TickScheduler s = queuedIn(); + if (s == null) return; + TickScheduler.Entry old = entry; + entry = TickScheduler.coalescedEntry(this, owner, action); + old.cancel(); + QUEUED.compareAndSet(this, s, null); + } + + void retire() { + entry.cancel(); + } + + void submitTo(TickScheduler scheduler, int delay) { + while (true) { + TickScheduler current = queuedIn(); + if (current != null && !current.isClosed()) return; + if (scheduler.isClosed()) return; + if (QUEUED.compareAndSet(this, current, scheduler)) break; + } + scheduler.enqueueCoalesced(this, delay); + } + + @Nullable + TickScheduler queuedIn() { + return (TickScheduler) QUEUED.getVolatile(this); + } + + boolean dequeue(TickScheduler scheduler) { + return QUEUED.compareAndSet(this, scheduler, null); + } + + TickScheduler.Entry entryForLink(TickScheduler scheduler) { + TickScheduler.Entry e = entry; + if (e.linked || !e.active) { + e = TickScheduler.coalescedEntry(this, owner, action); + entry = e; + } + e.scheduler = scheduler; + return e; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/KeyedSignal.java b/src/main/java/com/modularmc/mmclutils/api/schedule/KeyedSignal.java new file mode 100644 index 0000000..8011337 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/KeyedSignal.java @@ -0,0 +1,101 @@ +package com.modularmc.mmclutils.api.schedule; + +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 按键分片的依赖信号:派生只依赖读到的那几个键,触发一个键只让追踪了它的派生重算。功能: + *
    + *
  • {@link #track}:在派生函数求值期间调用时,把这个键记为该派生的依赖;不在求值期间调用时什么也不做、不建任何东西
  • + *
  • {@link #emit}:只让追踪了这个键的派生重算、监听执行;没有追踪者的键直接返回;线程规矩与 {@link Signal#emit} + * 相同;在别的线程上触发时转投到车道,到车道线程上再按键重新查分片,期间分片被摘除又重建也能送到新的追踪者
  • + *
  • {@link #listen}:把监听挂在作用域上,这个键被触发时立即同步执行(顺序与规矩同 {@link Scope#listen}),作用域结束时自动摘除;作用域已结束或订阅失败时不留分片
  • + *
  • {@link #emitAll}:触发全部有追踪者的键
  • + *
  • 每个键的分片在第一个派生追踪时建立,最后一个追踪者退订时摘除,键大量出现又消失后不留东西;追踪后订阅失败(例如另一个线程上的车道来订阅同一个键)时分片也会摘除;{@link #keyCount} 是当前有分片的键数
  • + *
  • 键按 equals 区分,不得为 null
  • + *
+ */ +public final class KeyedSignal { + + private final ConcurrentHashMap slots = new ConcurrentHashMap<>(); + + /** 在派生值计算中登记对指定键的依赖。没有活动计算时直接返回。 */ + public void track(K key) { + Objects.requireNonNull(key, "key"); + if (!Signal.tracking()) return; + Slot slot = slots.get(key); + if (slot == null) { + Slot made = new Slot(this, key); + slot = slots.putIfAbsent(key, made); + if (slot == null) slot = made; + } + slot.track(); + } + + /** 订阅指定键的变化。注册随给定作用域结束而自动移除。 */ + public void listen(Scope scope, K key, Runnable listener) { + Objects.requireNonNull(scope, "scope"); + Objects.requireNonNull(key, "key"); + Slot slot = slots.get(key); + if (slot == null) { + Slot made = new Slot(this, key); + slot = slots.putIfAbsent(key, made); + if (slot == null) slot = made; + } + try { + scope.listen(slot, listener); + } finally { + slot.unclaimed(); + } + } + + /** 通知指定键的现有订阅者。 */ + public void emit(K key) { + Slot slot = slots.get(Objects.requireNonNull(key, "key")); + if (slot == null) return; + TickScheduler lane = slot.home(); + if (lane != null && lane.foreign()) { + Scope.anomaly("signal emitted off its lane thread", null); + lane.schedule(0, null, () -> emit(key)); + return; + } + slot.emit(); + } + + /** 通知所有当前有订阅者的键。 */ + public void emitAll() { + for (Slot slot : slots.values()) slot.emit(); + } + + /** 返回当前仍有信号条目的键数。 */ + public int keyCount() { + return slots.size(); + } + + static final class Slot extends Signal { + + private final KeyedSignal owner; + private final Object key; + + Slot(KeyedSignal owner, Object key) { + this.owner = owner; + this.key = key; + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + void firstSubscribed() { + ((ConcurrentHashMap) owner.slots).putIfAbsent(key, this); + } + + @Override + void lastUnsubscribed() { + owner.slots.remove(key, this); + } + + @Override + void unclaimed() { + if (subscriberCount() == 0) owner.slots.remove(key, this); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/Poll.java b/src/main/java/com/modularmc/mmclutils/api/schedule/Poll.java new file mode 100644 index 0000000..b2c08fe --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/Poll.java @@ -0,0 +1,50 @@ +package com.modularmc.mmclutils.api.schedule; + +/** + * 没有事件来源的读取用的周期信号。功能: + *
    + *
  • {@link #every}:在派生求值期间调用,让该派生每 period 轮重算一次;不在求值期间调用时什么也不做
  • + *
  • 同一车道上的派生按建立顺序分到周期内的各个相位,重查时刻互相错开,不会挤在同一轮;同一个派生每次重算落在同一个相位
  • + *
  • 同一车道同一周期同一相位共用一个信号,信号挂在车道上、随车道一起回收;有订阅时才挂周期任务,最后一个订阅消失即取消
  • + *
+ */ +public final class Poll { + + private Poll() {} + + /** 在派生计算中建立按给定周期触发的依赖。没有当次派生计算时直接返回。 */ + public static void every(int period) { + Signal.Frame frame = Signal.currentFrame(); + if (frame == null) return; + int p = Math.max(1, period); + frame.add(frame.lane.poll(p, Math.floorMod(frame.salt, p))); + } + + static PollSignal signal(TickScheduler lane, int period, int phase) { + return lane.poll(period, phase); + } + + static final class PollSignal extends Signal { + + private final TickScheduler lane; + private final int period; + private final int phase; + private Task task; + + PollSignal(TickScheduler lane, int period, int phase) { + this.lane = lane; + this.period = period; + this.phase = phase; + } + + @Override + void firstSubscribed() { + task = lane.repeat(Cadence.every(period).phase(phase), this::emit); + } + + @Override + void lastUnsubscribed() { + task = Task.cancel(task); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/PriorityTaskExecutor.java b/src/main/java/com/modularmc/mmclutils/api/schedule/PriorityTaskExecutor.java new file mode 100644 index 0000000..8147ca9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/PriorityTaskExecutor.java @@ -0,0 +1,55 @@ +package com.modularmc.mmclutils.api.schedule; + +import java.util.concurrent.Executor; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +/** 单线程执行异步计算。常规任务按登记顺序运行,优先任务可插入队首。 */ +public final class PriorityTaskExecutor implements Executor, AutoCloseable { + + private final AtomicLong order = new AtomicLong(); + private final ThreadPoolExecutor executor; + + /** 启动使用指定线程名的串行执行器。首个任务提交时才会创建工作线程。 */ + public PriorityTaskExecutor(String threadName) { + executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, + new PriorityBlockingQueue<>(), Thread.ofPlatform().daemon().name(threadName).factory()); + } + + @Override + public void execute(Runnable action) { + executor.execute(new Calculation(order.getAndIncrement(), action)); + } + + /** 返回一次性优先入口。首次提交进入优先队列,后续提交进入常规队列。 */ + public Executor firstExecutor() { + long priority = -order.getAndIncrement() - 1; + var first = new AtomicBoolean(true); + return action -> { + if (first.getAndSet(false)) executor.execute(new Calculation(priority, action)); + else execute(action); + }; + } + + /** 停止接收任务,取消队列并尝试中断运行中的任务。 */ + @Override + public void close() { + executor.shutdownNow(); + } + + private record Calculation(long order, Runnable action) implements Runnable, Comparable { + + @Override + public int compareTo(Calculation other) { + return Long.compare(order, other.order); + } + + @Override + public void run() { + action.run(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/PriorityTaskQueue.java b/src/main/java/com/modularmc/mmclutils/api/schedule/PriorityTaskQueue.java new file mode 100644 index 0000000..be0e476 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/PriorityTaskQueue.java @@ -0,0 +1,61 @@ +package com.modularmc.mmclutils.api.schedule; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectList; +import it.unimi.dsi.fastutil.objects.Reference2LongLinkedOpenHashMap; + +/** 由所属 Tick 线程维护的任务队列。按引用去重,到期任务按登记顺序取出。 */ +public final class PriorityTaskQueue { + + private final Reference2LongLinkedOpenHashMap dueTicks = new Reference2LongLinkedOpenHashMap<>(); + private long firstDueTick = Long.MAX_VALUE; + + /** 按引用登记任务。再次登记同一个对象会更新时间,保持队列中的原顺序。 */ + public void schedule(T task, long dueTick) { + dueTicks.put(task, dueTick); + firstDueTick = Math.min(firstDueTick, dueTick); + } + + /** 调整已有任务时间或将新任务放到队首。 */ + public void scheduleFirst(T task, long dueTick) { + dueTicks.putAndMoveToFirst(task, dueTick); + firstDueTick = Math.min(firstDueTick, dueTick); + } + + /** 从队列移除给定的任务对象。返回是否存在该对象。 */ + public boolean cancel(T task) { + if (!dueTicks.containsKey(task)) return false; + dueTicks.removeLong(task); + return true; + } + + /** 返回尚未取出或取消的任务个数。 */ + public int size() { + return dueTicks.size(); + } + + /** 取出截至指定轮次已到期的全部任务,结果按队列顺序排列。 */ + public ObjectList pollDue(long tick) { + if (tick < firstDueTick || dueTicks.isEmpty()) return ObjectList.of(); + var ready = new ObjectArrayList(); + firstDueTick = Long.MAX_VALUE; + var entries = dueTicks.reference2LongEntrySet().fastIterator(); + while (entries.hasNext()) { + var entry = entries.next(); + long due = entry.getLongValue(); + if (due <= tick) { + ready.add(entry.getKey()); + entries.remove(); + } else { + firstDueTick = Math.min(firstDueTick, due); + } + } + return ready; + } + + /** 丢弃排队的全部任务并重置最早到期时间。 */ + public void clear() { + dueTicks.clear(); + firstDueTick = Long.MAX_VALUE; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/ProgressTimer.java b/src/main/java/com/modularmc/mmclutils/api/schedule/ProgressTimer.java new file mode 100644 index 0000000..8f2cfed --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/ProgressTimer.java @@ -0,0 +1,52 @@ +package com.modularmc.mmclutils.api.schedule; + +import java.util.function.DoubleSupplier; + +/** + * 在一个以 Tick 配置的周期内提供从零到一的连续进度值。 + * 实例由调用方在单一线程访问,时间基于系统时钟而非游戏 Tick。 + */ +public class ProgressTimer implements DoubleSupplier { + + private final long msPerCycle; + private final int maxValue; + private final boolean countDown; + private long startTime; + + /** + * 创建指定周期长度和进度范围的计时器。 + * + * @param ticksPerCycle 一个周期包含的 Tick 数,必须为正数 + * @param maxValue 归一化前使用的正整数范围 + * @param countDown 为 {@code true} 时进度从一递减到零 + * @throws IllegalArgumentException 周期长度或进度范围不是正数 + */ + public ProgressTimer(int ticksPerCycle, int maxValue, boolean countDown) { + if (ticksPerCycle <= 0 || maxValue <= 0) throw new IllegalArgumentException("计时周期和进度范围须为正数"); + this.msPerCycle = (long) ticksPerCycle * 50; + this.maxValue = maxValue; + this.countDown = countDown; + this.startTime = System.currentTimeMillis(); + } + + /** 重置当前周期的起始时间,重新开始计时或倒计时。 */ + public void resetCountdown() { + startTime = System.currentTimeMillis(); + } + + /** 返回当前周期内归一化到零至一的进度。 */ + @Override + public double getAsDouble() { + return calculateTime(); + } + + private double calculateTime() { + long currentTime = System.currentTimeMillis(); + long msPassed = (currentTime - startTime) % msPerCycle; + double currentValue = (1.0 * msPassed * maxValue) / msPerCycle; + if (countDown) { + return (maxValue - currentValue) / maxValue; + } + return currentValue / maxValue; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/Schedulers.java b/src/main/java/com/modularmc/mmclutils/api/schedule/Schedulers.java new file mode 100644 index 0000000..78f3d70 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/Schedulers.java @@ -0,0 +1,151 @@ +package com.modularmc.mmclutils.api.schedule; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.api.level.LevelStore; + +import net.minecraft.CrashReport; +import net.minecraft.CrashReportCategory; +import net.minecraft.ReportedException; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.server.ServerAboutToStartEvent; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; +import net.neoforged.neoforge.event.tick.LevelTickEvent; +import net.neoforged.neoforge.event.tick.ServerTickEvent; + +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; + +/** + * 取各车道的调度器,并把它们接到 NeoForge 的 Tick 与生命周期事件上。功能: + *
    + *
  • {@link #of}:该维度的主线程车道,在维度 tick 结束时推进一轮;客户端与服务端的维度各一份,维度卸载时关闭
  • + *
  • {@link #async}:该维度的异步车道,每次主线程车道推进后若上一轮已结束就投给车道的线程池,没有到期任务时只推进轮次不占线程
  • + *
  • {@link #server}/{@link #client}:不属于某个维度的全服与客户端车道,分别在服务器 tick、客户端 tick 结束时推进;停服、断开连接时关闭并换成新的一份
  • + *
  • 主线程与全局车道的任务抛出异常时按原版方块实体的做法生成带所有者信息的崩溃报告,所有者是作用域时写上作用域的路径与标签;异步车道只记日志
  • + *
  • 主线程车道建立时就认领驱动它的线程:服务端维度认领服务器线程,客户端维度认领客户端主线程(在第一个客户端 tick 记下,进世界之前主菜单就已在 + * tick);全服车道在服务器即将启动时认领服务器线程,换新的客户端车道时认领客户端主线程;认领前别的线程上的 post、set、open 不会被误当成车道线程
  • + *
+ */ +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) +public final class Schedulers { + + private static final TickScheduler.FailureHandler CRASH = Schedulers::crash; + private static final LevelStore MAIN = LevelStore.createWithLevel(Schedulers::mainLane, TickScheduler::close); + private static volatile @Nullable Thread clientThread; + private static volatile TickScheduler server = new TickScheduler(true, CRASH); + private static volatile TickScheduler client = new TickScheduler(true, CRASH); + + private Schedulers() {} + + private static TickScheduler mainLane(Level level) { + TickScheduler lane = new TickScheduler(true, CRASH); + Thread owner = level instanceof ServerLevel serverLevel ? serverLevel.getServer().getRunningThread() : level.isClientSide() ? clientThread : null; + if (owner != null) lane.claim(owner); + return lane; + } + + /** + * 获取在维度 Tick 结束时推进的主线程调度器。 + * + * @param level 任务所属的维度 + * @return 对应维度的调度器,维度已卸载时返回关闭状态的调度器 + */ + public static TickScheduler of(Level level) { + if (LevelStore.isReleased(level)) return TickScheduler.CLOSED; + return MAIN.get(level); + } + + /** + * 获取此维度的默认异步调度器。任务访问世界时应使用由所属线程提前取得的独立数据。 + * + * @param level 任务所属的维度 + * @return 默认异步车道中对应维度的调度器 + */ + public static TickScheduler async(Level level) { + return AsyncLane.DEFAULT.scheduler(level); + } + + /** + * 获取指定异步车道的调度器。上一轮仍在执行时跳过本次推进。 + * + * @param level 任务所属的维度 + * @param lane 此任务使用的异步车道 + * @return 指定车道中对应维度的调度器 + */ + public static TickScheduler async(Level level, AsyncLane lane) { + return lane.scheduler(level); + } + + /** 返回由服务器主线程驱动的全局调度器。服务器停止后须重新获取。 */ + public static TickScheduler server() { + return server; + } + + /** 返回由物理客户端主线程驱动的全局调度器。连接断开后须重新获取。 */ + public static TickScheduler client() { + return client; + } + + /** 结束旧客户端调度器及其作用域,并创建空调度器供下一次连接使用。 */ + @ApiStatus.Internal + public static void resetClient() { + TickScheduler old = client; + TickScheduler fresh = new TickScheduler(true, CRASH); + Thread thread = clientThread; + if (thread != null) fresh.claim(thread); + client = fresh; + old.close(); + } + + @SubscribeEvent + private static void onServerAboutToStart(ServerAboutToStartEvent event) { + server.claim(event.getServer().getRunningThread()); + } + + @SubscribeEvent(priority = EventPriority.HIGH) + private static void onLevelTick(LevelTickEvent.Post event) { + Level level = event.getLevel(); + TickScheduler main = MAIN.getIfPresent(level); + if (main != null) main.runRound(); + AsyncLane.kickAll(level); + } + + @SubscribeEvent(priority = EventPriority.HIGH) + private static void onServerTick(ServerTickEvent.Post event) { + server.runRound(); + } + + /** 推进客户端调度器一轮。应在客户端 Tick 的结束阶段调用一次。 */ + @ApiStatus.Internal + public static void runClientTick() { + if (clientThread == null) { + clientThread = Thread.currentThread(); + client.claim(clientThread); + } + client.runRound(); + } + + @SubscribeEvent + private static void onServerStopped(ServerStoppedEvent event) { + TickScheduler old = server; + server = new TickScheduler(true, CRASH); + old.close(); + } + + private static void crash(Throwable error, @Nullable Object owner) { + if (error instanceof ReportedException reported) throw reported; + CrashReport report = CrashReport.forThrowable(error, "Running scheduled task"); + CrashReportCategory category = report.addCategory("Scheduled task"); + category.setDetail("Owner", owner == null ? "none" : owner.getClass().getName()); + if (owner instanceof Scope scope) category.setDetail("Scope", scope::toString); + else if (owner instanceof BlockEntity be) be.fillCrashReportCategory(category); + else if (owner instanceof Entity entity) entity.fillCrashReportCategory(category); + throw new ReportedException(report); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/Scope.java b/src/main/java/com/modularmc/mmclutils/api/schedule/Scope.java new file mode 100644 index 0000000..ce7f546 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/Scope.java @@ -0,0 +1,1134 @@ +package com.modularmc.mmclutils.api.schedule; + +import com.mojang.logging.LogUtils; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.Accessors; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * 作用域:持有副作用,结束时全部收回;绑定一条车道,只在该车道线程上使用。功能: + *
    + *
  • {@link #child}:子作用域,父结束时连带结束;只有 child 与 {@link Owned#root} 返回能结束的 + * {@link Owned},select、when、each、模块挂载、共享池、{@link ScopeSlot} 交给回调的作用域都不是 Owned,强转后结束不了
  • + *
  • {@link #onDispose}/{@link #effect}:登记撤销;结束时先把整棵子树标为不活动,再自叶到根、按登记倒序执行,子作用域之间也按建立的倒序;每个作用域只拆一次,撤销里结束祖先或别的作用域、触发信号、新建作用域都是安全的;撤销抛异常记入失败记录并继续;effect + * 先检查撤销非空再施加,施加抛异常时异常交给调用方、不登记撤销
  • + *
  • {@link #effectWhile}:条件为真期间施加,变假或作用域结束时撤销;不建子作用域;施加与撤销的失败处理同三参 effect
  • + *
  • {@link #repeat}/{@link #schedule}/{@link #trigger}:以本作用域为所有者的周期、延迟与合并任务,结束后不再执行,{@link Task#isActive} + * 随之为假;不占撤销登记,可在长寿命作用域上反复排一次性任务
  • + *
  • {@link #listen}:信号触发时同步执行,结束时退订;作用域一旦不活动(包括正在拆除、撤销里触发了这个信号)就不再执行
  • + *
  • {@link #watch}:派生一个值,首次以及之后每次按 equals 变化时把新值交给动作;派生期间读到的 {@link Signal}、{@link Cell} + * 自动成为依赖,触发后合并重算:在车道的一轮里触发的当轮就重算,一轮里最多连锁 16 层,超出的那个派生此后一律顺延到下一轮(互相触发的派生因此每轮只跑一次);在轮外触发的在即将到来的那一轮重算
  • + *
  • {@link #select}:同样派生一个值,值变化时先结束旧的子作用域,再建新的并在里面挂载,新旧不会同时存在
  • + *
  • {@link #when}:派生一个布尔值,为真时建子作用域,为假时结束;为假期间不占子作用域
  • + *
  • {@link #each}:派生一张表,按键对账:键同值等保留,值变重建,键消失结束;先结束消失的和值变了的,再给新增的和值变了的建子作用域;键按 equals 判等,源表要用同样的判等方式;表没变时不改动
  • + *
  • {@link #effect(Supplier, Consumer, Consumer)}:派生一个值并对它施加效果,值按 equals 变化时先撤旧值的效果再施加新值的,值为 null + * 时没有效果,作用域结束时撤掉当前效果;不建子作用域;施加抛异常记入失败记录、当作没有施加也没见过这个值,任何一个依赖再触发时重试;撤销抛异常(包括作用域已不活动时的撤销)记入失败记录、不外抛,并照常施加新值;派生值是 Boolean + * 或 Optional 时在值变化时记一次误用(只有 null 表示没有效果,布尔条件用 effectWhile);effect 默认自己是外部登记的唯一持有者,登记会被第三方清掉时清除方要触发一个效果追踪了的信号
  • + *
  • 所有挂载体的第一个参数都是它所在的作用域;派生函数拿不到作用域,只读
  • + *
  • 派生函数抛异常记日志并保持原状;挂载体抛异常记日志,这次挂到一半的子作用域整个撤回,值再变化时重新挂
  • + *
  • {@link #pool}/{@link #lease}:建一个随本作用域结束的 {@link SharedPool};向池借用共享资源,借用方结束时归还
  • + *
  • {@link #provide}/{@link #lookup}/{@link #require}:按 {@link Key} 向所属实例(最近的 {@link ScopeKind} + * 实例或无父作用域)提供带类型的服务,提供方结束时撤下;查找沿父作用域向上,在派生里查找会自动依赖经过的实例,别的实例上的增减不会让它重算;require 找不到时报错
  • + *
  • 在已结束的作用域上登记:副作用不发生,撤销立即执行,任务直接是已取消状态;listen、watch、select、when、each、effect、effectWhile、provide + * 此时记一次误用,作用域是因车道关闭而结束的不记
  • + *
  • 在派生函数求值期间登记(onDispose、listen、watch、select、when、each、effect、effectWhile、provide、lease、child、pool、建无父作用域)记一次误用,照常执行;挂载体与模块挂载不在派生求值期间,不算
  • + *
  • 线程:登记、建子作用域、借用、提供服务只能在车道线程上做,别的线程上调用直接报错;别的线程上结束作用域会转投到车道、下一轮开头再结束,并在首次发生时带调用栈告警,车道已关闭时直接返回、由车道自己的清理结束它;只能建在由固定线程驱动的车道上,异步车道上建作用域直接报错
  • + *
  • 车道关闭时,挂在它上面的无父作用域全部结束;在已关闭的车道上建的无父作用域一建立就是结束状态
  • + *
  • {@link #name}:标签的字符串形式;标签不是字符串时每次现算、不缓存;作用域结束后不再引用标签对象
  • + *
  • {@link #liveCount}:全进程存活作用域数,用于查泄漏;{@link #size}:本作用域连同全部子孙的个数;{@link #dump}:按缩进导出本作用域这棵树,每层最多列 24 + * 个子作用域;{@link #label}:建立时给的标签对象,供诊断按拥有者归类,结束后是字符串 ended
  • + *
  • {@link #failureCount}/{@link #recentFailures}:全进程累计的失败次数、最近 32 + * 条摘要;撤销、派生、挂载体、模块挂载、信号监听抛出的异常都记在这里;日志按"种类、异常类、抛出处第一帧"去重,首次带完整堆栈,之后只计数,每满 1000 次打一行带计数的摘要
  • + *
  • {@link #anomalyCount}:全进程累计的误用次数:被转投的跨线程调用、在派生函数里触发信号、登记或建立实例、在已结束的作用域上登记、effect 派生出布尔值、派生一轮里连锁超过 16 + * 层;每一种在首次发生时带调用栈告警并记进最近摘要,之后只计数;系统属性 mmclutils.strictScopes 为 true 时误用直接抛 IllegalStateException
  • + *
+ */ +public abstract sealed class Scope { + + private static final Logger LOGGER = LogUtils.getLogger(); + private static final AtomicInteger LIVE = new AtomicInteger(); + private static final AtomicInteger FAILURES = new AtomicInteger(); + private static final AtomicInteger ANOMALIES = new AtomicInteger(); + private static final ConcurrentHashMap REPORTED = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap FAILURE_SITES = new ConcurrentHashMap<>(); + private static final int FAILURE_SITE_LIMIT = 4096; + private static final int FAILURE_SUMMARY_EVERY = 1000; + private static final boolean STRICT = Boolean.getBoolean("mmclutils.strictScopes"); + static volatile boolean strictOverride; + static final String IN_DERIVATION = "scope registration inside a derivation function"; + static final String ON_ENDED = "registration on an ended scope"; + static final String TRUTHY_EFFECT = "effect derived a Boolean or Optional; only null means no effect, use effectWhile for conditions"; + private static final String ENDED = "ended"; + private static final String[] RECENT = new String[32]; + private static final int DUMP_SIBLINGS = 24; + private static int recentCount; + private static final Object[] NO_UNDO = new Object[0]; + private static final Scope[] NO_CHILDREN = new Scope[0]; + private static final Object[] NO_SERVICES = new Object[0]; + private static final Signal.Sub[] NO_SUBS = new Signal.Sub[0]; + + private Object label; + private final TickScheduler lane; + private final @Nullable Scope parent; + private boolean anchor; + private boolean active = true; + private boolean torn; + int slot = -1; + private Scope[] children = NO_CHILDREN; + private int childCount; + private Object[] undo = NO_UNDO; + private int undoCount; + private @Nullable Extras extras; + + Scope(Object label, TickScheduler lane, @Nullable Scope parent) { + this.label = label; + this.lane = lane; + this.parent = parent; + this.anchor = parent == null; + guard(); + if (!lane.sticky() && !lane.isClosed()) throw new IllegalStateException("Scope " + this + " needs a lane driven by one thread, async lanes are not supported"); + LIVE.incrementAndGet(); + if (parent == null) { + if (!lane.adopt(this)) end(); + } else if (parent.active) parent.attach(this); + else end(); + } + + /** 返回当前进程里仍在生效的作用域数。 */ + public static int liveCount() { + return LIVE.get(); + } + + /** 返回当前进程里记录的作用域回调失败次数。 */ + public static int failureCount() { + return FAILURES.get(); + } + + /** 返回当前进程里记录的作用域契约违规次数。 */ + public static int anomalyCount() { + return ANOMALIES.get(); + } + + /** 复制最近的异常记录,顺序从早到晚。调用方可以修改返回的列表。 */ + public static List recentFailures() { + synchronized (RECENT) { + int n = Math.min(recentCount, RECENT.length); + ArrayList out = new ArrayList<>(n); + for (int i = recentCount - n; i < recentCount; i++) out.add(RECENT[i & RECENT.length - 1]); + return out; + } + } + + static void fail(String what, @Nullable Object where, Throwable error) { + FAILURES.incrementAndGet(); + String place = String.valueOf(where); + remember(what + " @ " + place + ": " + error); + String site = failureSite(what, error); + AtomicInteger seen = FAILURE_SITES.get(site); + if (seen == null) { + if (FAILURE_SITES.size() >= FAILURE_SITE_LIMIT) { + LOGGER.error("作用域 {} 的操作 {} 失败", place, what, error); + return; + } + AtomicInteger made = new AtomicInteger(); + seen = FAILURE_SITES.putIfAbsent(site, made); + if (seen == null) seen = made; + } + int n = seen.incrementAndGet(); + if (n == 1) LOGGER.error("作用域 {} 的操作 {} 首次失败,后续同类失败按次数汇总", place, what, error); + else if (n % FAILURE_SUMMARY_EVERY == 0) LOGGER.error("操作 {} 已失败 {} 次,最近一次发生在作用域 {},原因为 {}", what, n, place, String.valueOf(error)); + } + + private static String failureSite(String what, Throwable error) { + StackTraceElement[] trace = error.getStackTrace(); + String top = trace.length == 0 ? "" : String.valueOf(trace[0]); + return what + '|' + error.getClass().getName() + '|' + top; + } + + static void anomaly(String what, @Nullable Object where) { + ANOMALIES.incrementAndGet(); + if (STRICT || strictOverride) throw new IllegalStateException("作用域使用错误:" + what + " @ " + where); + if (REPORTED.putIfAbsent(what, Boolean.TRUE) != null) return; + String place = String.valueOf(where); + LOGGER.warn("线程 {} 在作用域 {} 上执行了无效操作 {},后续同类操作按次数汇总", Thread.currentThread().getName(), place, what, new Throwable("调用位置")); + remember(what + " @ " + place); + } + + private static void remember(String line) { + synchronized (RECENT) { + RECENT[recentCount++ & RECENT.length - 1] = line; + } + } + + final void guard() { + if (lane.foreign()) throw new IllegalStateException("Scope " + this + " is used from thread " + Thread.currentThread().getName() + " instead of its lane thread"); + } + + static void checkFrame(@Nullable Object where) { + if (Signal.tracking()) anomaly(IN_DERIVATION, where); + } + + private boolean refuse() { + if (active) return false; + if (!lane.isClosed()) anomaly(ON_ENDED, this); + return true; + } + + /** 把作用域标签转换为可用于日志的名称。 */ + public final String name() { + Object current = label; + return current instanceof String name ? name : String.valueOf(current); + } + + /** 取得创建时提供的标签。作用域结束后返回结束标记,避免继续引用所有者。 */ + public final Object label() { + return label; + } + + final TickScheduler lane() { + return lane; + } + + /** 判断作用域是否还接收注册。结束阶段开始时立即返回 {@code false}。 */ + public final boolean isActive() { + return active; + } + + /** 在当前调度线程创建带结束权限的子作用域。父作用域结束时会结束其子级。 */ + public final Owned child(String name) { + checkFrame(this); + return new Owned(name, lane, this); + } + + final Scope inner(Object label) { + return new Inner(label, lane, this); + } + + static Scope innerRoot(Object label, TickScheduler lane) { + return new Inner(label, lane, null); + } + + final void markAnchor() { + if (anchor) return; + anchor = true; + if (childCount == 0 && undoCount == 0) return; + for (Scope s = parent; s != null; s = s.parent) { + if (!s.anchor) continue; + s.instanceChanged(); + return; + } + } + + final void trackInstance() { + if (!Signal.tracking()) return; + Extras x = extras(); + Signal s = x.changed; + if (s == null) x.changed = s = new Signal(); + s.track(); + } + + final void instanceChanged() { + Extras x = extras; + if (x != null && x.changed != null) x.changed.emit(); + } + + private Extras extras() { + Extras x = extras; + if (x == null) extras = x = new Extras(); + return x; + } + + /** 计算当前节点下仍挂接的作用域数,包含自身。请在调度线程调用。 */ + public final int size() { + int n = 1; + for (int i = 0; i < childCount; i++) { + Scope c = children[i]; + if (c != null) n += c.size(); + } + return n; + } + + /** 向缓冲区追加作用域层级诊断信息。当前节点深度为零,达到给定深度时停止展开。 */ + public final void dump(StringBuilder out, int maxDepth) { + dump(out, 0, maxDepth); + } + + private void dump(StringBuilder out, int depth, int maxDepth) { + indent(out, depth).append(name()).append(" ["); + if (childCount > 0) out.append(size() - 1).append(" below, "); + out.append(undoCount).append(" undo"); + int services = extras == null ? 0 : extras.serviceCount; + if (services > 0) out.append(", ").append(services).append(" services"); + out.append("]\n"); + if (depth >= maxDepth) return; + int shown = 0; + int hidden = 0; + for (int i = 0; i < childCount; i++) { + Scope c = children[i]; + if (c == null) continue; + if (shown == DUMP_SIBLINGS) { + hidden++; + continue; + } + shown++; + c.dump(out, depth + 1, maxDepth); + } + if (hidden > 0) indent(out, depth + 1).append("+ ").append(hidden).append(" more\n"); + } + + private static StringBuilder indent(StringBuilder out, int depth) { + for (int i = 0; i < depth; i++) out.append(" "); + return out; + } + + /** 在调度线程登记清理回调。清理按登记的逆序执行,已结束的作用域立即执行回调。 */ + public final void onDispose(Runnable action) { + Objects.requireNonNull(action, "action"); + guard(); + checkFrame(this); + undo(action); + } + + final void undo(Runnable action) { + if (!active) { + runQuietly(action); + return; + } + push(action); + } + + private void push(Object action) { + int n = undoCount; + if (n == undo.length) undo = Arrays.copyOf(undo, Math.max(2, n * 2)); + undo[n] = action; + undoCount = n + 1; + } + + /** 立即应用一次变更,并在当前作用域结束时执行对应撤销。 */ + public final void effect(Runnable apply, Runnable revert) { + Objects.requireNonNull(revert, "revert"); + guard(); + checkFrame(this); + if (refuse()) return; + apply.run(); + if (active) push(revert); + else runQuietly(revert); + } + + /** 跟踪派生值读取的依赖。值变化时先撤销上一值,再应用新值,结束时撤销最后一次应用。 */ + public final void effect(Supplier derive, Consumer apply, Consumer revert) { + Objects.requireNonNull(derive, "derive"); + Objects.requireNonNull(apply, "apply"); + Objects.requireNonNull(revert, "revert"); + guard(); + checkFrame(this); + if (refuse()) return; + new Applied(this, derive, apply, revert).run(); + } + + /** 根据受跟踪的布尔条件应用或撤销变更,结束时撤销还生效的变更。 */ + public final void effectWhile(BooleanSupplier condition, Runnable apply, Runnable revert) { + Objects.requireNonNull(condition, "condition"); + Objects.requireNonNull(apply, "apply"); + Objects.requireNonNull(revert, "revert"); + guard(); + checkFrame(this); + if (refuse()) return; + new Toggled(this, condition, apply, revert).run(); + } + + /** 在所属调度器上提交周期任务。作用域结束后,任务在到期时取消。 */ + public final Task repeat(Cadence cadence, Runnable action) { + Task task = lane.repeat(cadence, this, action); + if (!active) task.cancel(); + return task; + } + + /** 在所属调度器上提交一次性任务。作用域先结束时,任务在到期时跳过。 */ + public final Task schedule(int delay, Runnable action) { + Task task = lane.schedule(delay, this, action); + if (!active) task.cancel(); + return task; + } + + /** 创建与作用域绑定的合并触发器。同一等待窗口内的触发只执行一次。 */ + public final Trigger trigger(int delay, Runnable action) { + CoalescedTask task = new CoalescedTask(this, action); + int d = Math.max(0, delay); + return () -> { + if (active) lane.submit(task, d); + }; + } + + /** 在调度线程订阅信号,通知在所属调度器上执行。作用域结束时解除订阅。 */ + public final void listen(Signal signal, Runnable listener) { + Objects.requireNonNull(listener, "listener"); + guard(); + checkFrame(this); + if (refuse()) return; + Listening hook = new Listening(this, listener); + hook.sub = signal.subscribe(lane, hook); + push(hook); + } + + /** 立即读取派生值并通知监听者。之后只在依赖触发且值发生变化时再次通知。 */ + public final void watch(Supplier derive, Consumer action) { + guard(); + checkFrame(this); + if (refuse()) return; + new Watch(this, derive, action).run(); + } + + /** 为当前派生值建立子作用域。值变化时先清理旧子作用域,再运行新的作用域回调。 */ + public final void select(Supplier derive, Body body) { + guard(); + checkFrame(this); + if (refuse()) return; + new Select(this, derive, body).run(); + } + + /** 仅在条件成立时维持一个子作用域。条件退出时释放子作用域里的资源。 */ + public final void when(BooleanSupplier condition, Consumer body) { + guard(); + checkFrame(this); + if (refuse()) return; + new When(this, condition, body).run(); + } + + /** 按键维护子作用域。键消失或对应值改变时结束旧作用域,同键同值继续复用。 */ + public final void each(Supplier> derive, KeyedBody body) { + guard(); + checkFrame(this); + if (refuse()) return; + new Each(this, derive, body).run(); + } + + /** 创建随当前作用域关闭的共享池。最后一处借用释放后,条目按给定轮数保留。 */ + public final SharedPool pool(String name, int grace, SharedPool.Factory factory) { + checkFrame(this); + return new SharedPool<>(inner(name), grace, factory); + } + + /** 获取指定键的共享资源。借用在当前作用域结束时释放。 */ + public final SharedPool.Lease lease(SharedPool pool, K key) { + guard(); + checkFrame(this); + return pool.lease(this, key); + } + + /** 把非空值登记到最近的服务作用域。同一键按登记次序覆盖,在派生子作用域中登记的值随该子作用域撤销。 */ + public final void provide(Key key, V value) { + Objects.requireNonNull(value, "value"); + guard(); + checkFrame(this); + if (refuse()) return; + Scope host = this; + while (!host.anchor) host = host.parent; + host.put(key, value); + if (host == this) return; + Scope instance = host; + push((Runnable) () -> instance.withdraw(key, value)); + } + + /** 从最近的服务作用域向父级按键身份查找。未登记时返回 {@code null},派生计算中会跟踪查找使用的作用域。 */ + @Nullable + @SuppressWarnings("unchecked") + public final V lookup(Key key) { + for (Scope s = this; s != null; s = s.parent) { + if (!s.anchor) continue; + s.trackInstance(); + Extras x = s.extras; + if (x == null) continue; + for (int i = x.serviceCount - 1; i >= 0; i--) { + if (x.services[i * 2] == key) return (V) x.services[i * 2 + 1]; + } + } + return null; + } + + /** 查找当前可见的服务。缺少对应键时抛出 {@link IllegalStateException}。 */ + public final V require(Key key) { + V value = lookup(key); + if (value == null) throw new IllegalStateException("No " + key + " in scope " + this); + return value; + } + + private void put(Key key, Object value) { + Extras x = extras(); + if (x.serviceCount * 2 == x.services.length) x.services = Arrays.copyOf(x.services, Math.max(4, x.services.length * 2)); + x.services[x.serviceCount * 2] = key; + x.services[x.serviceCount * 2 + 1] = value; + x.serviceCount++; + instanceChanged(); + } + + private void withdraw(Key key, Object value) { + Extras x = extras; + if (x == null) return; + for (int i = x.serviceCount - 1; i >= 0; i--) { + if (x.services[i * 2] != key || x.services[i * 2 + 1] != value) continue; + int tail = (x.serviceCount - 1 - i) * 2; + System.arraycopy(x.services, i * 2 + 2, x.services, i * 2, tail); + x.serviceCount--; + x.services[x.serviceCount * 2] = null; + x.services[x.serviceCount * 2 + 1] = null; + instanceChanged(); + return; + } + } + + @Override + public String toString() { + return parent == null ? name() : parent + "/" + name(); + } + + final void end() { + if (!active) return; + if (lane.foreign()) { + if (lane.isClosed()) return; + anomaly("scope ended off its lane thread", this); + lane.schedule(0, null, this::end); + return; + } + deactivate(); + teardown(); + if (parent != null) parent.detach(this); + else lane.release(this); + } + + private void deactivate() { + active = false; + for (int i = 0; i < childCount; i++) { + Scope c = children[i]; + if (c != null) c.deactivate(); + } + } + + private void teardown() { + if (torn) return; + torn = true; + Scope[] ending = children; + int endingCount = childCount; + children = NO_CHILDREN; + childCount = 0; + for (int i = endingCount - 1; i >= 0; i--) { + Scope c = ending[i]; + if (c == null) continue; + ending[i] = null; + c.slot = -1; + c.teardown(); + } + Object[] undoing = undo; + int undoingCount = undoCount; + undo = NO_UNDO; + undoCount = 0; + for (int i = undoingCount - 1; i >= 0; i--) { + Object r = undoing[i]; + undoing[i] = null; + runQuietly(r); + } + Extras x = extras; + if (x != null) { + extras = null; + Signal s = x.changed; + if (s != null) s.emit(); + } + if (!(label instanceof String)) label = ENDED; + LIVE.decrementAndGet(); + } + + private void attach(Scope child) { + if (childCount == children.length) makeRoom(); + child.slot = childCount; + children[childCount++] = child; + } + + private void makeRoom() { + int kept = 0; + for (int i = 0; i < childCount; i++) { + Scope c = children[i]; + if (c == null) continue; + if (kept != i) { + children[kept] = c; + children[i] = null; + c.slot = kept; + } + kept++; + } + childCount = kept; + if (kept >= children.length - (children.length >> 2)) children = Arrays.copyOf(children, Math.max(2, children.length * 2)); + } + + private void detach(Scope child) { + int i = child.slot; + if (i < 0 || i >= childCount || children[i] != child) return; + children[i] = null; + child.slot = -1; + while (childCount > 0 && children[childCount - 1] == null) childCount--; + } + + private void runQuietly(Object r) { + try { + if (r instanceof Hook hook) hook.stop(); + else((Runnable) r).run(); + } catch (Throwable t) { + fail("dispose action", this, t); + } + } + + /** 按依赖变化触发的轻量通知入口。 */ + @FunctionalInterface + public interface Trigger { + + /** 在依赖状态变化后执行通知。 */ + void fire(); + } + + /** 在指定作用域中挂载由调用方提供的值。 */ + @FunctionalInterface + public interface Body { + + /** + * 将值与生命周期作用域一起挂载。 + * + * @param scope 管理挂载资源的子作用域 + * @param value 已取得的挂载值 + */ + void mount(Scope scope, T value); + } + + /** 在作用域中挂载带显式键和值的资源。 */ + @FunctionalInterface + public interface KeyedBody { + + /** + * 将键值资源挂载至子作用域。 + * + * @param scope 管理挂载资源的子作用域 + * @param key 资源标识键 + * @param value 与键对应的资源值 + */ + void mount(Scope scope, K key, V value); + } + + static final class Inner extends Scope { + + Inner(Object label, TickScheduler lane, @Nullable Scope parent) { + super(label, lane, parent); + } + } + + private static final class Extras { + + Object[] services = NO_SERVICES; + int serviceCount; + @Nullable + Signal changed; + } + + abstract static class Hook { + + abstract void fire(); + + abstract void stop(); + } + + private static final class Listening extends Hook { + + private final Scope owner; + private final Runnable listener; + Signal.Sub sub; + + Listening(Scope owner, Runnable listener) { + this.owner = owner; + this.listener = listener; + } + + @Override + void fire() { + if (owner.active) listener.run(); + } + + @Override + void stop() { + sub.remove(); + } + } + + private abstract static class Derivation extends Hook implements Runnable { + + final Scope owner; + private final int salt; + private @Nullable CoalescedTask task; + private Signal.Sub[] subs = NO_SUBS; + private int subCount; + + Derivation(Scope owner) { + this.owner = owner; + this.salt = owner.lane.nextSalt(); + owner.push(this); + } + + @Override + public final void run() { + if (owner.active) evaluate(); + } + + @Override + final void fire() { + if (!owner.active) return; + CoalescedTask t = task; + if (t == null) task = t = new CoalescedTask(owner, this); + owner.lane.settle(t); + } + + @Override + final void stop() { + CoalescedTask t = task; + if (t != null) t.retire(); + for (int i = 0; i < subCount; i++) subs[i].remove(); + subCount = 0; + subs = NO_SUBS; + stopped(); + } + + void stopped() {} + + abstract void evaluate(); + + abstract Object compute(); + + final Object derive() { + Signal.Frame frame = Signal.enter(owner.lane, salt); + try { + return compute(); + } finally { + try { + rewire(frame); + } finally { + Signal.exit(frame); + } + } + } + + final void failed(String what, Throwable error) { + fail(what, owner, error); + } + + private void rewire(Signal.Frame frame) { + int n = frame.count; + Signal[] deps = frame.deps; + if (subCount == 0) { + if (n == 0) return; + Signal.Sub[] next = new Signal.Sub[n]; + int made = 0; + try { + for (; made < n; made++) next[made] = deps[made].subscribe(owner.lane, this); + } catch (Throwable t) { + for (int i = 0; i < made; i++) next[i].remove(); + for (int i = 0; i < n; i++) deps[i].unclaimed(); + throw t; + } + subs = next; + subCount = n; + return; + } + boolean same = n == subCount; + for (int i = 0; same && i < n; i++) same = subs[i].signal == deps[i]; + if (same) return; + Signal.Sub[] next = n == 0 ? NO_SUBS : new Signal.Sub[n]; + boolean[] kept = new boolean[subCount]; + boolean[] fresh = new boolean[n]; + try { + for (int i = 0; i < n; i++) { + for (int j = 0; j < subCount; j++) { + if (!kept[j] && subs[j].signal == deps[i]) { + next[i] = subs[j]; + kept[j] = true; + break; + } + } + if (next[i] != null) continue; + next[i] = deps[i].subscribe(owner.lane, this); + fresh[i] = true; + } + } catch (Throwable t) { + for (int i = 0; i < n; i++) if (fresh[i]) next[i].remove(); + for (int i = 0; i < n; i++) deps[i].unclaimed(); + throw t; + } + for (int j = 0; j < subCount; j++) if (!kept[j]) subs[j].remove(); + subs = next; + subCount = n; + } + } + + private static final class Watch extends Derivation { + + private final Supplier source; + private final Consumer action; + private boolean seen; + private @Nullable T value; + + Watch(Scope owner, Supplier source, Consumer action) { + super(owner); + this.source = source; + this.action = action; + } + + @Override + Object compute() { + return source.get(); + } + + @Override + @SuppressWarnings("unchecked") + void evaluate() { + T next; + try { + next = (T) derive(); + } catch (Throwable t) { + failed("derivation", t); + return; + } + if (seen && Objects.equals(next, value)) return; + seen = true; + value = next; + try { + action.accept(next); + } catch (Throwable t) { + failed("action", t); + } + } + } + + private static class Applied extends Derivation { + + private final @Nullable Supplier source; + private final @Nullable Consumer apply; + private final @Nullable Consumer revert; + private boolean seen; + private @Nullable T value; + private @Nullable T held; + + Applied(Scope owner, @Nullable Supplier source, @Nullable Consumer apply, @Nullable Consumer revert) { + super(owner); + this.source = source; + this.apply = apply; + this.revert = revert; + } + + @Override + Object compute() { + return source.get(); + } + + void applyValue(T next) { + apply.accept(next); + } + + void revertValue(T old) { + revert.accept(old); + } + + void inspect(Object next) { + if (next instanceof Boolean || next instanceof Optional) anomaly(TRUTHY_EFFECT, owner); + } + + @Override + @SuppressWarnings("unchecked") + final void evaluate() { + T next; + try { + next = (T) derive(); + } catch (Throwable t) { + failed("derivation", t); + return; + } + if (seen && Objects.equals(next, value)) return; + seen = true; + value = next; + if (next != null) inspect(next); + T old = held; + if (old != null) { + held = null; + try { + revertValue(old); + } catch (Throwable t) { + failed("revert", t); + } + if (!owner.active) return; + } + if (next == null) return; + try { + applyValue(next); + held = next; + } catch (Throwable t) { + failed("apply", t); + seen = false; + } + if (owner.active) return; + try { + stopped(); + } catch (Throwable t) { + failed("revert", t); + } + } + + @Override + final void stopped() { + T old = held; + if (old == null) return; + held = null; + revertValue(old); + } + } + + private static final class Toggled extends Applied { + + private final BooleanSupplier condition; + private final Runnable on; + private final Runnable off; + + Toggled(Scope owner, BooleanSupplier condition, Runnable on, Runnable off) { + super(owner, null, null, null); + this.condition = condition; + this.on = on; + this.off = off; + } + + @Override + Object compute() { + return condition.getAsBoolean() ? Boolean.TRUE : null; + } + + @Override + void applyValue(Boolean next) { + on.run(); + } + + @Override + void revertValue(Boolean old) { + off.run(); + } + + @Override + void inspect(Object next) {} + } + + private static final class Select extends Derivation { + + private final Supplier source; + private final Body body; + private @Nullable Scope child; + private @Nullable T value; + + Select(Scope owner, Supplier source, Body body) { + super(owner); + this.source = source; + this.body = body; + } + + @Override + Object compute() { + return source.get(); + } + + @Override + @SuppressWarnings("unchecked") + void evaluate() { + T next; + try { + next = (T) derive(); + } catch (Throwable t) { + failed("derivation", t); + return; + } + Scope previous = child; + if (previous != null && Objects.equals(next, value)) return; + value = next; + if (previous != null) { + previous.end(); + if (!owner.active) return; + } + Scope built = owner.inner("select"); + child = built; + try { + body.mount(built, next); + } catch (Throwable t) { + failed("body", t); + built.end(); + } + } + } + + private static final class When extends Derivation { + + private final BooleanSupplier condition; + private final Consumer body; + private @Nullable Scope child; + + When(Scope owner, BooleanSupplier condition, Consumer body) { + super(owner); + this.condition = condition; + this.body = body; + } + + @Override + Object compute() { + return condition.getAsBoolean(); + } + + @Override + void evaluate() { + boolean open; + try { + open = (Boolean) derive(); + } catch (Throwable t) { + failed("derivation", t); + return; + } + Scope current = child; + if (open == (current != null)) return; + if (current != null) { + child = null; + current.end(); + return; + } + Scope built = owner.inner("when"); + child = built; + try { + body.accept(built); + } catch (Throwable t) { + failed("body", t); + built.end(); + } + } + } + + private static final class Each extends Derivation { + + private final Supplier> source; + private final KeyedBody body; + private final HashMap> entries = new HashMap<>(); + + Each(Scope owner, Supplier> source, KeyedBody body) { + super(owner); + this.source = source; + this.body = body; + } + + @Override + Object compute() { + return source.get(); + } + + @Override + @SuppressWarnings("unchecked") + void evaluate() { + Map next; + try { + next = (Map) derive(); + } catch (Throwable t) { + failed("derivation", t); + return; + } + try { + if (!entries.isEmpty()) { + var held = entries.entrySet().iterator(); + while (held.hasNext()) { + var e = held.next(); + K key = e.getKey(); + Entry entry = e.getValue(); + V now = next.get(key); + if (Objects.equals(now, entry.value) && (now != null || next.containsKey(key))) continue; + held.remove(); + entry.scope.end(); + if (!owner.active) return; + } + } + if (entries.size() == next.size()) return; + for (var e : next.entrySet()) { + K key = e.getKey(); + if (entries.containsKey(key)) continue; + V value = e.getValue(); + Scope scope = owner.inner("each"); + entries.put(key, new Entry<>(value, scope)); + try { + body.mount(scope, key, value); + } catch (Throwable t) { + fail("body", owner + " [key " + key + "]", t); + scope.end(); + } + if (!owner.active) return; + } + } catch (Throwable t) { + failed("reconciliation", t); + } + } + } + + private record Entry(V value, Scope scope) {} + + /** 作用域服务的类型键。同名键各自独立,在所属车道上通过 provide 和 lookup 使用。 */ + @RequiredArgsConstructor(access = AccessLevel.PRIVATE) + public static final class Key { + + /** 出现在诊断输出中的名称。服务键始终按引用身份比较。 */ + @Getter + @Accessors(fluent = true) + private final String name; + + /** 分配一个新的服务键。名称相同的多次调用会得到彼此独立的键。 */ + public static Key of(String name) { + return new Key<>(name); + } + + @Override + public String toString() { + return "Scope.Key[" + name + "]"; + } + } + + /** 持有结束权限的作用域。由 root 和 child 建立,结束会按作用域的车道安排。 */ + public static final class Owned extends Scope { + + private Owned(Object label, TickScheduler lane, @Nullable Scope parent) { + super(label, lane, parent); + } + + /** 在给定调度器上创建带名字的根作用域。关闭调度器时释放该作用域。 */ + public static Owned root(String name, TickScheduler lane) { + checkFrame(name); + return new Owned(name, lane, null); + } + + /** 创建根作用域并保留对象标签,结束时释放标签的引用。 */ + public static Owned root(Object label, TickScheduler lane) { + Objects.requireNonNull(label, "label"); + checkFrame(label); + return new Owned(label, lane, null); + } + + /** 结束本作用域及其子作用域,重复调用幂等。 */ + public void dispose() { + end(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/ScopeKind.java b/src/main/java/com/modularmc/mmclutils/api/schedule/ScopeKind.java new file mode 100644 index 0000000..5f0507c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/ScopeKind.java @@ -0,0 +1,233 @@ +package com.modularmc.mmclutils.api.schedule; + +import com.modularmc.mmclutils.api.schedule.Scope.Key; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; +import java.util.function.BiConsumer; + +/** + * 一种作用域:每个拥有者(玩家、维度、屏幕……)各有一个实例,模块登记一次、每个实例建立时自动挂上。功能: + *
    + *
  • {@link #byIdentity}/{@link #byEquality}:建一种作用域,拥有者按对象身份或按 equals 区分;返回的 {@link Control} 只交给负责开关的一方
  • + *
  • {@link #install}:登记一个模块;之后建立的每个实例都会挂上它,已经存在的实例立即补挂;同名重复登记报错
  • + *
  • open 建的实例与模块的子作用域都不是 {@link Scope.Owned},拿到的一方强转后结束不了;每个模块挂在实例下自己的子作用域里,它用 {@link Scope#provide} + * 提供的服务对整个实例可见;某个模块挂载时抛异常记入失败记录,它已挂上的部分整个撤回,不影响其余模块;模块挂载期间读到的信号不会记成外层派生的依赖
  • + *
  • {@link #get}:拥有者当前的实例,没有时为 null;在派生里调用会随这个拥有者的实例建立、更换与结束自动重算,别的拥有者的实例结束不会让它重算
  • + *
  • {@link #lookup}/{@link #require}:直接取拥有者实例上的服务;没有实例或没有该服务时,lookup 为 null,require 报错
  • + *
  • {@link #forEach}/{@link #size}:遍历当前全部实例
  • + *
  • {@link Control#open}:为拥有者建一个根实例,按登记顺序挂上全部模块;车道已关闭时得到的是已结束的实例,不留下任何登记
  • + *
  • {@link Control#bind}:把一个已有的作用域认作拥有者的实例(例如派生里建的子作用域),它结束时自动除名;同一个作用域重复认领什么也不做
  • + *
  • 一个拥有者同一时刻只有一个实例:open 与 bind 都会先结束该拥有者此前的实例,不论它是 open 建的还是 bind 认的
  • + *
  • {@link Control#close}/{@link Control#closeAll}:结束 open 建立的实例;closeAll 期间又被 open 出来的实例也一并结束
  • + *
  • 同一种作用域的实例只能在同一个线程上建立,另一个线程来建立直接报错;在派生函数里建立实例记一次误用
  • + *
+ */ +public final class ScopeKind { + + /** 将模块资源安装到指定拥有者的生命周期作用域中。 */ + @FunctionalInterface + public interface Module { + + /** + * 在拥有者的子作用域里安装模块资源。 + * 安装抛出异常时该子作用域会整体结束,并按模块挂载规则报告异常。 + * + * @param scope 该模块独占的子作用域 + * @param owner 模块所属对象 + */ + void mount(Scope scope, T owner); + } + + private record Installed(String id, Module module) {} + + private record Label(String kind, Object owner) { + + @Override + public String toString() { + return kind + " " + owner; + } + } + + private final String name; + private final Map live; + private final Map roots; + private final Signal arrived = new Signal(); + @SuppressWarnings("unchecked") + private Installed[] modules = new Installed[0]; + private @Nullable Thread home; + + private ScopeKind(String name, boolean identity) { + this.name = name; + this.live = identity ? new Reference2ObjectLinkedOpenHashMap<>() : new Object2ObjectLinkedOpenHashMap<>(); + this.roots = identity ? new Reference2ObjectLinkedOpenHashMap<>() : new Object2ObjectLinkedOpenHashMap<>(); + } + + /** 创建按所有者引用身份查找的作用域类型,并返回管理生命周期的控制入口。 */ + public static Control byIdentity(String name) { + return new Control<>(new ScopeKind<>(name, true)); + } + + /** 创建按所有者相等性查找的作用域类型。所有者参与哈希的字段在绑定期间须稳定。 */ + public static Control byEquality(String name) { + return new Control<>(new ScopeKind<>(name, false)); + } + + /** 返回此类作用域的诊断名称。 */ + public String name() { + return name; + } + + /** 注册模块并在已有作用域中挂载。模块标识必须唯一,重复时抛出异常。 */ + public void install(String id, Module module) { + for (var m : modules) if (m.id.equals(id)) throw new IllegalStateException("Module " + id + " already installed on scope kind " + name); + var installed = new Installed(id, module); + var grown = Arrays.copyOf(modules, modules.length + 1); + grown[modules.length] = installed; + modules = grown; + if (live.isEmpty()) return; + for (var owner : new ArrayList<>(live.keySet())) { + var scope = live.get(owner); + if (scope != null) mountSafely(installed, scope, owner); + } + } + + /** 查询所有者的活动作用域。缺失时返回空值,派生计算会订阅后续建立通知。 */ + @Nullable + public Scope get(T owner) { + Scope scope = live.get(owner); + if (scope != null) scope.trackInstance(); + else arrived.track(); + return scope; + } + + /** 从所有者作用域向上查找服务。所有者或服务缺失时返回空值。 */ + @Nullable + public V lookup(T owner, Key key) { + Scope scope = get(owner); + return scope == null ? null : scope.lookup(key); + } + + /** 读取必须已登记的服务,作用域或服务缺失时抛出异常。 */ + public V require(T owner, Key key) { + Scope scope = get(owner); + if (scope == null) throw new IllegalStateException("No " + name + " scope for " + owner); + return scope.require(key); + } + + /** 按当前登记顺序访问活动所有者和作用域。请在所属调度线程调用。 */ + public void forEach(BiConsumer action) { + for (var owner : new ArrayList<>(live.keySet())) { + var scope = live.get(owner); + if (scope != null) action.accept(owner, scope); + } + } + + /** 返回当前绑定的活动实例数量。 */ + public int size() { + return live.size(); + } + + @Override + public String toString() { + return "ScopeKind[" + name + "]"; + } + + private void mountSafely(Installed installed, Scope scope, T owner) { + if (!scope.isActive()) return; + Scope room = scope.inner(installed.id); + Signal.Frame muted = Signal.mute(); + try { + installed.module.mount(room, owner); + } catch (Throwable t) { + Scope.fail("module " + installed.id + " mount", room, t); + room.end(); + } finally { + Signal.unmute(muted); + } + } + + private void enter() { + Thread thread = Thread.currentThread(); + if (live.isEmpty()) home = thread; + else if (home != thread) throw new IllegalStateException("Scope kind " + name + " is used from thread " + thread.getName() + " while its instances live on another thread"); + if (Signal.tracking()) Scope.anomaly("scope instance opened inside a derivation function", name); + } + + private void attach(T owner, Scope scope) { + scope.markAnchor(); + Scope previous = live.put(owner, scope); + scope.undo(() -> { + if (live.get(owner) == scope) live.remove(owner); + if (roots.get(owner) == scope) roots.remove(owner); + }); + if (previous == null) arrived.emit(); + else if (previous != scope) previous.end(); + Installed[] mounting = modules; + for (var installed : mounting) mountSafely(installed, scope, owner); + } + + /** 对拥有者实例进行开设、绑定和关闭的句柄。 */ + public static final class Control { + + private final ScopeKind kind; + + private Control(ScopeKind kind) { + this.kind = kind; + } + + /** 返回此句柄管理的作用域种类。 */ + public ScopeKind kind() { + return kind; + } + + /** + * 为拥有者打开一个根实例并按登记顺序安装所有模块。 + * 同一拥有者的既有实例会先结束。 + * + * @param owner 新实例的拥有者 + * @param lane 驱动实例中任务与清理的调度车道 + * @return 新打开的拥有者作用域 + */ + public Scope open(T owner, TickScheduler lane) { + kind.enter(); + lane.claim(); + close(owner); + var root = Scope.innerRoot(new Label(kind.name, owner), lane); + Scope reentered = kind.roots.put(owner, root); + if (reentered != null) reentered.end(); + kind.attach(owner, root); + return root; + } + + /** 将已有活动作用域登记为该拥有者的当前实例,结束旧实例并安装尚未安装的模块。 */ + public void bind(T owner, Scope scope) { + if (!scope.isActive() || kind.live.get(owner) == scope) return; + scope.guard(); + kind.enter(); + close(owner); + kind.attach(owner, scope); + } + + /** 结束此拥有者由 {@link #open(Object, TickScheduler)} 建立的根实例。 */ + public void close(T owner) { + var root = kind.roots.remove(owner); + if (root != null) root.end(); + } + + /** 结束调用开始时以及结束回调期间新建立的全部根实例。 */ + public void closeAll() { + for (int budget = kind.roots.size() + 16; budget > 0 && !kind.roots.isEmpty(); budget--) { + var first = kind.roots.values().iterator(); + Scope root = first.next(); + first.remove(); + root.end(); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/ScopeSlot.java b/src/main/java/com/modularmc/mmclutils/api/schedule/ScopeSlot.java new file mode 100644 index 0000000..43a92d6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/ScopeSlot.java @@ -0,0 +1,95 @@ +package com.modularmc.mmclutils.api.schedule; + +import org.jspecify.annotations.Nullable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.Objects; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * 可重开的无父作用域槽,给"加载时开、卸载时关"的拥有者用,省掉自己存字段、判空、先关后开。功能: + *
    + *
  • {@link #open(Object, TickScheduler, Consumer)}:先结束槽里上一个作用域,再在车道上建一个新的无父作用域并在里面执行体;体抛异常记入失败记录,这次挂到一半的作用域整个撤回,槽变空;车道已关闭时不执行体,返回已结束的作用域,槽变空;在车道以外的线程上调用、或车道是异步车道时直接报错,槽里原有的作用域不受影响;在派生函数求值期间调用记一次误用
  • + *
  • {@link #open(Object, TickScheduler, Object, BiConsumer)}:同上,体额外收一个实参,体可以写成不捕获的静态常量,省掉每次打开新建的转接 lambda
  • + *
  • 返回的作用域与 {@link #current} 都不是 {@link Scope.Owned},强转后结束不了,只能经 {@link #close} 或再次 open 结束
  • + *
  • {@link #close}:结束槽里的作用域;幂等,槽空、作用域已自行结束、车道已关闭时什么也不做;在别的线程上调用按 {@link Scope.Owned#dispose} 的规矩转投
  • + *
  • {@link #current}/{@link #isOpen}:查询槽内仍在活动的作用域。槽位以发布语义写入,其它线程可通过 volatile 读取取得该值
  • + *
+ */ +public final class ScopeSlot { + + private static final BiConsumer> PLAIN = (s, body) -> body.accept(s); + private static final VarHandle SCOPE; + + static { + try { + SCOPE = MethodHandles.lookup().findVarHandle(ScopeSlot.class, "scope", Scope.class); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + private volatile @Nullable Scope scope; + + /** 在给定调度器下打开新作用域,结束槽位上此前建立的作用域。 */ + public Scope open(Object label, TickScheduler lane, Consumer body) { + Objects.requireNonNull(body, "body"); + return open(label, lane, body, PLAIN); + } + + /** 替换槽中的作用域,将调用方参数传给新作用域的初始化回调。 */ + public
Scope open(Object label, TickScheduler lane, A arg, BiConsumer body) { + Objects.requireNonNull(label, "label"); + Objects.requireNonNull(body, "body"); + Scope opened = begin(label, lane); + if (!opened.isActive()) return opened; + try { + body.accept(opened, arg); + } catch (Throwable t) { + Scope.fail("slot body", opened, t); + opened.end(); + } + if (!opened.isActive() && SCOPE.get(this) == opened) SCOPE.setRelease(this, null); + return opened; + } + + private Scope begin(Object label, TickScheduler lane) { + if (lane.foreign() || !lane.sticky() && !lane.isClosed()) refuse(label, lane); + Scope.checkFrame(label); + Scope previous = (Scope) SCOPE.get(this); + if (previous != null) { + SCOPE.setRelease(this, null); + previous.end(); + } + Scope opened = Scope.innerRoot(label, lane); + if (opened.isActive()) SCOPE.setRelease(this, opened); + return opened; + } + + private static void refuse(Object label, TickScheduler lane) { + if (lane.foreign()) throw new IllegalStateException("Scope slot opened from thread " + Thread.currentThread().getName() + " instead of its lane thread"); + throw new IllegalStateException("Scope slot " + label + " needs a lane driven by one thread, async lanes are not supported"); + } + + /** 结束当前作用域并清空槽位。没有活动作用域时直接返回。 */ + public void close() { + Scope current = scope; + if (current == null) return; + SCOPE.setRelease(this, null); + current.end(); + } + + /** 读取槽中的当前作用域。槽为空或先前作用域已结束时返回空值。 */ + @Nullable + public Scope current() { + Scope current = scope; + return current != null && current.isActive() ? current : null; + } + + /** 判断槽中是否还有活动作用域。 */ + public boolean isOpen() { + return current() != null; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/ScopedOverride.java b/src/main/java/com/modularmc/mmclutils/api/schedule/ScopedOverride.java new file mode 100644 index 0000000..70277dc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/ScopedOverride.java @@ -0,0 +1,87 @@ +package com.modularmc.mmclutils.api.schedule; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.jspecify.annotations.Nullable; + +/** + * 通过 {@code try} 资源语句临时覆盖状态。每个实例用于单线程上的一次覆盖,关闭时恢复初始值。 + */ +public abstract class ScopedOverride implements AutoCloseable { + + /** + * 临时覆盖对象值,关闭时恢复构造时指定的值,默认恢复为 {@code null}。 + * + * @param 对象类型 + */ + @RequiredArgsConstructor + public static final class Object extends ScopedOverride { + + private final @Nullable T initialValue; + + /** + * 当前覆盖值,关闭后为配置的恢复值。 + */ + @Getter + private @Nullable T value; + + /** 创建以空值作为恢复值的对象覆盖。 */ + public Object() { + this(null); + } + + /** + * 设置当前覆盖值,返回可在资源语句中关闭的对象。 + * + * @return 当前作用域对象 + */ + public Object with(T value) { + this.value = value; + return this; + } + + @Override + public void close() { + this.value = this.initialValue; + } + } + + /** + * 临时覆盖布尔值,关闭时恢复构造时指定的值。 + */ + @RequiredArgsConstructor + public static final class Boolean extends ScopedOverride { + + private final boolean initialValue; + + /** + * 当前布尔状态,关闭后为配置的恢复值。 + */ + @Getter + private boolean active; + + /** + * 设置当前覆盖值,返回可在资源语句中关闭的对象。 + * + * @return 当前作用域对象 + */ + public Boolean with(boolean value) { + this.active = value; + return this; + } + + /** + * 将当前状态设为初始值的反值,返回可关闭的对象。 + * + * @return 当前作用域对象 + */ + public Boolean active() { + return with(!this.initialValue); + } + + @Override + public void close() { + this.active = this.initialValue; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/SerialTaskExecutor.java b/src/main/java/com/modularmc/mmclutils/api/schedule/SerialTaskExecutor.java new file mode 100644 index 0000000..f1a3d52 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/SerialTaskExecutor.java @@ -0,0 +1,51 @@ +package com.modularmc.mmclutils.api.schedule; + +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; + +/** + * 在同一个工作线程按队列顺序执行操作,适合需要保序的写盘或其他后台工作。 + * 提交可来自多个线程。由执行器的所有者在工作线程之外关闭队列。 + */ +public final class SerialTaskExecutor implements AutoCloseable { + + private final ExecutorService executor; + + /** 创建串行队列,使用指定名称启动虚拟线程。 */ + public SerialTaskExecutor(String name) { + executor = Executors.newSingleThreadExecutor(Thread.ofVirtual().name(name).factory()); + } + + /** + * 排队执行一个操作,将返回值或执行异常交给结果对象。 + * 取消结果对象只影响结果的接收,已提交的操作仍会执行。 + * + * @param 操作的结果类型 + * @param operation 在后台线程执行的操作 + * @return 与本次操作关联的结果对象 + * @throws RejectedExecutionException 队列已关闭 + */ + public CompletableFuture submit(Callable operation) { + var result = new CompletableFuture(); + executor.execute(() -> { + try { + result.complete(operation.call()); + } catch (Exception exception) { + result.completeExceptionally(exception); + } catch (Error error) { + result.completeExceptionally(error); + throw error; + } + }); + return result; + } + + /** 停止接收任务并等待已经提交的操作执行完毕。 */ + @Override + public void close() { + executor.close(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/ServerExecutors.java b/src/main/java/com/modularmc/mmclutils/api/schedule/ServerExecutors.java new file mode 100644 index 0000000..aef11b0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/ServerExecutors.java @@ -0,0 +1,37 @@ +package com.modularmc.mmclutils.api.schedule; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; + +/** 每台服务器按标识共享的优先计算线程,停服时取消该服务器的任务。 */ +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) +public final class ServerExecutors { + + private static final Reference2ObjectOpenHashMap> SERVERS = new Reference2ObjectOpenHashMap<>(); + + private ServerExecutors() {} + + /** 在所属服务器线程上取得执行器。后台只应使用与游戏线程分离的数据。 */ + public static synchronized PriorityTaskExecutor priority(MinecraftServer server, Identifier id) { + if (!server.isSameThread()) throw new IllegalStateException("须在所属服务器线程取得执行器"); + return SERVERS.computeIfAbsent(server, ignored -> new Object2ObjectOpenHashMap<>()) + .computeIfAbsent(id, key -> new PriorityTaskExecutor(key.toString())); + } + + @SubscribeEvent + private static void release(ServerStoppedEvent event) { + Object2ObjectOpenHashMap executors; + synchronized (ServerExecutors.class) { + executors = SERVERS.remove(event.getServer()); + } + if (executors != null) executors.values().forEach(PriorityTaskExecutor::close); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/SharedPool.java b/src/main/java/com/modularmc/mmclutils/api/schedule/SharedPool.java new file mode 100644 index 0000000..56229a7 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/SharedPool.java @@ -0,0 +1,174 @@ +package com.modularmc.mmclutils.api.schedule; + +import org.jspecify.annotations.Nullable; + +import java.util.HashMap; +import java.util.Objects; + +/** + * 按键共享、引用计数的资源池,由 {@link Scope#pool} 建立并随那个作用域结束;资源活在自己的作用域里。功能: + *
    + *
  • 建池时给定唯一的工厂;{@link Scope#lease} 借用:第一个借用者到来时用工厂在资源作用域里创建资源,之后的借用者共用;借用者的作用域结束即归还
  • + *
  • 工厂抛异常或返回 null 时,这次建到一半的资源作用域整个撤回、该键不留下任何东西,异常照常抛给借用方,下次借用重新创建;工厂里再借同一个键直接报错
  • + *
  • 最后一个借用归还后等 grace 轮才结束资源作用域,期间再借用则继续沿用;grace 为 0 时立即结束
  • + *
  • {@link Lease#demand}:借用者声明是否需要资源工作;{@link Pooled#demanded} 汇总为"至少一个借用者需要",在派生里读取时自动追踪
  • + *
  • {@link #peek}/{@link #size}:查看已有资源与资源数
  • + *
  • 池所在的作用域结束后全部资源结束,之后的借用拿到的是已结束作用域里的资源
  • + *
  • 池作用域与资源作用域都不是 {@link Scope.Owned},{@link Pooled#scope} 拿到的一方强转后结束不了
  • + *
+ */ +public final class SharedPool { + + /** 首次借用资源键时创建共享值的工厂。 */ + @FunctionalInterface + public interface Factory { + + /** + * 在资源自己的作用域内创建值。 + * + * @param pooled 接收资源作用域与需求状态的池条目 + * @param key 共享资源的键 + * @return 新建的非空资源值 + */ + V create(Pooled pooled, K key); + } + + private final Scope root; + private final int grace; + private final Factory factory; + private final HashMap slots = new HashMap<>(); + + SharedPool(Scope root, int grace, Factory factory) { + this.root = root; + this.grace = Math.max(0, grace); + this.factory = Objects.requireNonNull(factory, "factory"); + root.undo(slots::clear); + } + + @SuppressWarnings("unchecked") + Lease lease(Scope borrower, K key) { + Pooled slot = slots.get(key); + if (slot != null && slot.value == null) throw new IllegalStateException("Re-entrant lease of " + key + " in pool " + root.name()); + if (slot == null || !slot.scope.isActive()) slot = create(key); + slot.release = Task.cancel(slot.release); + slot.refs++; + var lease = new Lease(this, key, slot, (V) slot.value); + borrower.undo(lease::release); + return lease; + } + + private Pooled create(K key) { + Pooled slot = new Pooled(root.inner(key)); + boolean kept = root.isActive(); + slots.put(key, slot); + try { + slot.value = Objects.requireNonNull(factory.create(slot, key), "pooled value"); + } catch (Throwable t) { + slots.remove(key, slot); + slot.scope.end(); + throw t; + } + if (!kept) slots.remove(key, slot); + return slot; + } + + /** 查看当前键下已有的资源。缺失时返回空值,此方法不增加借用计数。 */ + @Nullable + @SuppressWarnings("unchecked") + public V peek(K key) { + Pooled slot = slots.get(key); + return slot == null ? null : (V) slot.value; + } + + /** 返回当前池中的键数,包含宽限期内等待释放的条目。 */ + public int size() { + return slots.size(); + } + + private void returned(K key, Pooled slot) { + if (--slot.refs > 0) return; + if (grace == 0 || !root.isActive()) { + retire(key, slot); + return; + } + slot.release = root.lane().schedule(grace, root, () -> { + slot.release = null; + if (slot.refs == 0) retire(key, slot); + }); + } + + private void retire(K key, Pooled slot) { + slots.remove(key, slot); + slot.scope.end(); + } + + /** 描述一个仍由池管理的共享资源及其作用域和合并需求状态。 */ + public static final class Pooled { + + private final Scope scope; + private final Signal demand = new Signal(); + private @Nullable Object value; + private @Nullable Task release; + private int refs; + private int demands; + + private Pooled(Scope scope) { + this.scope = scope; + } + + /** 返回共享资源的生命周期作用域。 */ + public Scope scope() { + return scope; + } + + /** 查询至少一个租用者是否声明需要该资源,且在响应式派生中登记依赖。 */ + public boolean demanded() { + demand.track(); + return demands > 0; + } + + private void demandChanged(int delta) { + int before = demands; + demands += delta; + if ((before > 0) != (demands > 0)) demand.emit(); + } + } + + /** 持有共享资源的单个租约,租用者作用域结束时自动归还。 */ + public static final class Lease { + + private final SharedPool pool; + private final Object key; + private final Pooled slot; + private final V value; + private boolean demanding; + private boolean released; + + private Lease(SharedPool pool, Object key, Pooled slot, V value) { + this.pool = pool; + this.key = key; + this.slot = slot; + this.value = Objects.requireNonNull(value, "value"); + } + + /** 返回此租约所借到的共享资源。 */ + public V get() { + return value; + } + + /** 将此租用者的需要状态纳入共享资源的合并状态。 */ + public void demand(boolean wanted) { + if (released || wanted == demanding) return; + demanding = wanted; + slot.demandChanged(wanted ? 1 : -1); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void release() { + if (released) return; + demand(false); + released = true; + ((SharedPool) pool).returned(key, slot); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/Signal.java b/src/main/java/com/modularmc/mmclutils/api/schedule/Signal.java new file mode 100644 index 0000000..04b1616 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/Signal.java @@ -0,0 +1,251 @@ +package com.modularmc.mmclutils.api.schedule; + +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 无载荷的依赖信号,作用域派生({@link Scope#watch}、{@link Scope#select}、{@link Scope#when}、{@link Scope#each})据此自动重算。功能: + *
    + *
  • {@link #track}:在派生函数求值期间调用时,把本信号记为该派生的依赖;不在求值期间调用时什么也不做,开销是一次原子读;求值用的记录按线程复用,重算不分配
  • + *
  • {@link #emit}:依赖本信号的派生标脏并合并重算,在车道的一轮里触发的当轮就重算;经 {@link Scope#listen} 挂上的监听立即同步执行;没有订阅时直接返回
  • + *
  • 在订阅方车道以外的线程上触发:不在那个线程上分发,转投到订阅方的车道、下一轮开头再触发,并在首次发生时带调用栈告警;转投用的车道关闭后,改用仍有订阅的另一条车道
  • + *
  • 同一个信号只能被同一个线程上的作用域订阅,另一个线程来订阅直接报错
  • + *
  • 在派生函数求值期间触发信号属于误用:照常分发,记一次异常并在首次发生时带调用栈告警
  • + *
  • 某个订阅抛异常只记入失败记录,不影响其余订阅,也不会抛给触发方
  • + *
  • 分发期间新增的订阅本次不执行,移除的订阅本次不再执行;订阅的增删都是 O(1)
  • + *
  • {@link #subscriberCount}:当前订阅数
  • + *
+ */ +public sealed class Signal permits Poll.PollSignal, KeyedSignal.Slot, Cell.Changed { + + private static final AtomicInteger FRAMES = new AtomicInteger(); + private static final ThreadLocal TRACKERS = new ThreadLocal<>(); + private static final Sub[] NONE = new Sub[0]; + + private Sub[] subs = NONE; + private int size; + private int live; + private int dispatching; + private boolean holes; + private volatile @Nullable TickScheduler home; + + /** 在派生值计算期间记录读取依赖。需要正常的值读取和仅观察状态两种入口时,只在前者调用。 */ + public final void track() { + if (FRAMES.get() == 0) return; + Tracker tracker = TRACKERS.get(); + if (tracker != null && tracker.depth > 0) tracker.frames[tracker.depth - 1].add(this); + } + + /** 向订阅者标记变更,由各订阅者所属的调度器合并并处理通知。 */ + public final void emit() { + TickScheduler lane = home; + if (lane == null) return; + if (lane.foreign()) { + relay(lane); + return; + } + if (FRAMES.get() != 0 && currentFrame() != null) Scope.anomaly("signal emitted inside a derivation function", null); + int n = size; + dispatching++; + try { + for (int i = 0; i < n; i++) { + Sub s = subs[i]; + if (s != null && s.live) deliver(s.action); + } + } finally { + if (--dispatching == 0 && holes) compact(); + } + } + + private void relay(TickScheduler lane) { + Scope.anomaly("signal emitted off its lane thread", null); + lane.schedule(0, null, this::emit); + } + + private static void deliver(Object action) { + try { + if (action instanceof Scope.Hook hook) hook.fire(); + else((Runnable) action).run(); + } catch (Throwable t) { + Scope.fail("signal subscriber", null, t); + } + } + + /** 返回当前信号的订阅数,包括等待调度器处理的订阅。 */ + public final int subscriberCount() { + return live; + } + + @Nullable + final TickScheduler home() { + return home; + } + + void firstSubscribed() {} + + void lastUnsubscribed() {} + + void unclaimed() {} + + final Sub subscribe(TickScheduler lane, Object action) { + TickScheduler current = home; + if (current == null || current.isClosed()) home = lane; + else if (current.foreign()) throw new IllegalStateException("Signal is already subscribed from another thread"); + Sub s = new Sub(this, lane, action); + if (size == subs.length) subs = Arrays.copyOf(subs, Math.max(2, size * 2)); + s.index = size; + subs[size++] = s; + if (live++ == 0) firstSubscribed(); + return s; + } + + private void remove(Sub s) { + if (!s.live) return; + s.live = false; + if (dispatching > 0) { + subs[s.index] = null; + holes = true; + } else { + int last = --size; + Sub moved = subs[last]; + subs[last] = null; + if (moved != s) { + subs[s.index] = moved; + moved.index = s.index; + } + if (last < subs.length >> 2 && subs.length > 16) subs = Arrays.copyOf(subs, subs.length >> 1); + } + if (--live == 0) { + home = null; + lastUnsubscribed(); + return; + } + TickScheduler lane = home; + if (lane != null && lane.isClosed()) rehome(); + } + + private void rehome() { + for (int i = 0; i < size; i++) { + Sub s = subs[i]; + if (s == null || !s.live || s.lane.isClosed()) continue; + home = s.lane; + return; + } + } + + private void compact() { + holes = false; + int j = 0; + for (int i = 0; i < size; i++) { + Sub s = subs[i]; + if (s == null) continue; + s.index = j; + subs[j++] = s; + } + Arrays.fill(subs, j, size, null); + size = j; + } + + static boolean tracking() { + return currentFrame() != null; + } + + @Nullable + static Frame currentFrame() { + if (FRAMES.get() == 0) return null; + Tracker tracker = TRACKERS.get(); + if (tracker == null || tracker.depth == 0) return null; + Frame frame = tracker.frames[tracker.depth - 1]; + return frame.muted ? null : frame; + } + + static Frame enter(TickScheduler lane, int salt) { + Tracker tracker = TRACKERS.get(); + if (tracker == null) TRACKERS.set(tracker = new Tracker()); + Frame frame = tracker.push(); + frame.lane = lane; + frame.salt = salt; + FRAMES.incrementAndGet(); + return frame; + } + + static void exit(Frame frame) { + FRAMES.decrementAndGet(); + Arrays.fill(frame.deps, 0, frame.count, null); + frame.count = 0; + frame.lane = null; + frame.muted = false; + frame.tracker.depth--; + } + + @Nullable + static Frame mute() { + if (FRAMES.get() == 0) return null; + Tracker tracker = TRACKERS.get(); + if (tracker == null || tracker.depth == 0) return null; + Frame frame = tracker.push(); + frame.muted = true; + FRAMES.incrementAndGet(); + return frame; + } + + static void unmute(@Nullable Frame frame) { + if (frame != null) exit(frame); + } + + private static final class Tracker { + + Frame[] frames = new Frame[4]; + int depth; + + Frame push() { + if (depth == frames.length) frames = Arrays.copyOf(frames, depth * 2); + Frame frame = frames[depth]; + if (frame == null) frames[depth] = frame = new Frame(this); + depth++; + return frame; + } + } + + static final class Sub { + + final Signal signal; + final TickScheduler lane; + final Object action; + int index; + boolean live = true; + + Sub(Signal signal, TickScheduler lane, Object action) { + this.signal = signal; + this.lane = lane; + this.action = action; + } + + void remove() { + signal.remove(this); + } + } + + static final class Frame { + + private final Tracker tracker; + TickScheduler lane; + Signal[] deps = new Signal[4]; + int count; + int salt; + boolean muted; + + Frame(Tracker tracker) { + this.tracker = tracker; + } + + void add(Signal signal) { + if (muted) return; + for (int i = 0; i < count; i++) if (deps[i] == signal) return; + if (count == deps.length) deps = Arrays.copyOf(deps, count * 2); + deps[count++] = signal; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/SlidingWindowCounter.java b/src/main/java/com/modularmc/mmclutils/api/schedule/SlidingWindowCounter.java new file mode 100644 index 0000000..ddfbe94 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/SlidingWindowCounter.java @@ -0,0 +1,65 @@ +package com.modularmc.mmclutils.api.schedule; + +import java.util.Arrays; +import java.util.function.LongSupplier; + +/** + * 以滑动时间窗口约束操作速率,按访问时刻推进窗口。 + */ +public class SlidingWindowCounter { + + private final LongSupplier timeSupplier; + + private final long[] usedAmounts; + private final long[] updateTimes; + + private final int countingTimeframe; + + /** 创建固定长度的计量窗口。窗口长度须为正,时间源应单调递增并返回非负值。 */ + public SlidingWindowCounter(LongSupplier timeSupplier, int countingTimeframe) { + this.timeSupplier = timeSupplier; + this.countingTimeframe = countingTimeframe; + + this.usedAmounts = new long[countingTimeframe]; + this.updateTimes = new long[countingTimeframe]; + } + + /** 按当前时间统计有效窗口内的用量,窗口起点之前及起点上的槽位不参与统计。 */ + public long getUsedSum() { + long excludeUntilTime = timeSupplier.getAsLong() - countingTimeframe; + long sum = 0L; + + for (int i = 0; i < countingTimeframe; i++) { + if (updateTimes[i] <= excludeUntilTime) continue; + sum += usedAmounts[i]; + } + + return sum; + } + + /** 用给定量更新当前时间所在槽位。时间推进到新的槽位时丢弃该位置的旧用量。 */ + public void addUsed(long amount) { + long currentTime = timeSupplier.getAsLong(); + int idx = (int) (currentTime % countingTimeframe); + + if (updateTimes[idx] != currentTime) + usedAmounts[idx] = 0L; + + usedAmounts[idx] += amount; + updateTimes[idx] = currentTime; + } + + /** 清零窗口中保存的用量,保留已分配的槽位。 */ + public void clear() { + Arrays.fill(usedAmounts, 0L); + } + + /** 复制窗口和历史用量。新计数器独立写入,继续使用同一时间源。 */ + public SlidingWindowCounter copy() { + var copied = new SlidingWindowCounter(this.timeSupplier, this.countingTimeframe); + System.arraycopy(this.usedAmounts, 0, copied.usedAmounts, 0, usedAmounts.length); + System.arraycopy(this.updateTimes, 0, copied.updateTimes, 0, updateTimes.length); + + return copied; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/Task.java b/src/main/java/com/modularmc/mmclutils/api/schedule/Task.java new file mode 100644 index 0000000..ce6edf6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/Task.java @@ -0,0 +1,49 @@ +package com.modularmc.mmclutils.api.schedule; + +import org.jspecify.annotations.Nullable; + +/** + * 一次性或周期任务的取消与周期查询契约。 + * 任务生命周期与执行线程由创建它的调度器控制。 + */ +public interface Task { + + /** 判断任务是否仍有效并可执行。 */ + boolean isActive(); + + /** 使任务失效;已经开始执行的操作不会被强制中断。 */ + void cancel(); + + /** 返回周期 Tick 数,一次性任务返回零。 */ + int period(); + + /** + * 请求更改周期任务的执行间隔。 + * 新间隔在当前执行结束后生效,一次性任务不支持修改。 + * + * @param period 新周期 Tick 数,低于一的数值按一处理 + * @throws IllegalStateException 当前任务不支持周期修改 + */ + void setPeriod(int period); + + /** + * 取消非空任务并返回空值,便于在同一赋值中清空句柄。 + * + * @param task 要取消的任务,可以为空 + * @return 始终为空 + */ + static @Nullable Task cancel(@Nullable Task task) { + if (task != null) task.cancel(); + return null; + } + + /** + * 判断非空任务是否仍有效。 + * + * @param task 要查询的任务,可以为空 + * @return 任务非空且有效时为 {@code true} + */ + static boolean isActive(@Nullable Task task) { + return task != null && task.isActive(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/TaskFailures.java b/src/main/java/com/modularmc/mmclutils/api/schedule/TaskFailures.java new file mode 100644 index 0000000..7d28b2f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/TaskFailures.java @@ -0,0 +1,31 @@ +package com.modularmc.mmclutils.api.schedule; + +/** + * 在调用边界保留可处理的异常,并让 JVM 致命错误继续传播。 + * + *

+ * 适用于捕获 {@link Throwable} 的集成边界。 + * 调用方可对普通失败记录日志、回滚或隔离当前操作。 + */ +public final class TaskFailures { + + private TaskFailures() {} + + /** + * 重新抛出致命错误,并恢复中断异常携带的线程中断标记。 + * + *

+ * 边界可以处理已捕获的 {@link InterruptedException},线程中断标记仍应交还给调用方。 + * + * @param throwable 调用过程中捕获的异常 + * @throws VirtualMachineError 捕获异常属于 JVM 致命错误 + */ + public static void rethrowIfFatal(Throwable throwable) { + if (throwable instanceof VirtualMachineError virtualMachineError) { + throw virtualMachineError; + } + if (throwable instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/TickBatch.java b/src/main/java/com/modularmc/mmclutils/api/schedule/TickBatch.java new file mode 100644 index 0000000..cf8ad6e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/TickBatch.java @@ -0,0 +1,85 @@ +package com.modularmc.mmclutils.api.schedule; + +import com.modularmc.mmclutils.api.level.LevelStore; + +import net.minecraft.world.level.Level; + +import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet; + +import java.util.Objects; +import java.util.function.Consumer; + +/** + * 每个维度一份的去重批量队列,在下一轮主线程车道上统一冲刷。功能: + *

    + *
  • {@link #create}:新建一种批量,给定逐个处理的回调;通常声明成静态常量
  • + *
  • {@link #add}:加入一个对象,同一轮内重复加入只算一次,按首次加入的顺序冲刷;队列从空变非空时才排一次冲刷任务,空闲时没有开销
  • + *
  • {@link #remove}/{@link #contains}:从待冲刷的对象里去掉、查询
  • + *
  • 冲刷时先把整批换出再逐个处理,处理中再加入的对象进下一批;维度卸载时整批丢弃
  • + *
  • 只能在该维度的主线程上调用
  • + *
+ */ +public final class TickBatch { + + private final Consumer flush; + private final LevelStore> queues; + + private TickBatch(Consumer flush) { + this.flush = Objects.requireNonNull(flush, "flush"); + this.queues = LevelStore.createWithLevel(level -> new Queue<>(this.flush, Schedulers.of(level))); + } + + /** 为同一逐项回调创建批处理入口,内部按维度保留独立队列。 */ + public static TickBatch create(Consumer flush) { + return new TickBatch<>(flush); + } + + /** 排入此维度的下一批。按引用去重,已经卸载的维度不会继续接收。 */ + public void add(Level level, T item) { + if (LevelStore.isReleased(level)) return; + queues.get(level).add(Objects.requireNonNull(item, "item")); + } + + /** 从待处理的下一批删除对象,返回是否成功删除。 */ + public boolean remove(Level level, T item) { + Queue q = queues.getIfPresent(level); + return q != null && q.pending.remove(item); + } + + /** 检查同一对象是否还在该维度的待处理队列中。 */ + public boolean contains(Level level, T item) { + Queue q = queues.getIfPresent(level); + return q != null && q.pending.contains(item); + } + + static final class Queue implements Runnable { + + private final Consumer flush; + private final TickScheduler scheduler; + private final CoalescedTask task = new CoalescedTask(this); + ReferenceLinkedOpenHashSet pending = new ReferenceLinkedOpenHashSet<>(); + private ReferenceLinkedOpenHashSet spare = new ReferenceLinkedOpenHashSet<>(); + + Queue(Consumer flush, TickScheduler scheduler) { + this.flush = flush; + this.scheduler = scheduler; + } + + void add(T item) { + if (pending.add(item) && !task.isQueued()) scheduler.submit(task); + } + + @Override + public void run() { + ReferenceLinkedOpenHashSet batch = pending; + pending = spare; + spare = batch; + try { + for (T item : batch) flush.accept(item); + } finally { + batch.clear(); + if (!pending.isEmpty() && !task.isQueued()) scheduler.submit(task); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/TickScheduler.java b/src/main/java/com/modularmc/mmclutils/api/schedule/TickScheduler.java new file mode 100644 index 0000000..5cf76f0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/TickScheduler.java @@ -0,0 +1,757 @@ +package com.modularmc.mmclutils.api.schedule; + +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.entity.BlockEntity; + +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import org.jspecify.annotations.Nullable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.Arrays; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * 按轮推进的任务调度器;每个维度的主线程、各异步车道以及全服、客户端车道各有一个,经 {@link Schedulers} 取得。功能: + *
    + *
  • {@link #schedule}:一次性任务,delay 轮后执行;在轮外提交时 delay 为 0 指即将到来的那一轮,在轮内提交时最早下一轮;同一轮按提交顺序执行
  • + *
  • {@link #scheduleAt}/{@link #currentTick}:按绝对轮次排一次性任务,早于可执行的最早一轮时顺延到那一轮;currentTick + * 在轮内是当前轮,在轮外是即将到来的那一轮,只在调度线程上有意义
  • + *
  • {@link #submit}:合并任务 {@link CoalescedTask},排队期间再提交不重复加入;带延迟时窗口内多次提交只在窗口末尾执行一次
  • + *
  • {@link #repeat}:周期任务,按 {@link Cadence} + * 的周期与相位执行;自动相位的任务第一次在挂上后最早可执行的那一轮执行,之后在同周期的各相位之间轮流分配;所有者是方块实体或实体时随其移除停止,是作用域时随其结束停止,until 为真时停止
  • + *
  • {@link Task#setPeriod}:改周期,在该任务下一次执行之后生效
  • + *
  • 任何线程都能提交和取消:在调度线程上直接挂入,其它线程经收件箱在下一轮开头并入;任务只在调度线程上执行
  • + *
  • {@link #runRound}:推进一轮,只访问本轮到期的条目;周期任务按周期分组、组内按相位分桶,条目常驻不动;一次性任务与超长周期走 256 槽时间轮
  • + *
  • {@link #close}:关闭后已排的任务全部失效,之后提交的直接是已取消状态,挂在本车道上的无父作用域全部结束;任务抛出的异常交给构造时给的处理器;在车道线程以外、又不在一轮里关闭时记一次误用,作用域的清理推迟到车道线程下一次推进时执行,之后再也不推进的车道上,这些作用域不会结束
  • + *
  • {@link #foreign}:当前线程是否不是驱动本车道的线程;车道还没被任何线程认领时对所有线程都为假;{@link Schedulers} 建维度与全局车道时就认领服务端或客户端主线程
  • + *
  • 所有者是作用域的任务在作用域结束后最多留在时间轮里 256 轮就被摘掉,周期任务最多留一个周期
  • + *
  • {@link #forEachScope}:遍历挂在本车道上的无父作用域,只在调度线程上调用
  • + *
+ */ +public final class TickScheduler { + + /** 接收调度任务执行期间抛出的异常和对应的任务所有者。 */ + @FunctionalInterface + public interface FailureHandler { + + /** + * 处理一次调度失败。 + * + * @param error 任务抛出的异常 + * @param owner 注册任务时附带的所有者,可以为空 + */ + void failed(Throwable error, @Nullable Object owner); + } + + static final int WHEEL_SIZE = 256; + static final int MAX_GROUP_PERIOD = 4096; + static final int SETTLE_DEPTH = 16; + static final int SETTLE = -2; + private static final int WHEEL_MASK = WHEEL_SIZE - 1; + + private static final byte ONCE = 0; + private static final byte REPEAT = 1; + private static final byte COALESCED = 2; + private static final byte OWNER_NONE = 0; + private static final byte OWNER_BLOCK_ENTITY = 1; + private static final byte OWNER_ENTITY = 2; + private static final byte OWNER_SCOPE = 3; + private static final Scope[] NO_ROOTS = new Scope[0]; + private static final String SPILLED = "derivations re-triggered each other more than " + SETTLE_DEPTH + " times in one round"; + private static final String CLOSED_OFF_LANE = "lane closed off its lane thread outside a round; its scopes end when the lane thread next drives it"; + + static final TickScheduler CLOSED = closedScheduler(); + + private final boolean sticky; + private final FailureHandler failures; + private volatile @Nullable Thread affinity; + private volatile @Nullable Thread roundThread; + private volatile long round; + private volatile boolean closed; + private volatile boolean cleared; + private int linked; + private boolean inRound; + private int depth; + private long largeCursor; + + private final Entry[] wheelHead = new Entry[WHEEL_SIZE]; + private final Entry[] wheelTail = new Entry[WHEEL_SIZE]; + private Group[] groups = new Group[0]; + private final Int2ObjectOpenHashMap groupByPeriod = new Int2ObjectOpenHashMap<>(); + private final Object inboxLock = new Object(); + private @Nullable Entry inboxHead; + private @Nullable Entry inboxTail; + private @Nullable Long2ObjectOpenHashMap polls; + private int salts; + private Scope[] roots = NO_ROOTS; + private int rootCount; + + TickScheduler(boolean sticky, FailureHandler failures) { + this.sticky = sticky; + this.failures = Objects.requireNonNull(failures, "failures"); + } + + private static TickScheduler closedScheduler() { + TickScheduler s = new TickScheduler(false, (error, owner) -> {}); + s.closed = true; + return s; + } + + /** 提交一次性任务,安排在最早可用的一轮。返回的句柄可在任何线程取消。 */ + public Task schedule(Runnable action) { + return schedule(0, null, action); + } + + /** 延迟指定轮数执行一次。轮内提交时,零延迟也从下一轮开始计算。 */ + public Task schedule(int delay, Runnable action) { + return schedule(delay, null, action); + } + + /** 提交可随所有者失效的一次性任务。方块实体或实体移除、作用域结束后,任务到期时自动跳过。 */ + public Task schedule(int delay, @Nullable Object owner, Runnable action) { + Entry e = new Entry(this, ONCE, owner, Objects.requireNonNull(action, "action"), null); + e.delay = Math.max(0, delay); + enqueue(e); + return e; + } + + /** 按绝对轮次执行一次。若该轮已无法接受任务,顺延到最早可用的一轮。 */ + public Task scheduleAt(long tick, @Nullable Object owner, Runnable action) { + Entry e = new Entry(this, ONCE, owner, Objects.requireNonNull(action, "action"), null); + e.delay = -1; + e.due = tick; + enqueue(e); + return e; + } + + /** 返回当前执行的轮次,轮外返回下一轮。此时序只在调度线程上有效。 */ + public long currentTick() { + return inRound ? round : round + 1; + } + + /** 按给定周期和相位重复执行,使用返回的句柄取消。 */ + public Task repeat(Cadence cadence, Runnable action) { + return repeat(cadence, null, action); + } + + /** 按给定周期和相位重复执行,所有者失效时自动停止。 */ + public Task repeat(Cadence cadence, @Nullable Object owner, Runnable action) { + RepeatEntry e = new RepeatEntry(this, owner, Objects.requireNonNull(action, "action"), null, null, cadence); + enqueue(e); + return e; + } + + /** 每次到期先检查可选的停止条件,再将所有者传给任务。条件满足时停止,且本轮跳过任务。 */ + @SuppressWarnings("unchecked") + public Task repeat(Cadence cadence, O owner, Consumer action, @Nullable Predicate until) { + RepeatEntry e = new RepeatEntry(this, Objects.requireNonNull(owner, "owner"), null, (Consumer) Objects.requireNonNull(action, "action"), + (Predicate) until, cadence); + enqueue(e); + return e; + } + + /** 把任务安排在最早可用的一轮。同一个任务排队期间的提交会合并。 */ + public void submit(CoalescedTask task) { + task.submitTo(this, 0); + } + + /** 从首次提交计算等待轮数,后续提交与这次合并并沿用原执行轮次。 */ + public void submit(CoalescedTask task, int delay) { + task.submitTo(this, Math.max(0, delay)); + } + + void settle(CoalescedTask task) { + task.submitTo(this, SETTLE); + } + + boolean sticky() { + return sticky; + } + + /** 判断当前线程是否与已绑定的调度线程不同。调度器尚未绑定线程时返回 {@code false}。 */ + public boolean foreign() { + Thread driver = sticky ? affinity : roundThread; + return driver != null && driver != Thread.currentThread(); + } + + /** 返回最近一次开始执行的轮次。可从其他线程读取诊断值。 */ + public long round() { + return round; + } + + /** 判断调度器是否已请求关闭。关闭期间仍可能在释放所属作用域。 */ + public boolean isClosed() { + return closed; + } + + /** 使排队中的任务失效并停止接受新任务。作用域清理由调度线程完成。 */ + public void close() { + closed = true; + if (!sticky || inRound && onDriverThread()) return; + Thread driver = affinity; + if (driver == null || driver == Thread.currentThread()) { + clear(); + return; + } + if (roundThread == null && !cleared) Scope.anomaly(CLOSED_OFF_LANE, this); + } + + void runRound() { + if (closed) { + if (!cleared) clear(); + return; + } + Thread t = Thread.currentThread(); + if (sticky && affinity != t) affinity = t; + roundThread = t; + inRound = true; + long r = round + 1; + round = r; + try { + drainInbox(r); + Group[] gs = groups; + for (Group g : gs) { + if (closed) break; + runBucket(g, (int) (r % g.period), r); + } + if (!closed) runWheel((int) (r & WHEEL_MASK), r); + } finally { + inRound = false; + depth = 0; + roundThread = null; + if (closed) clear(); + } + } + + boolean advanceIfIdle() { + if (closed) return true; + long r = round + 1; + synchronized (inboxLock) { + if (inboxHead != null) return false; + } + if (linked != 0) { + for (Group g : groups) { + if (g.head[(int) (r % g.period)] != null) return false; + } + for (Entry e = wheelHead[(int) (r & WHEEL_MASK)]; e != null; e = e.next) { + if (e.due <= r) return false; + } + } + round = r; + return true; + } + + void clear() { + cleared = true; + Arrays.fill(wheelHead, null); + Arrays.fill(wheelTail, null); + groups = new Group[0]; + groupByPeriod.clear(); + synchronized (inboxLock) { + inboxHead = null; + inboxTail = null; + } + linked = 0; + polls = null; + Scope[] ending = roots; + int n = rootCount; + roots = NO_ROOTS; + rootCount = 0; + for (int i = n - 1; i >= 0; i--) { + ending[i].slot = -1; + ending[i].end(); + } + } + + boolean adopt(Scope root) { + if (closed) return false; + if (rootCount == roots.length) roots = Arrays.copyOf(roots, Math.max(4, rootCount * 2)); + root.slot = rootCount; + roots[rootCount++] = root; + return true; + } + + void release(Scope root) { + int i = root.slot; + if (i < 0 || i >= rootCount || roots[i] != root) return; + int last = --rootCount; + Scope moved = roots[last]; + roots[last] = null; + if (moved != root) { + roots[i] = moved; + moved.slot = i; + } + root.slot = -1; + if (last < roots.length >> 2 && roots.length > 64) roots = Arrays.copyOf(roots, roots.length >> 1); + } + + Poll.PollSignal poll(int period, int phase) { + if (closed) return new Poll.PollSignal(this, period, phase); + var signals = polls; + if (signals == null) polls = signals = new Long2ObjectOpenHashMap<>(); + long key = (long) period << 32 | phase; + var signal = signals.get(key); + if (signal == null) signals.put(key, signal = new Poll.PollSignal(this, period, phase)); + return signal; + } + + int nextSalt() { + return salts++; + } + + void claim() { + claim(Thread.currentThread()); + } + + void claim(Thread thread) { + if (sticky && affinity == null) affinity = thread; + } + + /** 遍历此调度器直接持有的根作用域。请在调度线程调用。 */ + public void forEachScope(Consumer action) { + Scope[] rootsToVisit = Arrays.copyOf(roots, rootCount); + for (Scope root : rootsToVisit) action.accept(root); + } + + int linkedCount() { + return linked; + } + + int groupCount() { + return groups.length; + } + + private boolean onDriverThread() { + Thread t = Thread.currentThread(); + return sticky ? t == affinity : t == roundThread; + } + + private void enqueue(Entry e) { + if (closed) { + e.active = false; + return; + } + if (onDriverThread()) { + link(e, round + 1); + return; + } + pushInbox(e); + } + + private void pushInbox(Entry e) { + synchronized (inboxLock) { + e.inboxNext = null; + if (inboxTail == null) inboxHead = e; + else inboxTail.inboxNext = e; + inboxTail = e; + } + } + + void enqueueCoalesced(CoalescedTask task, int delay) { + boolean settle = delay == SETTLE; + if (onDriverThread()) { + Entry e = task.entryForLink(this); + e.delay = settle ? 0 : delay; + int hop = depth + 1; + if (settle && inRound && !task.lagging) { + if (hop <= SETTLE_DEPTH) { + e.hop = (byte) hop; + link(e, round); + return; + } + task.lagging = true; + e.hop = 0; + link(e, round + 1); + Scope.anomaly(SPILLED, e.owner); + return; + } + e.hop = 0; + link(e, round + 1); + return; + } + Entry e = task.entry; + e.delay = settle ? 0 : delay; + pushInbox(e); + } + + private void drainInbox(long r) { + Entry e; + synchronized (inboxLock) { + e = inboxHead; + inboxHead = null; + inboxTail = null; + } + while (e != null) { + Entry next = e.inboxNext; + e.inboxNext = null; + if (e.kind == COALESCED) { + CoalescedTask task = e.coalesced; + if (task != null && task.queuedIn() == this && task.entry == e) { + int delay = e.delay; + Entry linkable = task.entryForLink(this); + linkable.delay = delay; + linkable.hop = 0; + link(linkable, r); + } + } else if (e.active) { + link(e, r); + } + e = next; + } + } + + private void link(Entry e, long base) { + e.scheduler = this; + if (e.kind == REPEAT) { + RepeatEntry re = (RepeatEntry) e; + re.notBefore = base; + placeRepeat(re, base); + } else { + e.due = e.delay < 0 ? Math.max(e.due, base) : base + e.delay; + wheelAppend(e); + } + } + + private void placeRepeat(RepeatEntry e, long base) { + int p = e.period; + if (e.fresh) { + e.fresh = false; + if (e.autoPhase && p > 1) { + e.group = null; + e.due = base; + wheelAppend(e); + return; + } + } + if (p > MAX_GROUP_PERIOD) { + long phase = e.autoPhase ? Math.floorMod(largeCursor++, p) : e.phase; + e.autoPhase = false; + e.phase = (int) phase; + e.group = null; + e.due = base + Math.floorMod(phase - base, (long) p); + wheelAppend(e); + return; + } + Group g = groupByPeriod.get(p); + if (g == null) { + g = new Group(p); + groupByPeriod.put(p, g); + Group[] grown = Arrays.copyOf(groups, groups.length + 1); + grown[groups.length] = g; + Arrays.sort(grown, (a, b) -> Integer.compare(a.period, b.period)); + groups = grown; + } + int phase = e.autoPhase ? g.nextPhase() : e.phase; + e.autoPhase = false; + e.group = g; + g.append(e, phase); + e.linked = true; + linked++; + } + + private void wheelAppend(Entry e) { + int slot = (int) (e.due & WHEEL_MASK); + Entry tail = wheelTail[slot]; + e.next = null; + if (tail == null) wheelHead[slot] = e; + else tail.next = e; + wheelTail[slot] = e; + e.linked = true; + linked++; + } + + private void runBucket(Group g, int bucket, long r) { + RepeatEntry prev = null; + RepeatEntry e = g.head[bucket]; + while (e != null) { + if (e.notBefore > r) { + prev = e; + e = (RepeatEntry) e.next; + continue; + } + if (!e.active || ownerGone(e) || e.until != null && e.until.test(e.owner)) { + e.active = false; + e = g.unlink(bucket, prev, e); + linked--; + continue; + } + run(e); + if (closed) return; + if (!e.active) { + e = g.unlink(bucket, prev, e); + linked--; + continue; + } + int np = e.pendingPeriod; + if (np != 0) { + e.pendingPeriod = 0; + RepeatEntry next = g.unlink(bucket, prev, e); + linked--; + e.period = np; + e.autoPhase = false; + e.phase = (int) Math.floorMod(r, (long) np); + e.notBefore = r + 1; + placeRepeat(e, r + 1); + e = next; + continue; + } + prev = e; + e = (RepeatEntry) e.next; + } + } + + private void runWheel(int slot, long r) { + Entry prev = null; + Entry e = wheelHead[slot]; + while (e != null) { + if (e.due > r) { + if (!e.active || e.ownerKind == OWNER_SCOPE && !((Scope) e.owner).isActive()) { + e = discard(slot, prev, e); + continue; + } + prev = e; + e = e.next; + continue; + } + Entry next = e.next; + if (prev == null) wheelHead[slot] = next; + else prev.next = next; + if (wheelTail[slot] == e) wheelTail[slot] = prev; + e.next = null; + e.linked = false; + linked--; + switch (e.kind) { + case ONCE -> { + if (e.active) { + e.active = false; + if (!ownerGone(e)) run(e); + } + } + case COALESCED -> { + CoalescedTask task = e.coalesced; + if (e.active && task != null && task.entry == e && task.dequeue(this) && !ownerGone(e)) run(e); + } + default -> runLarge((RepeatEntry) e, r); + } + if (closed) return; + e = prev == null ? wheelHead[slot] : prev.next; + } + } + + private Entry discard(int slot, @Nullable Entry prev, Entry e) { + Entry next = e.next; + if (prev == null) wheelHead[slot] = next; + else prev.next = next; + if (wheelTail[slot] == e) wheelTail[slot] = prev; + e.next = null; + e.linked = false; + linked--; + CoalescedTask task = e.coalesced; + if (task != null && task.entry == e) task.dequeue(this); + e.active = false; + return next; + } + + private void runLarge(RepeatEntry e, long r) { + if (!e.active || ownerGone(e) || e.until != null && e.until.test(e.owner)) { + e.active = false; + return; + } + run(e); + if (!e.active || closed) return; + int np = e.pendingPeriod; + if (np != 0) { + e.pendingPeriod = 0; + e.period = np; + e.autoPhase = false; + e.phase = (int) Math.floorMod(r, (long) np); + e.notBefore = r + 1; + placeRepeat(e, r + 1); + return; + } + if (e.autoPhase) { + e.notBefore = r + 1; + placeRepeat(e, r + 1); + return; + } + e.due = r + e.period; + wheelAppend(e); + } + + private void run(Entry e) { + depth = e.hop; + try { + e.invoke(); + } catch (Throwable t) { + failures.failed(t, e.owner); + } + } + + private static boolean ownerGone(Entry e) { + return switch (e.ownerKind) { + case OWNER_BLOCK_ENTITY -> ((BlockEntity) e.owner).isRemoved(); + case OWNER_ENTITY -> ((Entity) e.owner).isRemoved(); + case OWNER_SCOPE -> !((Scope) e.owner).isActive(); + default -> false; + }; + } + + private static byte ownerKind(@Nullable Object owner) { + if (owner instanceof BlockEntity) return OWNER_BLOCK_ENTITY; + if (owner instanceof Entity) return OWNER_ENTITY; + if (owner instanceof Scope) return OWNER_SCOPE; + return OWNER_NONE; + } + + static Entry coalescedEntry(CoalescedTask task, @Nullable Object owner, Runnable action) { + return new Entry(CLOSED, COALESCED, owner, action, task); + } + + static final class Group { + + final int period; + final RepeatEntry[] head; + final RepeatEntry[] tail; + private int cursor; + + Group(int period) { + this.period = period; + this.head = new RepeatEntry[period]; + this.tail = new RepeatEntry[period]; + } + + int nextPhase() { + int p = cursor; + cursor = p + 1 == period ? 0 : p + 1; + return p; + } + + void append(RepeatEntry e, int bucket) { + e.phase = bucket; + e.next = null; + RepeatEntry t = tail[bucket]; + if (t == null) head[bucket] = e; + else t.next = e; + tail[bucket] = e; + } + + RepeatEntry unlink(int bucket, @Nullable RepeatEntry prev, RepeatEntry e) { + RepeatEntry next = (RepeatEntry) e.next; + if (prev == null) head[bucket] = next; + else prev.next = next; + if (tail[bucket] == e) tail[bucket] = prev; + e.next = null; + e.linked = false; + e.group = null; + return next; + } + } + + static class Entry implements Task { + + private static final VarHandle ACTIVE; + + static { + try { + ACTIVE = MethodHandles.lookup().findVarHandle(Entry.class, "active", boolean.class); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + final byte kind; + final byte ownerKind; + byte hop; + boolean active = true; + boolean linked; + final @Nullable Object owner; + final @Nullable Runnable action; + final @Nullable CoalescedTask coalesced; + TickScheduler scheduler; + int delay; + long due; + @Nullable + Entry next; + @Nullable + Entry inboxNext; + + Entry(TickScheduler scheduler, byte kind, @Nullable Object owner, @Nullable Runnable action, @Nullable CoalescedTask coalesced) { + this.scheduler = scheduler; + this.kind = kind; + this.owner = owner; + this.ownerKind = ownerKind(owner); + this.action = action; + this.coalesced = coalesced; + } + + void invoke() { + action.run(); + } + + @Override + public boolean isActive() { + return (boolean) ACTIVE.getAcquire(this) && !scheduler.closed && (ownerKind != OWNER_SCOPE || ((Scope) owner).isActive()); + } + + @Override + public void cancel() { + ACTIVE.setRelease(this, false); + } + + @Override + public int period() { + return 0; + } + + @Override + public void setPeriod(int period) { + throw new IllegalStateException("not a repeating task"); + } + } + + static final class RepeatEntry extends Entry { + + final @Nullable Consumer consumer; + final @Nullable Predicate until; + volatile int pendingPeriod; + int period; + int phase; + boolean autoPhase; + boolean fresh = true; + long notBefore; + @Nullable + Group group; + + RepeatEntry(TickScheduler scheduler, @Nullable Object owner, @Nullable Runnable action, @Nullable Consumer consumer, + @Nullable Predicate until, Cadence cadence) { + super(scheduler, REPEAT, owner, action, null); + this.consumer = consumer; + this.until = until; + this.period = cadence.period(); + this.autoPhase = cadence.isAutoPhase(); + this.phase = autoPhase ? 0 : cadence.phase(); + } + + @Override + void invoke() { + if (consumer != null) consumer.accept(owner); + else action.run(); + } + + @Override + public int period() { + int p = pendingPeriod; + return p != 0 ? p : period; + } + + @Override + public void setPeriod(int period) { + int p = Math.max(1, period); + pendingPeriod = p == this.period ? 0 : p; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/schedule/WaitList.java b/src/main/java/com/modularmc/mmclutils/api/schedule/WaitList.java new file mode 100644 index 0000000..ea72332 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/schedule/WaitList.java @@ -0,0 +1,148 @@ +package com.modularmc.mmclutils.api.schedule; + +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; +import java.util.Objects; +import java.util.function.Consumer; + +/** + * 侵入式等待表:等待者自带节点,登记与撤销都是 O(1) 且不分配,触发时同步执行并移出。功能: + *
    + *
  • {@link Waiter}:一个等待者的节点,由等待方长期持有、反复使用;同一时刻最多在一张表里
  • + *
  • {@link #await}:把节点登记到本表;已在本表时不动,在别的表里时先从那张表撤销
  • + *
  • {@link Waiter#cancel}:撤销登记,没在等待时什么也不做;{@link Waiter#waiting} 是否在等待,{@link Waiter#list} 在哪张表里
  • + *
  • {@link #fire}:把触发开始时在表里的节点逐个移出并交给动作,后登记的先执行;动作里新登记的节点留到下一次触发,动作里撤销了尚未轮到的节点就不再执行它,动作里再次触发本表是安全的;动作抛异常时异常交给调用方,尚未轮到的节点留在表里
  • + *
  • {@link #isEmpty}/{@link #size}:当前登记数;{@link #trim}:表空时放掉峰值时撑大的数组
  • + *
  • 不是线程安全的,只在拥有它的线程上使用;开断言(-ea)时表在首次使用时记下线程,之后别的线程上 await、cancel、对非空表 fire 直接断言失败,生产环境不开断言时零成本
  • + *
  • 用法:一个 Waiter 只服务同一种表,要同时挂在两种表上就持有两个 Waiter;fire 的动作用无捕获的静态常量,调用前先判 {@link #isEmpty}
  • + *
+ */ +public final class WaitList { + + private static final Waiter[] NONE = new Waiter[0]; + + private Waiter[] items = none(); + private int size; + private int fireId; + private @Nullable Thread home; + + @SuppressWarnings("unchecked") + private static Waiter[] none() { + return (Waiter[]) NONE; + } + + private void own() { + assert owned() : "WaitList used from thread " + Thread.currentThread().getName() + " but it belongs to " + home.getName(); + } + + private boolean owned() { + Thread t = Thread.currentThread(); + if (home == null) home = t; + return home == t; + } + + /** 将等待项挂到本队列。若它此前属于其他队列,先从原队列摘除。 */ + public void await(Waiter waiter) { + own(); + WaitList at = waiter.list; + if (at == this) return; + if (at != null) { + at.own(); + at.remove(waiter); + } + int n = size; + if (n == items.length) items = Arrays.copyOf(items, Math.max(4, n << 1)); + items[n] = waiter; + waiter.slot = n; + waiter.stamp = fireId; + waiter.list = this; + size = n + 1; + } + + /** 唤醒当前等待项并清空本批。处理期间新登记的等待项留待下一批。 */ + public void fire(Consumer action) { + if (size == 0) return; + own(); + int mark = ++fireId; + for (int i = size - 1; i >= 0; i--) { + if (i >= size) { + i = size; + continue; + } + Waiter waiter = items[i]; + if (waiter.stamp - mark >= 0) continue; + remove(waiter); + action.accept(waiter.owner); + } + } + + /** 判断当前是否有等待项。 */ + public boolean isEmpty() { + return size == 0; + } + + /** 返回当前队列含有的等待项数。 */ + public int size() { + return size; + } + + /** 队列为空时释放内部已分配的存储。 */ + public void trim() { + if (size == 0) items = none(); + } + + private void remove(Waiter waiter) { + int slot = waiter.slot; + int last = --size; + Waiter tail = items[last]; + items[last] = null; + if (tail != waiter) { + items[slot] = tail; + tail.slot = slot; + } + waiter.list = null; + } + + /** + * 可在等待表之间转移并复用的单个等待节点。 + * 登记、触发和取消均须由等待表所属线程执行。 + * + * @param 等待者持有的对象类型 + */ + public static final class Waiter { + + private final T owner; + private @Nullable WaitList list; + private int slot; + private int stamp; + + /** + * 创建未登记的等待节点。 + * + * @param owner 等待触发时提供给回调的非空对象 + */ + public Waiter(T owner) { + this.owner = Objects.requireNonNull(owner, "owner"); + } + + /** 判断该节点当前是否登记在等待表中。 */ + public boolean waiting() { + return list != null; + } + + /** 返回当前登记的等待表,尚未登记时返回空值。 */ + @Nullable + public WaitList list() { + return list; + } + + /** 从当前等待表移除此节点;未登记时不执行操作。 */ + public void cancel() { + WaitList at = list; + if (at == null) return; + at.own(); + at.remove(this); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/shape/VoxelOccupancy.java b/src/main/java/com/modularmc/mmclutils/api/shape/VoxelOccupancy.java new file mode 100644 index 0000000..e956165 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/shape/VoxelOccupancy.java @@ -0,0 +1,44 @@ +package com.modularmc.mmclutils.api.shape; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +/** 用原始类型分页存储占用区间的端点。采集结束后由后台只读访问。 */ +public final class VoxelOccupancy { + + private static final int PAGE_BITS = 10; + private static final int PAGE_SIZE = 1 << PAGE_BITS; + private final ObjectArrayList pages = new ObjectArrayList<>(); + private int size; + + /** 在采集线程按升序成对追加区间起点和终点。区间包含起点,排除终点。 */ + public void append(long value) { + int offset = size & (PAGE_SIZE - 1); + if (offset == 0) pages.add(new long[PAGE_SIZE]); + pages.get(size++ >> PAGE_BITS)[offset] = value; + } + + /** 判断端点列表是否为空。 */ + public boolean empty() { + return size == 0; + } + + /** 根据已发布的升序区间端点判断指定单元索引是否被占用。 */ + public boolean contains(long cell) { + int low = 0, high = size; + while (low < high) { + int middle = (low + high) >>> 1; + if (get(middle) <= cell) low = middle + 1; + else high = middle; + } + return (low & 1) != 0; + } + + /** 判断所有单元是否由一个从零开始的连续区间覆盖。 */ + public boolean fills(long cells) { + return size == 2 && get(0) == 0 && get(1) == cells; + } + + private long get(int index) { + return pages.get(index >> PAGE_BITS)[index & (PAGE_SIZE - 1)]; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/shape/VoxelShapeCache.java b/src/main/java/com/modularmc/mmclutils/api/shape/VoxelShapeCache.java new file mode 100644 index 0000000..62babb2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/shape/VoxelShapeCache.java @@ -0,0 +1,110 @@ +package com.modularmc.mmclutils.api.shape; + +import com.modularmc.mmclutils.mixin.mc.VoxelShapeAccessor; + +import net.minecraft.core.Direction; +import net.minecraft.world.phys.shapes.DiscreteVoxelShape; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +import it.unimi.dsi.fastutil.doubles.DoubleList; +import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; +import org.jspecify.annotations.Nullable; + +/** 在所属线程按形状实例缓存采样结果。坐标复制和网格读取均按时限分步进行。 */ +public final class VoxelShapeCache { + + private static final long MAX_CELLS = 65_536; + private static final int MAX_COORDINATES = 4_096; + private static final int MAX_CACHED_SHAPES = 128; + private final Reference2ObjectLinkedOpenHashMap shapes = new Reference2ObjectLinkedOpenHashMap<>(); + + /** + * 推进指定形状的采集。再次传入相同形状实例可接着处理未完成的数据。 + * + * @param shape 在所属世界线程访问的体素形状 + * @param deadline 以 {@link System#nanoTime()} 为基准的采集截止时刻 + * @return 已完成的数据,超过复杂度限制时返回 {@link VoxelShapeGeometry#UNSUPPORTED},未采完时返回空值 + */ + public @Nullable VoxelShapeGeometry capture(VoxelShape shape, long deadline) { + if (shape == Shapes.block()) return VoxelShapeGeometry.BLOCK; + if (shape == Shapes.empty()) return VoxelShapeGeometry.EMPTY; + Capture capture = shapes.getAndMoveToLast(shape); + if (capture == null) { + capture = new Capture(shape); + shapes.put(shape, capture); + if (shapes.size() > MAX_CACHED_SHAPES) shapes.removeFirst(); + } + return capture.advance(deadline); + } + + /** 丢弃正在处理和已采集的形状。已经交给调用方的几何数据仍可读取。 */ + public void clear() { + shapes.clear(); + } + + private static final class Capture { + + private final DiscreteVoxelShape grid; + private final DoubleList[] source; + private final double[][] coordinates; + private final VoxelOccupancy runs = new VoxelOccupancy(); + private final long cells; + private int axis; + private int coordinate; + private long cell; + private long start = -1; + private @Nullable VoxelShapeGeometry result; + + private Capture(VoxelShape shape) { + grid = ((VoxelShapeAccessor) shape).mmclutils$voxelGrid(); + source = new DoubleList[] { shape.getCoords(Direction.Axis.X), shape.getCoords(Direction.Axis.Y), shape.getCoords(Direction.Axis.Z) }; + cells = Math.multiplyExact(Math.multiplyExact((long) grid.getXSize(), grid.getYSize()), grid.getZSize()); + if (cells > MAX_CELLS || source[0].size() > MAX_COORDINATES || source[1].size() > MAX_COORDINATES || source[2].size() > MAX_COORDINATES) { + coordinates = new double[][] { new double[] { 0 }, new double[] { 0 }, new double[] { 0 } }; + result = VoxelShapeGeometry.UNSUPPORTED; + } else { + coordinates = new double[][] { new double[source[0].size()], new double[source[1].size()], new double[source[2].size()] }; + } + } + + private @Nullable VoxelShapeGeometry advance(long deadline) { + if (result != null) return result; + while (axis < 3) { + if (System.nanoTime() >= deadline) return null; + double value = source[axis].getDouble(coordinate); + if (!Double.isFinite(value)) throw new IllegalArgumentException("体素形状包含非有限坐标"); + coordinates[axis][coordinate++] = value; + if (coordinate == coordinates[axis].length) { + coordinate = 0; + axis++; + } + } + while (cell < cells) { + if ((cell & 63) == 0 && System.nanoTime() >= deadline) return null; + int z = (int) (cell % grid.getZSize()); + long row = cell / grid.getZSize(); + boolean filled = grid.isFull((int) (row / grid.getYSize()), (int) (row % grid.getYSize()), z); + if (filled && start < 0) start = cell; + else if (!filled && start >= 0) { + runs.append(start); + runs.append(cell); + start = -1; + } + cell++; + } + if (start >= 0) { + runs.append(start); + runs.append(cells); + } + if (runs.empty()) result = VoxelShapeGeometry.EMPTY; + else if (runs.fills(cells)) result = new VoxelShapeGeometry(bounds(coordinates[0]), bounds(coordinates[1]), bounds(coordinates[2]), VoxelShapeGeometry.BLOCK.runs()); + else result = new VoxelShapeGeometry(coordinates[0], coordinates[1], coordinates[2], runs); + return result; + } + + private static double[] bounds(double[] coordinates) { + return new double[] { coordinates[0], coordinates[coordinates.length - 1] }; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/api/shape/VoxelShapeGeometry.java b/src/main/java/com/modularmc/mmclutils/api/shape/VoxelShapeGeometry.java new file mode 100644 index 0000000..a9f1056 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/api/shape/VoxelShapeGeometry.java @@ -0,0 +1,55 @@ +package com.modularmc.mmclutils.api.shape; + +import net.minecraft.core.Direction; + +import java.util.Arrays; + +/** 构造时接管坐标和占用区间。读取方共享同一份数据,交付后各方均只读。 */ +public record VoxelShapeGeometry(double[] x, double[] y, double[] z, VoxelOccupancy runs) { + + /** 没有占用区间的空形状。 */ + public static final VoxelShapeGeometry EMPTY = new VoxelShapeGeometry(new double[] { 0 }, new double[] { 0 }, new double[] { 0 }, new VoxelOccupancy()); + /** 形状无法采集时的特殊结果。可按引用区分此状态与空形状。 */ + public static final VoxelShapeGeometry UNSUPPORTED = new VoxelShapeGeometry(new double[] { 0 }, new double[] { 0 }, new double[] { 0 }, new VoxelOccupancy()); + /** 局部坐标从零到一的完整立方体,调用方共享此几何数据。 */ + public static final VoxelShapeGeometry BLOCK = box(1); + + /** 创建底面覆盖一个完整方块的直角体,高度以方块为单位。高度应大于零。 */ + public static VoxelShapeGeometry box(double height) { + var runs = new VoxelOccupancy(); + runs.append(0); + runs.append(1); + return new VoxelShapeGeometry(new double[] { 0, 1 }, new double[] { 0, height }, new double[] { 0, 1 }, runs); + } + + /** 返回指定轴的分割坐标数组。数组由当前几何持有,调用方须只读访问。 */ + public double[] coordinates(Direction.Axis axis) { + return switch (axis) { + case X -> x; + case Y -> y; + case Z -> z; + }; + } + + /** 判断是否存在任何占用区间。 */ + public boolean empty() { + return runs.empty(); + } + + /** 按三轴网格单元索引判断是否占用。越界单元视为空。 */ + public boolean filled(int cx, int cy, int cz) { + if (cx < 0 || cy < 0 || cz < 0 || cx >= x.length - 1 || cy >= y.length - 1 || cz >= z.length - 1) return false; + long cell = ((long) cx * (y.length - 1) + cy) * (z.length - 1) + cz; + return runs.contains(cell); + } + + /** 按局部坐标查找所在体素。每个单元包括下界,排除上界。 */ + public boolean contains(double px, double py, double pz) { + return filled(cell(x, px), cell(y, py), cell(z, pz)); + } + + private static int cell(double[] coordinates, double position) { + int index = Arrays.binarySearch(coordinates, position); + return index >= 0 ? index : -index - 2; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/ClientTickScheduler.java b/src/main/java/com/modularmc/mmclutils/client/ClientTickScheduler.java new file mode 100644 index 0000000..942c540 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/ClientTickScheduler.java @@ -0,0 +1,30 @@ +package com.modularmc.mmclutils.client; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.api.schedule.Schedulers; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; +import net.neoforged.neoforge.client.event.ClientTickEvent; + +import org.jetbrains.annotations.ApiStatus; + +/** 将客户端 Post Tick 与断开事件转交给客户端调度车道。 */ +@ApiStatus.Internal +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID, value = Dist.CLIENT) +public final class ClientTickScheduler { + + private ClientTickScheduler() {} + + @SubscribeEvent + private static void onTick(ClientTickEvent.Post event) { + Schedulers.runClientTick(); + } + + @SubscribeEvent + private static void onLoggingOut(ClientPlayerNetworkEvent.LoggingOut event) { + Schedulers.resetClient(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java b/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java new file mode 100644 index 0000000..dd80ffa --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java @@ -0,0 +1,63 @@ +package com.modularmc.mmclutils.client; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.client.input.ClientKeyBindings; +import com.modularmc.mmclutils.client.render.effect.EffectRenderer; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.Entity; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; + +import org.jspecify.annotations.Nullable; + +import java.util.UUID; + +/** + * 注册仅在物理客户端加载的渲染与输入监听,并提供当前客户端状态查询。 + * 客户端方法只能从拥有客户端类的物理客户端调用。 + */ +@Mod(value = ModularMCLibUtils.MOD_ID, dist = Dist.CLIENT) +public final class ModularMCLibUtilsClient { + + /** + * 登记客户端模组总线监听器。 + * + * @param modBus 当前模组的事件总线 + */ + public ModularMCLibUtilsClient(IEventBus modBus) { + EffectRenderer.init(modBus); + ClientKeyBindings.init(modBus); + } + + /** 判断当前线程是否为客户端主线程。 */ + public static boolean isClientThread() { + Minecraft minecraft = Minecraft.getInstance(); + return minecraft != null && minecraft.isSameThread(); + } + + /** 判断实体是否由客户端实体渲染器绘制。 */ + public static boolean isClientPlayer(Entity entity) { + return entity instanceof AbstractClientPlayer; + } + + /** 返回当前本地玩家,尚未进入世界时返回空值。 */ + public static @Nullable LocalPlayer getPlayer() { + return Minecraft.getInstance().player; + } + + /** 返回当前本地玩家的 UUID,尚未进入世界时返回空值。 */ + public static @Nullable UUID getPlayerId() { + LocalPlayer player = getPlayer(); + return player == null ? null : player.getUUID(); + } + + /** 返回当前客户端世界,尚未进入世界时返回空值。 */ + public static @Nullable ClientLevel getLevel() { + return Minecraft.getInstance().level; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/gui/GuiUtils.java b/src/main/java/com/modularmc/mmclutils/client/gui/GuiUtils.java new file mode 100644 index 0000000..b26cfe2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/gui/GuiUtils.java @@ -0,0 +1,87 @@ +package com.modularmc.mmclutils.client.gui; + +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.navigation.ScreenRectangle; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.state.gui.GuiElementRenderState; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.VertexConsumer; +import org.joml.Matrix3x2f; +import org.joml.Matrix3x2fc; +import org.jspecify.annotations.Nullable; + +/** 绘制原版界面中的渐变矩形并计算列表行和滚动条布局。 */ +public final class GuiUtils { + + private static final float MIN_SCROLL_THUMB_HEIGHT = 6.0F; + + private GuiUtils() {} + + /** 用原版 GUI 管线提交从左到右的 ARGB 渐变。矩形使用当前姿态和裁剪范围。 */ + public static void fillHorizontalGradient(GuiGraphicsExtractor graphics, int left, int top, int right, int bottom, + int leftColor, int rightColor) { + fillGradient(graphics, RenderPipelines.GUI, left, top, right, bottom, leftColor, leftColor, rightColor, rightColor); + } + + /** 使用指定的位置和颜色管线提交水平渐变。调用方传入两侧的 ARGB 颜色。 */ + public static void fillHorizontalGradient(GuiGraphicsExtractor graphics, RenderPipeline pipeline, int left, int top, + int right, int bottom, int leftColor, int rightColor) { + fillGradient(graphics, pipeline, left, top, right, bottom, leftColor, leftColor, rightColor, rightColor); + } + + /** 管线须使用位置和颜色顶点格式。颜色依次对应左上、左下、右下和右上。 */ + public static void fillGradient(GuiGraphicsExtractor graphics, RenderPipeline pipeline, int left, int top, int right, int bottom, + int topLeft, int bottomLeft, int bottomRight, int topRight) { + if (left >= right || top >= bottom) return; + var pose = new Matrix3x2f(graphics.pose()); + ScreenRectangle scissor = graphics.peekScissorStack(); + ScreenRectangle bounds = new ScreenRectangle(left, top, right - left, bottom - top).transformMaxBounds(pose); + if (scissor != null) bounds = bounds.intersection(scissor); + if (bounds == null) return; + graphics.submitGuiElementRenderState( + new Gradient(pipeline, pose, scissor, bounds, left, top, right, bottom, topLeft, bottomLeft, bottomRight, topRight)); + } + + private record Gradient(RenderPipeline pipeline, Matrix3x2fc pose, @Nullable ScreenRectangle scissorArea, ScreenRectangle bounds, + int left, int top, int right, int bottom, int topLeft, int bottomLeft, int bottomRight, int topRight) + implements GuiElementRenderState { + + @Override + public TextureSetup textureSetup() { + return TextureSetup.noTexture(); + } + + @Override + public void buildVertices(VertexConsumer vertices) { + vertices.addVertexWith2DPose(pose, left, top).setColor(topLeft); + vertices.addVertexWith2DPose(pose, left, bottom).setColor(bottomLeft); + vertices.addVertexWith2DPose(pose, right, bottom).setColor(bottomRight); + vertices.addVertexWith2DPose(pose, right, top).setColor(topRight); + } + } + + /** 把零到一的列表进度换算成整像素宽度,最大值比行宽少一像素以保留行边界。 */ + public static int listProgressWidth(int rowWidth, float progress) { + if (!Float.isFinite(progress) || progress < 0.0F || progress > 1.0F) { + throw new IllegalArgumentException("进度应当在零与一之间"); + } + return (int) Math.floor(progress * (rowWidth - 1)); + } + + /** 用轨道高度将六像素的最小滑块换算为百分比。轨道高度为零时直接返回原比例。 */ + public static float scrollbarThumbPercent(float naturalPercent, float trackHeight, boolean overflowing) { + if (!Float.isFinite(naturalPercent) || naturalPercent < 0.0F || naturalPercent > 100.0F) { + throw new IllegalArgumentException("滚动条比例应当在零与一百之间"); + } + if (!Float.isFinite(trackHeight) || trackHeight < 0.0F) { + throw new IllegalArgumentException("滚动条轨道高度应为非负数"); + } + if (trackHeight == 0.0F) { + return naturalPercent; + } + float minimumPercent = Math.min(100.0F, MIN_SCROLL_THUMB_HEIGHT * 100.0F / trackHeight); + return overflowing ? Math.max(naturalPercent, minimumPercent) : minimumPercent; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java b/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java new file mode 100644 index 0000000..e9e2c77 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java @@ -0,0 +1,65 @@ +package com.modularmc.mmclutils.client.input; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.input.InputQuirks; +import net.neoforged.neoforge.client.settings.KeyConflictContext; +import net.neoforged.neoforge.client.settings.KeyModifier; + +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.Window; +import org.jspecify.annotations.Nullable; +import org.lwjgl.glfw.GLFW; + +/** 在客户端线程读取键盘和鼠标的当前状态。 */ +public final class ClientInput { + + /** 表示物理 Ctrl 修饰键的位。 */ + public static final int CONTROL = 1; + /** 表示 Shift 修饰键的位。 */ + public static final int SHIFT = 2; + /** 表示 Alt 或 Option 修饰键的位。 */ + public static final int ALT = 4; + /** 表示使用 Command 的平台上的命令修饰位。 */ + public static final int COMMAND = 8; + /** 本库识别的全部修饰位。 */ + public static final int ALL_MODIFIERS = CONTROL | SHIFT | ALT | COMMAND; + + private ClientInput() {} + + /** 读取当前按下的全部修饰键并组成位掩码。请在客户端线程调用。 */ + public static int modifiers() { + return (KeyModifier.CONTROL.isActive(KeyConflictContext.UNIVERSAL) ? CONTROL : 0) | (KeyModifier.SHIFT.isActive(KeyConflictContext.UNIVERSAL) ? SHIFT : 0) | (KeyModifier.ALT.isActive(KeyConflictContext.UNIVERSAL) ? ALT : 0) | (InputQuirks.REPLACE_CTRL_KEY_WITH_CMD_KEY && KeyModifier.CONTROL_OR_COMMAND.isActive(KeyConflictContext.UNIVERSAL) ? COMMAND : 0); + } + + /** 将 NeoForge 修饰键转换成当前平台的掩码位。无修饰键则返回零。 */ + public static int modifierBit(KeyModifier modifier) { + return switch (modifier) { + case CONTROL -> CONTROL; + case CONTROL_OR_COMMAND -> InputQuirks.REPLACE_CTRL_KEY_WITH_CMD_KEY ? COMMAND : CONTROL; + case SHIFT -> SHIFT; + case ALT -> ALT; + case NONE -> 0; + }; + } + + /** 把输入键转换成对应修饰位。普通输入键或不受支持的 Command 键返回零。 */ + public static int keyModifierBit(InputConstants.Key key) { + int code = key.getValue(); + if (key.getType() == InputConstants.Type.KEYSYM && (code == GLFW.GLFW_KEY_LEFT_SUPER || code == GLFW.GLFW_KEY_RIGHT_SUPER)) { + return InputQuirks.REPLACE_CTRL_KEY_WITH_CMD_KEY ? COMMAND : 0; + } + return modifierBit(KeyModifier.getKeyModifier(key)); + } + + /** 直接读取主键。扫描码使用原版记录的状态,当前输入事件可以提供更早的状态变化。 */ + public static boolean mainKeyDown(Window window, KeyMapping mapping, InputConstants.@Nullable Key changed, boolean down) { + if (mapping.isUnbound()) return false; + InputConstants.Key key = mapping.getKey(); + if (key.equals(changed)) return down; + return switch (key.getType()) { + case KEYSYM -> InputConstants.isKeyDown(window, key.getValue()); + case MOUSE -> GLFW.glfwGetMouseButton(window.handle(), key.getValue()) == GLFW.GLFW_PRESS; + case SCANCODE -> mapping.isDown(); + }; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java b/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java new file mode 100644 index 0000000..8cbc16f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java @@ -0,0 +1,355 @@ +package com.modularmc.mmclutils.client.input; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.api.input.SyncedKeyMappings.ChangeSet; +import com.modularmc.mmclutils.api.input.SyncedKeyMappings.Key; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.resources.Identifier; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.InputEvent; +import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent; +import net.neoforged.neoforge.client.event.ScreenEvent; + +import com.mojang.blaze3d.platform.InputConstants; +import it.unimi.dsi.fastutil.objects.Object2BooleanLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; +import org.lwjgl.glfw.GLFW; + +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + * 绑定原版按键,采样组合键并同步状态变化。 + * 登记、查询和回调均在客户端线程执行。绑定须在原版按键注册阶段之前声明。 + */ +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID, value = Dist.CLIENT) +public final class ClientKeyBindings { + + private static final Reference2ObjectLinkedOpenHashMap BINDINGS = new Reference2ObjectLinkedOpenHashMap<>(); + private static final Object2IntOpenHashMap ACTIVE_PRIORITIES = new Object2IntOpenHashMap<>(); + private static @Nullable LocalPlayer owner; + + private ClientKeyBindings() {} + + /** 在客户端模组初始化时绑定并将按键加入原版控制设置。 */ + public static Binding bind(Key key, KeyMapping mapping) { + return put(key, new Binding(key, () -> mapping, true)); + } + + /** 使用原版已有的按键,供应器在客户端进入世界后首次调用。 */ + public static Binding bindVanilla(Key key, Supplier mapping) { + return put(key, new Binding(key, mapping, false)); + } + + private static Binding put(Key key, Binding binding) { + if (BINDINGS.putIfAbsent(key, binding) != null) throw new IllegalArgumentException("客户端按键已经绑定 " + key.id()); + return binding; + } + + /** 将按键设置接入客户端模组总线。 */ + @ApiStatus.Internal + public static void init(IEventBus modBus) { + modBus.addListener(ClientKeyBindings::initMappings); + } + + private static void initMappings(RegisterKeyMappingsEvent event) { + for (Binding binding : BINDINGS.values()) { + if (binding.configurable) event.register(binding.mapping()); + } + } + + @SubscribeEvent + private static void sampleTick(ClientTickEvent.Pre event) { + sample(null, false); + Minecraft client = Minecraft.getInstance(); + for (Binding binding : BINDINGS.values()) { + for (Consumer listener : binding.tickListeners) listener.accept(client); + } + } + + @SubscribeEvent + private static void sampleKeyboard(InputEvent.Key event) { + if (event.getAction() != GLFW.GLFW_REPEAT) { + sample(InputConstants.getKey(event.getKeyEvent()), event.getAction() == GLFW.GLFW_PRESS); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + private static void sampleMouse(InputEvent.MouseButton.Pre event) { + var key = InputConstants.Type.MOUSE.getOrCreate(event.getButton()); + boolean pressed = event.getAction() == GLFW.GLFW_PRESS; + sample(key, pressed); + if (!pressed) return; + Minecraft client = Minecraft.getInstance(); + for (Binding binding : BINDINGS.values()) { + var capture = binding.captureInput; + if (binding.down && capture != null && binding.mapping().getKey().equals(key) && capture.test(client)) { + event.setCanceled(true); + return; + } + } + } + + @SubscribeEvent + private static void onScreenKey(ScreenEvent.KeyPressed.Pre event) { + Minecraft client = Minecraft.getInstance(); + double x = client.mouseHandler.xpos() * event.getScreen().width / client.getWindow().getScreenWidth(); + double y = client.mouseHandler.ypos() * event.getScreen().height / client.getWindow().getScreenHeight(); + if (dispatchScreen(event.getScreen(), InputConstants.getKey(event.getKeyEvent()), x, y)) event.setCanceled(true); + } + + @SubscribeEvent + private static void onScreenMouse(ScreenEvent.MouseButtonPressed.Pre event) { + if (dispatchScreen(event.getScreen(), InputConstants.Type.MOUSE.getOrCreate(event.getButton()), + event.getMouseX(), event.getMouseY())) + event.setCanceled(true); + } + + private static boolean dispatchScreen(Screen screen, InputConstants.Key key, double x, double y) { + if (screen instanceof KeyBindsScreen) return false; + int modifiers = ClientInput.modifiers(); + for (Binding binding : BINDINGS.values()) { + if (binding.screenListeners.isEmpty()) continue; + KeyMapping mapping = binding.mapping(); + if (mapping.isUnbound() || !mapping.getKey().equals(key) || !binding.matches(mapping, modifiers)) continue; + binding.waitingForRelease = true; + for (ScreenListener listener : binding.screenListeners) { + if (listener.pressed(screen, binding, x, y)) return true; + } + } + return false; + } + + private static void sample(InputConstants.@Nullable Key changed, boolean down) { + if (BINDINGS.isEmpty()) return; + Minecraft client = Minecraft.getInstance(); + LocalPlayer player = client.player; + if (owner != player) { + owner = player; + clearLocalState(); + } + if (player == null) return; + var connection = client.getConnection(); + boolean available = connection != null && client.isWindowActive() && client.screen == null && !client.isPaused(); + int modifiers = available ? ClientInput.modifiers() : 0; + ACTIVE_PRIORITIES.clear(); + for (Binding binding : BINDINGS.values()) { + KeyMapping mapping = binding.mapping(); + boolean mainDown = ClientInput.mainKeyDown(client.getWindow(), mapping, changed, down); + if (!mainDown) binding.waitingForRelease = false; + else if (!available) binding.waitingForRelease = true; + if (mainDown && available && !binding.waitingForRelease && binding.matches(mapping, modifiers)) { + int priority = 1 + Integer.bitCount(binding.requiredModifiers(mapping)); + binding.sampledPriority = priority; + ACTIVE_PRIORITIES.mergeInt(mapping.getKey(), priority, Math::max); + } else { + binding.sampledPriority = 0; + } + } + + // 同一主键上有更具体的生效组合时,只发布该组合的状态。 + ObjectArrayList changes = null; + for (Binding binding : BINDINGS.values()) { + int priority = binding.sampledPriority; + boolean pressed = priority != 0 && priority == ACTIVE_PRIORITIES.getInt(binding.mapping().getKey()); + if (binding.down == pressed) continue; + binding.down = pressed; + if (changes == null) changes = new ObjectArrayList<>(); + changes.add(binding); + } + if (changes == null) return; + if (connection != null && connection.hasChannel(ChangeSet.TYPE)) send(changes, connection::send); + for (Binding binding : changes) binding.notifyListeners(); + } + + private static void send(ObjectArrayList changes, Consumer send) { + var payload = new Object2BooleanLinkedOpenHashMap(Math.min(changes.size(), ChangeSet.MAX_CHANGES)); + for (Binding binding : changes) { + payload.put(binding.key.id(), binding.down); + if (payload.size() == ChangeSet.MAX_CHANGES) { + send.accept(new ChangeSet(payload)); + payload = new Object2BooleanLinkedOpenHashMap<>(); + } + } + if (!payload.isEmpty()) send.accept(new ChangeSet(payload)); + } + + @SubscribeEvent + private static void clearOnDisconnect(ClientPlayerNetworkEvent.LoggingOut event) { + owner = null; + clearLocalState(); + } + + private static void clearLocalState() { + ObjectArrayList released = null; + for (Binding binding : BINDINGS.values()) { + binding.waitingForRelease = false; + if (!binding.down) continue; + binding.down = false; + if (released == null) released = new ObjectArrayList<>(); + released.add(binding); + } + if (released != null) for (Binding binding : released) binding.notifyListeners(); + } + + /** 客户端按键绑定。状态和修饰键仅在客户端线程修改。 */ + public static final class Binding { + + private final Key key; + private final Supplier factory; + private final boolean configurable; + private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); + private final CopyOnWriteArrayList> tickListeners = new CopyOnWriteArrayList<>(); + private final CopyOnWriteArrayList screenListeners = new CopyOnWriteArrayList<>(); + private @Nullable KeyMapping mapping; + private @Nullable Predicate captureInput; + private int extraModifiers; + private int sampledPriority; + private boolean down; + private boolean waitingForRelease; + + private Binding(Key key, Supplier factory, boolean configurable) { + this.key = key; + this.factory = factory; + this.configurable = configurable; + } + + /** 返回两端共同声明的按键。 */ + public Key key() { + return key; + } + + /** 返回最近一次采样的游戏内状态。屏幕打开、失焦或断开后进入释放状态。 */ + public boolean isDown() { + return down; + } + + /** 判断给定输入是否符合本绑定的主键、修饰键和冲突上下文。 */ + public boolean isActiveAndMatches(InputConstants.Key key) { + KeyMapping mapping = mapping(); + return !mapping.isUnbound() && mapping.getKey().equals(key) && matches(mapping, ClientInput.modifiers()); + } + + /** 增加组合键条件。控制设置中的主键和原版修饰键仍由原版存储。 */ + public Binding withModifiers(int modifiers) { + if ((modifiers & ~ClientInput.ALL_MODIFIERS) != 0) { + throw new IllegalArgumentException("不支持的修饰键组合 " + modifiers); + } + extraModifiers = modifiers; + return this; + } + + /** 添加本地状态监听,相同监听只登记一次。 */ + public void addListener(Listener listener) { + listeners.addIfAbsent(listener); + } + + /** 移除本地状态监听。 */ + public void removeListener(Listener listener) { + listeners.remove(listener); + } + + /** + * 登记每个客户端 Tick 执行的回调。它在更新同步按键状态之后运行,主菜单也会调用。 + * + * @param listener 接收当前客户端实例的回调,相同回调只登记一次 + */ + public void addTickListener(Consumer listener) { + tickListeners.addIfAbsent(listener); + } + + /** 移除客户端 Tick 回调。 */ + public void removeTickListener(Consumer listener) { + tickListeners.remove(listener); + } + + /** + * 设置何时消费当前绑定对应的游戏内鼠标按下事件。 + * 同步状态仍会更新,释放事件照常交给原版以清理鼠标状态。 + * + * @param condition 客户端线程上运行的消费条件,空值清除条件 + * @return 当前绑定 + */ + public Binding captureInputWhen(@Nullable Predicate condition) { + captureInput = condition; + return this; + } + + /** 登记屏幕按下回调,用于界面内与游戏状态独立的按键操作。 */ + public void addScreenListener(ScreenListener listener) { + screenListeners.addIfAbsent(listener); + } + + /** 移除屏幕按下回调。 */ + public void removeScreenListener(ScreenListener listener) { + screenListeners.remove(listener); + } + + /** 返回当前绑定使用的原版按键,首次访问时向绑定提供者取得对象。 */ + public KeyMapping mapping() { + if (mapping == null) mapping = factory.get(); + return mapping; + } + + private boolean matches(KeyMapping mapping, int modifiers) { + if (extraModifiers == 0) return mapping.isConflictContextAndModifierActive(); + int mainModifier = ClientInput.keyModifierBit(mapping.getKey()); + return mapping.getKeyConflictContext().isActive() && (modifiers & ~mainModifier) == requiredModifiers(mapping); + } + + private int requiredModifiers(KeyMapping mapping) { + int mappingModifiers = mapping instanceof KeyChordMapping chord ? chord.modifiers() : ClientInput.modifierBit(mapping.getKeyModifier()); + return (extraModifiers | mappingModifiers) & ~ClientInput.keyModifierBit(mapping.getKey()); + } + + private void notifyListeners() { + for (Listener listener : listeners) listener.changed(this, down); + } + } + + /** 在客户端线程接收绑定的按下和释放通知。 */ + @FunctionalInterface + public interface Listener { + + /** + * 在本地绑定状态已经更新时调用。失焦与断开连接都会产生释放。 + * + * @param binding 发出状态变化的客户端绑定 + * @param down 新状态,真为按下 + */ + void changed(Binding binding, boolean down); + } + + /** 在客户端线程处理屏幕按键。只向当前屏幕派发,且不会发送游戏内按键状态。 */ + @FunctionalInterface + public interface ScreenListener { + + /** + * 在当前屏幕接收一个已匹配的按下边沿。 + * + * @param screen 当前屏幕 + * @param binding 匹配的客户端绑定 + * @param mouseX 鼠标在屏幕中的横向坐标 + * @param mouseY 鼠标在屏幕中的纵向坐标 + * @return 是否消费本次输入 + */ + boolean pressed(Screen screen, Binding binding, double mouseX, double mouseY); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java b/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java new file mode 100644 index 0000000..abab894 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java @@ -0,0 +1,179 @@ +package com.modularmc.mmclutils.client.input; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Options; +import net.minecraft.network.chat.Component; +import net.neoforged.neoforge.client.settings.IKeyConflictContext; +import net.neoforged.neoforge.client.settings.KeyConflictContext; +import net.neoforged.neoforge.client.settings.KeyModifier; + +import com.mojang.blaze3d.platform.InputConstants; +import lombok.Getter; +import lombok.experimental.Accessors; +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; + +/** 可在控制设置中编辑和保存的组合键。只在客户端线程读写。 */ +public final class KeyChordMapping extends KeyMapping { + + private static final KeyModifier[] DISPLAY_ORDER = { KeyModifier.ALT, KeyModifier.SHIFT, KeyModifier.CONTROL, + KeyModifier.CONTROL_OR_COMMAND }; + private final int defaultModifiers; + /** 当前组合要求的完整修饰键掩码。 */ + @Getter + @Accessors(fluent = true) + private int modifiers; + private @Nullable LegacyOptions legacyOptions; + + /** 用主键和修饰掩码创建绑定,自动去掉掩码中与主键重复的修饰位。 */ + public KeyChordMapping(String name, Category category, IKeyConflictContext context, InputConstants.Key key, int modifiers) { + super(name, context, primary(normalize(key, modifiers)), key, category); + defaultModifiers = normalize(key, modifiers); + this.modifiers = defaultModifiers; + } + + /** 用输入类型和按键编号创建组合。编号的解释遵循对应的原版输入类型。 */ + public KeyChordMapping(String name, Category category, IKeyConflictContext context, InputConstants.Type type, int key, int modifiers) { + this(name, category, context, type.getOrCreate(key), modifiers); + } + + /** 更换主键及完整修饰键。清除旧绑定积累的点击。 */ + public void setChord(InputConstants.Key key, int modifiers) { + this.modifiers = normalize(key, modifiers); + super.setKeyModifierAndCode(primary(this.modifiers), key); + setDown(false); + while (consumeClick()) { + // 旧绑定的点击不能触发新的组合键。 + } + } + + /** 从此库此前使用的按键名称读取设置。在绑定注册前指定旧名称。 */ + public KeyChordMapping migrateFrom(String previousName) { + return migrateFrom(previousName, "mmclutils_chord_" + previousName); + } + + /** + * 在注册前指定旧设置的位置。当前设置缺失时才尝试读取对应旧值。 + * + * @param previousName 旧按键名称,省略原版的 {@code key_} 前缀 + * @param previousChordKey 旧附加选项的完整键名,值为主键、主修饰键和位掩码以冒号分隔的格式。空值代表没有附加选项 + * @return 当前组合键 + */ + public KeyChordMapping migrateFrom(String previousName, @Nullable String previousChordKey) { + legacyOptions = new LegacyOptions("key_" + previousName, previousChordKey); + return this; + } + + @Override + public void setKeyModifierAndCode(KeyModifier modifier, InputConstants.Key key) { + setChord(key, ClientInput.modifierBit(modifier)); + } + + @Override + public boolean isConflictContextAndModifierActive() { + if (!getKeyConflictContext().isActive()) return false; + return modifiers == 0 ? super.isConflictContextAndModifierActive() : normalize(getKey(), ClientInput.modifiers()) == modifiers; + } + + @Override + public boolean isDefault() { + return getKey().equals(getDefaultKey()) && modifiers == defaultModifiers; + } + + @Override + public void setToDefault() { + setChord(getDefaultKey(), defaultModifiers); + } + + @Override + public Component getTranslatedKeyMessage() { + Component result = getKey().getDisplayName(); + for (KeyModifier modifier : DISPLAY_ORDER) { + if (modifier == KeyModifier.CONTROL_OR_COMMAND && ClientInput.modifierBit(modifier) != ClientInput.COMMAND) continue; + if ((modifiers & ClientInput.modifierBit(modifier)) == 0) continue; + Component suffix = result; + result = modifier.getCombinedName(getKey(), () -> suffix); + } + return result; + } + + @Override + public boolean same(KeyMapping other) { + if (!conflicts(other)) return false; + if (hasKeyModifierConflict(other) || other.hasKeyModifierConflict(this)) return true; + if (isUnbound() || !getKey().equals(other.getKey())) return false; + int otherModifiers = other instanceof KeyChordMapping chord ? chord.modifiers : ClientInput.modifierBit(other.getKeyModifier()); + return modifiers == otherModifiers || (modifiers == 0 || otherModifiers == 0) && (getKeyConflictContext().conflicts(KeyConflictContext.IN_GAME) || other.getKeyConflictContext().conflicts(KeyConflictContext.IN_GAME)); + } + + @Override + public boolean hasKeyModifierConflict(KeyMapping other) { + return conflicts(other) && (modifiers & ClientInput.keyModifierBit(other.getKey())) != 0; + } + + /** 只恢复与已加载的主键和 NeoForge 主修饰键匹配的组合。 */ + @ApiStatus.Internal + public void processOptions(Options.FieldAccess access) { + readModifiers(access.process(chordOption(), optionPrefix() + modifiers)); + } + + /** 在原版读取完成后补入仍缺失的配置。只在载入选项时调用。 */ + @ApiStatus.Internal + public void readLegacyOptions(Options.FieldAccess access) { + LegacyOptions legacy = legacyOptions; + if (legacy == null) return; + if (access.process("key_" + getName(), "").isEmpty()) { + String saved = access.process(legacy.mappingKey(), ""); + if (!saved.isEmpty()) { + try { + String[] parts = saved.split(":", 2); + setKeyModifierAndCode(parts.length == 2 ? KeyModifier.valueFromString(parts[1]) : KeyModifier.NONE, + InputConstants.getKey(parts[0])); + } catch (IllegalArgumentException failure) { + ModularMCLibUtils.LOGGER.warn("组合键 {} 的旧主键设置无效,旧设置键为 {}", getName(), legacy.mappingKey(), failure); + } + } + } + if (legacy.chordKey() != null && access.process(chordOption(), "").isEmpty()) { + readModifiers(access.process(legacy.chordKey(), "")); + } + } + + private String chordOption() { + return "mmclutils_chord_" + getName(); + } + + private String optionPrefix() { + return getKey().getName() + ":" + getKeyModifier().name() + ":"; + } + + private void readModifiers(String saved) { + String prefix = optionPrefix(); + if (!saved.startsWith(prefix) || saved.equals(prefix + modifiers)) return; + try { + setChord(getKey(), Integer.parseInt(saved.substring(prefix.length()))); + } catch (IllegalArgumentException failure) { + ModularMCLibUtils.LOGGER.warn("组合键 {} 的附加配置无效,使用已读取的主键和修饰键", getName(), failure); + } + } + + private boolean conflicts(KeyMapping other) { + return getKeyConflictContext().conflicts(other.getKeyConflictContext()) || other.getKeyConflictContext().conflicts(getKeyConflictContext()); + } + + private static int normalize(InputConstants.Key key, int modifiers) { + if ((modifiers & ~ClientInput.ALL_MODIFIERS) != 0) throw new IllegalArgumentException("未知修饰键 " + modifiers); + return key.equals(InputConstants.UNKNOWN) ? 0 : modifiers & ~ClientInput.keyModifierBit(key); + } + + private static KeyModifier primary(int modifiers) { + if ((modifiers & ClientInput.CONTROL) != 0) return KeyModifier.CONTROL; + if ((modifiers & ClientInput.COMMAND) != 0) return KeyModifier.CONTROL_OR_COMMAND; + if ((modifiers & ClientInput.SHIFT) != 0) return KeyModifier.SHIFT; + return (modifiers & ClientInput.ALT) != 0 ? KeyModifier.ALT : KeyModifier.NONE; + } + + private record LegacyOptions(String mappingKey, @Nullable String chordKey) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java b/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java new file mode 100644 index 0000000..8c716ea --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java @@ -0,0 +1,62 @@ +package com.modularmc.mmclutils.client.level; + +import com.modularmc.mmclutils.api.blockentity.BlockEntityTracking; + +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.LevelChunk; + +import org.jetbrains.annotations.ApiStatus; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReferenceArray; + +/** + * 客户端区块缓存移动视野时,原版只改视野中心,落到范围外的区块要等槽位被复用才卸载,缩小视野半径时被丢弃的区块不会卸载; + * 这里让索引跟原版的可见范围一致:范围外的区块里的方块实体先从索引里摘掉,回到范围内再登记。 + */ +@ApiStatus.Internal +public final class ClientChunkVisibility { + + /** 为客户端区块缓存注入提供当前槽位和可见范围。只在客户端区块线程使用。 */ + public interface View { + + /** 返回原版区块槽位,仅在本次同步期间读取。 */ + AtomicReferenceArray mmclutils$chunks(); + + /** 查询指定区块坐标是否落在当前视野范围内。 */ + boolean mmclutils$inRange(int x, int z); + } + + private ClientChunkVisibility() {} + + /** 视野存储扩缩后移除已被淘汰区块的索引,再按新范围同步。 */ + public static void afterResize(View now, View old) { + if (old != now) { + Set kept = Collections.newSetFromMap(new IdentityHashMap<>()); + AtomicReferenceArray current = now.mmclutils$chunks(); + for (int i = 0, n = current.length(); i < n; i++) { + LevelChunk chunk = current.get(i); + if (chunk != null) kept.add(chunk); + } + AtomicReferenceArray dropped = old.mmclutils$chunks(); + for (int i = 0, n = dropped.length(); i < n; i++) { + LevelChunk chunk = dropped.get(i); + if (chunk != null && !kept.contains(chunk)) BlockEntityTracking.setVisible(chunk, false); + } + } + sync(now); + } + + /** 按当前视野范围切换区块内方块实体的索引状态。 */ + public static void sync(View view) { + AtomicReferenceArray chunks = view.mmclutils$chunks(); + for (int i = 0, n = chunks.length(); i < n; i++) { + LevelChunk chunk = chunks.get(i); + if (chunk == null) continue; + ChunkPos pos = chunk.getPos(); + BlockEntityTracking.setVisible(chunk, view.mmclutils$inRange(pos.x(), pos.z())); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java b/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java new file mode 100644 index 0000000..0dcb037 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java @@ -0,0 +1,80 @@ +package com.modularmc.mmclutils.client.level; + +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.SectionPos; +import net.minecraft.world.level.chunk.LevelChunk; + +import lombok.Getter; + +/** + * 以中心区块为起点螺旋遍历,按高度交替访问已加载的非空区段。 + * 游标在同一客户端世界线程使用,跨调用只保留区块坐标和区段进度。 + */ +public final class LoadedSectionCursor { + + /** 当前调用未取得区段的返回值。可用 {@link #isFinished()} 区分时限用尽与遍历完成。 */ + public static final long NO_SECTION = Long.MIN_VALUE; + private final int centerX; + private final int centerZ; + private final int centerY; + private int remaining; + private int x; + private int z; + private int dx; + private int dz = -1; + private int chunkX; + private int chunkZ; + private int sectionCursor = -1; + /** 此游标是否已经遍历完全部列。 */ + @Getter + private boolean finished; + + /** 指定中心区段和水平搜索半径。坐标和半径均以区段为单位。 */ + public LoadedSectionCursor(int centerX, int centerY, int centerZ, int radius) { + if (radius < 0) throw new IllegalArgumentException("遍历半径须为非负数"); + this.centerX = centerX; + this.centerY = centerY; + this.centerZ = centerZ; + int width = Math.addExact(Math.multiplyExact(radius, 2), 1); + remaining = Math.multiplyExact(width, width); + } + + /** 返回区段的打包坐标。到达时限或遍历完毕时返回 NO_SECTION。 */ + public long next(ClientLevel level, long deadline) { + var source = level.getChunkSource(); + LevelChunk chunk = sectionCursor < 0 ? null : source.getChunk(chunkX, chunkZ, false); + while (System.nanoTime() < deadline) { + if (chunk == null) { + if (remaining == 0) { + finished = true; + return NO_SECTION; + } + chunkX = centerX + x; + chunkZ = centerZ + z; + chunk = source.getChunk(chunkX, chunkZ, false); + remaining--; + if (x == z || x < 0 && x == -z || x > 0 && x == 1 - z) { + int previous = dx; + dx = -dz; + dz = previous; + } + x += dx; + z += dz; + sectionCursor = chunk == null ? -1 : 0; + if (chunk == null) continue; + } + int count = chunk.getSections().length; + if (sectionCursor >= count * 2 - 1) { + chunk = null; + sectionCursor = -1; + continue; + } + int delta = (sectionCursor + 1) / 2 * ((sectionCursor & 1) == 0 ? -1 : 1); + sectionCursor++; + int index = Math.clamp(level.getSectionIndexFromSectionY(centerY), 0, count - 1) + delta; + if (index < 0 || index >= count || chunk.getSection(index).hasOnlyAir()) continue; + return SectionPos.asLong(chunkX, level.getSectionYFromSectionIndex(index), chunkZ); + } + return NO_SECTION; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotation.java b/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotation.java new file mode 100644 index 0000000..53cb216 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotation.java @@ -0,0 +1,156 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.renderer.block.dispatch.Variant; +import net.minecraft.client.renderer.block.dispatch.Variant.SimpleModelState; +import net.minecraft.core.Direction; + +import com.mojang.math.OctahedralGroup; +import com.mojang.math.Quadrant; +import com.mojang.math.Transformation; +import lombok.Getter; + +/** + * 记录可定向方块的 24 种正交旋转。每个枚举值的前缀是世界前向,后缀是用水平方向编码的滚转。 + *

+ * 旋转表源自 + * Applied + * Energistics 2,采用 LGPL 3.0 许可。 + */ +public enum BlockModelRotation { + + // 前向按原版三维方向编号排列,每组内部按原版二维方向编号排列。 + DOWN_SOUTH(90, 0, 180), + DOWN_WEST(90, 0, 270), + DOWN_NORTH(90, 0, 0), + DOWN_EAST(90, 0, 90), + + UP_SOUTH(270, 0, 0), + UP_WEST(270, 0, 270), + UP_NORTH(270, 0, 180), + UP_EAST(270, 0, 90), + + NORTH_SOUTH(0, 0, 180), + NORTH_WEST(0, 0, 90), + NORTH_NORTH(0, 0, 0), + NORTH_EAST(0, 0, 270), + + SOUTH_SOUTH(0, 180, 180), + SOUTH_WEST(0, 180, 90), + SOUTH_NORTH(0, 180, 0), + SOUTH_EAST(0, 180, 270), + + WEST_SOUTH(0, 270, 180), + WEST_WEST(0, 270, 90), + WEST_NORTH(0, 270, 0), + WEST_EAST(0, 270, 270), + + EAST_SOUTH(0, 90, 180), + EAST_WEST(0, 90, 90), + EAST_NORTH(0, 90, 0), + EAST_EAST(0, 90, 270); + + /** 按原版方向编号和水平旋转编号索引的旋转表。调用方应将数组视为只读。 */ + public static final BlockModelRotation[] VALUES = values(); + private static final SimpleModelState[] VARIANT_STATES = createVariantStates(); + + /** 模型绕 X 轴旋转的角度,以度为单位。 */ + @Getter + private final int angleX; + /** 模型绕 Y 轴旋转的角度,以度为单位。 */ + @Getter + private final int angleY; + /** 模型绕 Z 轴旋转的角度,以度为单位。 */ + @Getter + private final int angleZ; + + BlockModelRotation(int angleX, int angleY, int angleZ) { + this.angleX = angleX; + this.angleY = angleY; + this.angleZ = angleZ; + } + + /** + * 按世界前向与滚转编码查找方块的旋转参数。 + * + * @param frontFacing 模型局部前方朝向的世界面 + * @param upwardsFacing 原版水平旋转编码,须为水平方向 + * @return 对应的 X、Y、Z 旋转角 + */ + public static BlockModelRotation get(Direction frontFacing, Direction upwardsFacing) { + return VALUES[frontFacing.get3DDataValue() * 4 + upwardsFacing.get2DDataValue()]; + } + + /** 返回此朝向的原版坐标变换。 */ + public Transformation transformation() { + return transformation(angleX, angleY, angleZ); + } + + /** + * 应用此朝向,保留变体的模型位置和 UV 锁定设置。 + * + * @param variant 原版模型变体 + * @return 旋转后的模型变体 + */ + public Variant rotate(Variant variant) { + return rotate(variant, angleX, angleY, angleZ); + } + + /** + * 返回正交模型变换。先应用模型局部 Z 轴滚转,再依次应用 X 轴俯仰与 Y 轴偏航。 + * 各角度使用原版方块模型的方向约定。 + * + * @param x 绕 X 轴的角度 + * @param y 绕 Y 轴的角度 + * @param z 绕 Z 轴的角度 + * @return 与给定角度对应的原版变换 + * @throws IllegalArgumentException 任一轴的角度不是 0、90、180 或 270 度 + */ + public static Transformation transformation(int x, int y, int z) { + return rotationState(x, y, z).asModelState().transformation(); + } + + /** + * 以指定变换替换变体的旋转,保留模型位置与 UV 锁定。变换顺序与 {@link #transformation(int, int, int)} 一致。 + * + * @param variant 原版模型变体 + * @param x 绕 X 轴的角度 + * @param y 绕 Y 轴的角度 + * @param z 绕 Z 轴的角度 + * @return 旋转后的模型变体 + * @throws IllegalArgumentException 任一轴的角度不是 0、90、180 或 270 度 + */ + public static Variant rotate(Variant variant, int x, int y, int z) { + return variant.withState(rotationState(x, y, z).withUvLock(variant.modelState().uvLock())); + } + + private static SimpleModelState rotationState(int x, int y, int z) { + OctahedralGroup group = Quadrant.fromXYAngles(quadrant(x), quadrant(y)).compose(quadrant(z).rotationZ); + return VARIANT_STATES[group.ordinal()]; + } + + private static SimpleModelState[] createVariantStates() { + var states = new SimpleModelState[OctahedralGroup.values().length]; + Quadrant[] angles = Quadrant.values(); + // 原版变体最后绕世界 Z 轴旋转,按变换结果查出等价的原版角度以沿用 UV 锁定和序列化。 + for (Quadrant z : angles) { + for (Quadrant y : angles) { + for (Quadrant x : angles) { + int index = Quadrant.fromXYZAngles(x, y, z).ordinal(); + if (states[index] == null) states[index] = new SimpleModelState(x, y, z, false); + } + } + } + return states; + } + + private static Quadrant quadrant(int angle) { + return switch (angle) { + case 0 -> Quadrant.R0; + case 90 -> Quadrant.R90; + case 180 -> Quadrant.R180; + case 270 -> Quadrant.R270; + default -> throw new IllegalArgumentException("模型旋转角度无效 " + angle); + }; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java b/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java new file mode 100644 index 0000000..dc94e96 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java @@ -0,0 +1,62 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.renderer.block.BlockAndTintGetter; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.CardinalLighting; +import net.minecraft.world.level.ColorResolver; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.lighting.LevelLightEngine; +import net.minecraft.world.level.material.FluidState; + +import org.jspecify.annotations.Nullable; + +/** 以调用方提供的方块状态替代一格数据,维度范围、颜色和光照沿用底层视图。 */ +public record BlockTintView(BlockAndTintGetter parent, long position, BlockState state, @Nullable BlockEntity entity) + implements BlockAndTintGetter { + + /** 将坐标转换为原版打包值,创建指定位置上的临时方块与方块实体视图。 */ + public BlockTintView(BlockAndTintGetter parent, BlockPos position, BlockState state, @Nullable BlockEntity entity) { + this(parent, position.asLong(), state, entity); + } + + @Override + public CardinalLighting cardinalLighting() { + return parent.cardinalLighting(); + } + + @Override + public LevelLightEngine getLightEngine() { + return parent.getLightEngine(); + } + + @Override + public int getBlockTint(BlockPos pos, ColorResolver resolver) { + return parent.getBlockTint(pos, resolver); + } + + @Override + public @Nullable BlockEntity getBlockEntity(BlockPos pos) { + return pos.asLong() == position ? entity : parent.getBlockEntity(pos); + } + + @Override + public BlockState getBlockState(BlockPos pos) { + return pos.asLong() == position ? state : parent.getBlockState(pos); + } + + @Override + public FluidState getFluidState(BlockPos pos) { + return pos.asLong() == position ? state.getFluidState() : parent.getFluidState(pos); + } + + @Override + public int getHeight() { + return parent.getHeight(); + } + + @Override + public int getMinY() { + return parent.getMinY(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ConnectedTextureUtils.java b/src/main/java/com/modularmc/mmclutils/client/model/ConnectedTextureUtils.java new file mode 100644 index 0000000..59fd156 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/ConnectedTextureUtils.java @@ -0,0 +1,274 @@ +package com.modularmc.mmclutils.client.model; + +import com.modularmc.mmclutils.client.model.QuadUtils.Face; + +import net.minecraft.client.renderer.block.BlockAndTintGetter; +import net.minecraft.client.renderer.block.dispatch.BlockStateModel; +import net.minecraft.client.renderer.block.dispatch.BlockStateModelPart; +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.client.resources.model.geometry.QuadCollection; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.util.TriState; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.neoforge.client.model.DelegateBlockStateModel; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectImmutableList; +import it.unimi.dsi.fastutil.objects.ObjectList; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.jspecify.annotations.Nullable; + +import java.util.List; + +/** 切分四边形并为子面指定贴图。连接条件和材质由调用方决定。 */ +public final class ConnectedTextureUtils { + + private static final Direction[] DIRECTIONS = Direction.values(); + + private ConnectedTextureUtils() {} + + /** + * 包装能根据相邻方块更换表面的模型。无世界上下文的渲染沿用父模型。 + * + * @param parent 提供基础几何和粒子材质的模型 + * @param replacementFlags 所有候选替换材质的 {@link MaterialInfo#flags()} 按位或 + * @param rule 根据世界上下文确定每个面的输出 + * @return 保留父模型随机变体和光照行为的方块模型 + */ + public static BlockStateModel wrap(BlockStateModel parent, @BakedQuad.MaterialFlags int replacementFlags, FaceRule rule) { + return new ConnectedModel(parent, replacementFlags, rule); + } + + /** 四份材质按从左到右、从上到下排列。每个子面映射整个新贴图。 */ + public static ObjectList quadrants(Face input, MaterialInfo topLeft, MaterialInfo topRight, + MaterialInfo bottomLeft, MaterialInfo bottomRight) { + return ObjectList.of( + patch(input, 0, 0, 0.5f, 0.5f, topLeft), + patch(input, 0.5f, 0, 1, 0.5f, topRight), + patch(input, 0, 0.5f, 0.5f, 1, bottomLeft), + patch(input, 0.5f, 0.5f, 1, 1, bottomRight)); + } + + /** 参数域从顶点零出发,横轴沿零至三,纵轴沿零至一。子面使用整个目标精灵。 */ + public static Face patch(Face input, float u0, float v0, float u1, float v1, MaterialInfo material) { + return patch(input, u0, v0, u1, v1, new Tile(material, 0, 0, 1, 1)); + } + + /** 在顶点参数域内切分四边形,并将目标精灵的指定子区域铺到整个子面。 */ + public static Face patch(Face input, float u0, float v0, float u1, float v1, Tile tile) { + checkRegion(u0, v0, u1, v1); + QuadView source = QuadView.of(input.quad(), input.cullFace()); + var output = new MutableQuadView(source); + var a = new Vector3f(); + var b = new Vector3f(); + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + float u = vertex < 2 ? u0 : u1; + float v = vertex == 0 || vertex == 3 ? v0 : v1; + a.set(source.position(0)).lerp(source.position(3), u); + b.set(source.position(1)).lerp(source.position(2), u); + output.position(vertex, a.lerp(b, v)); + } + QuadUtils.interpolate(source, output, source.lightFace().getAxis()); + output.uv(0, tile.minU(), tile.minV()).uv(1, tile.minU(), tile.maxV()) + .uv(2, tile.maxU(), tile.maxV()).uv(3, tile.maxU(), tile.minV()); + return bake(output, tile); + } + + /** 按光照面的方块局部坐标切分轴对齐矩形,没有覆盖的象限会被略过。 */ + public static ObjectList quadrants(Face input, Tile topLeft, Tile topRight, Tile bottomLeft, Tile bottomRight) { + var result = new ObjectArrayList(4); + Tile[] tiles = { topLeft, topRight, bottomLeft, bottomRight }; + for (int i = 0; i < tiles.length; i++) { + float u0 = (i & 1) * 0.5f; + float v0 = (i >>> 1) * 0.5f; + Face face = tile(input, u0, v0, u0 + 0.5f, v0 + 0.5f, tiles[i]); + if (face != null) result.add(face); + } + return new ObjectImmutableList<>(result); + } + + /** + * 按 {@link QuadUtils#lockToFace} 的方块坐标裁切轴对齐矩形,将裁切区间线性对应到贴图子区域。 + * 顶点顺序、调制色、法线和剔除分组随几何裁切保留。仅接触边界时返回空值。 + * + * @param input 原始四边形,须为垂直于光照面轴向的矩形 + * @param u0 裁切区间左边界 + * @param v0 裁切区间上边界 + * @param u1 裁切区间右边界 + * @param v1 裁切区间下边界 + * @param tile 子面材质和目标精灵内的 UV 范围 + * @return 裁切后的烘焙面,或交集无面积时的空值 + */ + public static @Nullable Face tile(Face input, float u0, float v0, float u1, float v1, Tile tile) { + checkRegion(u0, v0, u1, v1); + QuadView source = QuadView.of(input.quad(), input.cullFace()); + Direction direction = source.lightFace(); + var output = QuadUtils.lockToFace(new MutableQuadView(source), direction); + float minU = u1, minV = v1, maxU = u0, maxV = v0; + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + float u = output.u(vertex), v = output.v(vertex); + float clampedU = Math.clamp(u, u0, u1); + float clampedV = Math.clamp(v, v0, v1); + minU = Math.min(minU, clampedU); + minV = Math.min(minV, clampedV); + maxU = Math.max(maxU, clampedU); + maxV = Math.max(maxV, clampedV); + moveVertex(output, vertex, direction, clampedU - u, clampedV - v); + } + if (minU >= maxU || minV >= maxV) return null; + + QuadUtils.interpolate(source, output, direction.getAxis()); + QuadUtils.lockToFace(output, direction); + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + float u = (output.u(vertex) - u0) / (u1 - u0); + float v = (output.v(vertex) - v0) / (v1 - v0); + output.uv(vertex, Mth.lerp(u, tile.minU(), tile.maxU()), Mth.lerp(v, tile.minV(), tile.maxV())); + } + return bake(output, tile); + } + + /** 两条相邻边及夹角按三个位存储,可作为材质数组索引。 */ + public static int connectionMask(boolean horizontal, boolean vertical, boolean diagonal) { + return (horizontal ? 1 : 0) | (vertical ? 2 : 0) | (horizontal && vertical && diagonal ? 4 : 0); + } + + /** 连接纹理的表面规则。模型构建线程可以并发调用,从传入的方块视图读取邻接状态。 */ + @FunctionalInterface + public interface FaceRule { + + /** + * 为当前面选择替换面。返回空值保留原面,返回空集合移除该面。 + * + * @param level 可读取邻接状态和模型数据的方块视图 + * @param pos 当前位置,仅在本次调用期间使用 + * @param state 当前正在构建模型的方块状态 + * @param face 父模型的烘焙面及剔除分组 + * @return 按绘制顺序排列的替换面,或表示保留原面的空值 + */ + @Nullable + Iterable replace(BlockAndTintGetter level, BlockPos pos, BlockState state, Face face); + } + + /** + * 目标材质在精灵局部坐标中使用的矩形,坐标在零至一之间。 + * + * @param material 目标精灵和渲染材质设置 + * @param minU 左边界 + * @param minV 上边界 + * @param maxU 右边界 + * @param maxV 下边界 + */ + public record Tile(MaterialInfo material, float minU, float minV, float maxU, float maxV) { + + /** @throws IllegalArgumentException 坐标越界或没有面积 */ + public Tile { + checkRegion(minU, minV, maxU, maxV); + } + } + + private static void checkRegion(float u0, float v0, float u1, float v1) { + if (!(u0 >= 0 && u1 <= 1 && u0 < u1 && v0 >= 0 && v1 <= 1 && v0 < v1)) { + throw new IllegalArgumentException("子区域须落在零至一之间并具有面积"); + } + } + + private static Face bake(MutableQuadView quad, Tile tile) { + QuadUtils.bake(quad.material(tile.material()), tile.material().sprite()); + return new Face(quad.bake(), quad.cullFace()); + } + + private static void moveVertex(MutableQuadView quad, int vertex, Direction face, float u, float v) { + Vector3fc pos = quad.position(vertex); + switch (face) { + case DOWN -> quad.position(vertex, pos.x() + u, pos.y(), pos.z() - v); + case UP -> quad.position(vertex, pos.x() + u, pos.y(), pos.z() + v); + case NORTH -> quad.position(vertex, pos.x() - u, pos.y() - v, pos.z()); + case SOUTH -> quad.position(vertex, pos.x() + u, pos.y() - v, pos.z()); + case WEST -> quad.position(vertex, pos.x(), pos.y() - v, pos.z() + u); + case EAST -> quad.position(vertex, pos.x(), pos.y() - v, pos.z() - u); + } + } + + private static final class ConnectedModel extends DelegateBlockStateModel { + + private final int replacementFlags; + private final FaceRule rule; + + private ConnectedModel(BlockStateModel parent, int replacementFlags, FaceRule rule) { + super(parent); + this.replacementFlags = replacementFlags; + this.rule = rule; + } + + @Override + public void collectParts(BlockAndTintGetter level, BlockPos pos, BlockState state, RandomSource random, + List parts) { + var source = new ObjectArrayList(); + delegate.collectParts(level, pos, state, random, source); + var geometry = new ObjectArrayList(); + for (BlockStateModelPart part : source) { + geometry.clear(); + boolean changed = collectFaces(level, pos, state, part, null, geometry); + for (Direction direction : DIRECTIONS) { + changed |= collectFaces(level, pos, state, part, direction, geometry); + } + parts.add(changed ? new ConnectedPart(part, QuadUtils.collect(geometry)) : part); + } + } + + private boolean collectFaces(BlockAndTintGetter level, BlockPos pos, BlockState state, BlockStateModelPart part, + @Nullable Direction direction, ObjectList geometry) { + boolean changed = false; + for (BakedQuad quad : part.getQuads(direction)) { + var face = new Face(quad, direction); + Iterable replacement = rule.replace(level, pos, state, face); + if (replacement == null) geometry.add(face); + else { + changed = true; + replacement.forEach(geometry::add); + } + } + return changed; + } + + @Override + public int materialFlags(BlockAndTintGetter level, BlockPos pos, BlockState state) { + return delegate.materialFlags(level, pos, state) | replacementFlags; + } + } + + private record ConnectedPart(BlockStateModelPart parent, QuadCollection quads) implements BlockStateModelPart { + + @Override + public List getQuads(@Nullable Direction direction) { + return quads.getQuads(direction); + } + + @Override + public Material.Baked particleMaterial() { + return parent.particleMaterial(); + } + + @Override + @Deprecated + public boolean useAmbientOcclusion() { + return parent.useAmbientOcclusion(); + } + + @Override + public TriState ambientOcclusion() { + return parent.ambientOcclusion(); + } + + @Override + public int materialFlags() { + return quads.materialFlags(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ItemModelGenerator.java b/src/main/java/com/modularmc/mmclutils/client/model/ItemModelGenerator.java new file mode 100644 index 0000000..0ddcc2d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/ItemModelGenerator.java @@ -0,0 +1,40 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.color.item.ItemTintSource; +import net.minecraft.client.data.models.ItemModelOutput; +import net.minecraft.client.data.models.model.ItemModelUtils; +import net.minecraft.client.data.models.model.ModelInstance; +import net.minecraft.client.data.models.model.ModelTemplate; +import net.minecraft.client.data.models.model.ModelTemplates; +import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.client.data.models.model.TextureSlot; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Item; + +import java.util.function.BiConsumer; + +/** 生成多层原版物品模型并按图层次序绑定染色来源。 */ +public final class ItemModelGenerator { + + private ItemModelGenerator() {} + + /** 向数据生成输出登记带逐层染色的平面物品模型。材质和染色源按图层顺序一一对应。 */ + public static Identifier generated(Item item, ItemModelOutput items, BiConsumer models, + Material[] materials, ItemTintSource... tints) { + if (materials.length == 0 || materials.length != tints.length) { + throw new IllegalArgumentException("每一层图案须对应一个染色来源"); + } + var mapping = new TextureMapping(); + var slots = new TextureSlot[materials.length]; + for (int index = 0; index < materials.length; index++) { + TextureSlot slot = TextureSlot.create("layer" + index); + slots[index] = slot; + mapping.put(slot, materials[index]); + } + var template = new ModelTemplate(ModelTemplates.FLAT_ITEM.model, ModelTemplates.FLAT_ITEM.suffix, slots); + Identifier model = template.create(item, mapping, models); + items.accept(item, ItemModelUtils.tintedModel(model, tints)); + return model; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ModelUtils.java b/src/main/java/com/modularmc/mmclutils/client/model/ModelUtils.java new file mode 100644 index 0000000..104b74c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/ModelUtils.java @@ -0,0 +1,180 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.block.BlockAndTintGetter; +import net.minecraft.client.renderer.block.BlockModelRenderState; +import net.minecraft.client.renderer.block.dispatch.BlockStateModel; +import net.minecraft.client.renderer.block.dispatch.BlockStateModelPart; +import net.minecraft.client.renderer.block.dispatch.SingleVariant; +import net.minecraft.client.renderer.block.model.BlockDisplayContext; +import net.minecraft.client.renderer.item.ItemModel; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.Identifier; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.ItemOwner; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.neoforge.client.model.DelegateBlockStateModel; +import net.neoforged.neoforge.client.model.standalone.StandaloneModelKey; + +import com.mojang.blaze3d.vertex.PoseStack; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectImmutableList; +import it.unimi.dsi.fastutil.objects.ObjectList; +import org.jspecify.annotations.Nullable; + +import java.util.List; + +/** 通过当前资源版本的原版模型解析器和提交器操作模型。 */ +public final class ModelUtils { + + private static final Direction[] DIRECTIONS = Direction.values(); + + private ModelUtils() {} + + /** 取得当前资源版本的方块状态模型。资源重载后应重新获取。 */ + public static BlockStateModel block(BlockState state) { + return Minecraft.getInstance().getModelManager().getBlockStateModelSet().get(state); + } + + /** 按物品模型标识查找当前已加载的模型。 */ + public static ItemModel item(Identifier model) { + return Minecraft.getInstance().getModelManager().getItemModel(model); + } + + /** 按已注册键取得独立烘焙模型。键应已参与当前资源版本的模型加载。 */ + public static T standalone(StandaloneModelKey key) { + return Minecraft.getInstance().getModelManager().getStandaloneModel(key); + } + + /** 为该栈分配渲染状态并解析显示上下文、世界和持有者驱动的模型。 */ + public static ItemStackRenderState resolveItem(ItemStack stack, ItemDisplayContext context, + @Nullable Level level, @Nullable ItemOwner owner, int seed) { + var state = new ItemStackRenderState(); + resolveItem(state, stack, context, level, owner, seed); + return state; + } + + /** 用当前模型解析器更新调用方提供的物品渲染状态。世界和持有者可以为空。 */ + public static void resolveItem(ItemStackRenderState output, ItemStack stack, ItemDisplayContext context, + @Nullable Level level, @Nullable ItemOwner owner, int seed) { + Minecraft.getInstance().getItemModelResolver().updateForTopItem(output, stack, context, level, owner, seed); + } + + /** 以指定显示上下文、姿态及亮度提交方块模型,提交器负责后续绘制。 */ + public static void submitBlock(BlockState block, BlockDisplayContext context, PoseStack poses, SubmitNodeCollector output, + int light, int overlay, int outlineColor) { + var state = new BlockModelRenderState(); + Minecraft.getInstance().getBlockModelResolver().update(state, block, context); + state.submit(poses, output, light, overlay, outlineColor); + } + + /** 采集一次加权模型选择的全部通用面和各方向剔除面。 */ + public static ObjectList quads(BlockStateModel model, RandomSource random) { + var parts = new ObjectArrayList(); + model.collectParts(random, parts); + return quads(parts); + } + + /** 使用当前方块视图读取模型。连接纹理等上下文相关模型从视图获取数据。 */ + public static ObjectList quads(BlockStateModel model, BlockAndTintGetter level, BlockPos pos, + BlockState state, RandomSource random) { + var parts = new ObjectArrayList(); + model.collectParts(level, pos, state, random, parts); + return quads(parts); + } + + /** 收集所有部件的通用面及六个方向的剔除分组。 */ + public static ObjectList quads(List parts) { + var result = new ObjectArrayList(); + for (BlockStateModelPart part : parts) { + for (var quad : part.getQuads(null)) result.add(new QuadUtils.Face(quad, null)); + for (Direction direction : DIRECTIONS) { + for (var quad : part.getQuads(direction)) result.add(new QuadUtils.Face(quad, direction)); + } + } + return new ObjectImmutableList<>(result); + } + + /** 给由方块实体渲染器负责提交几何的方块提供粒子材质。 */ + public static BlockStateModel particleOnly(Material.Baked material) { + return new SingleVariant(new ParticlePart(material)); + } + + /** 按输入顺序组合已烘焙模型。各部分共享随机变体种子,粒子材质取第一项。 */ + public static BlockStateModel combine(List parts) { + if (parts.isEmpty()) throw new IllegalArgumentException("模型组合需要至少一个部件"); + if (parts.size() == 1) return parts.getFirst(); + return new CombinedModel(List.copyOf(parts)); + } + + private record ParticlePart(Material.Baked particleMaterial) implements BlockStateModelPart { + + @Override + public List getQuads(@Nullable Direction direction) { + return List.of(); + } + + @Override + public boolean useAmbientOcclusion() { + return false; + } + + @Override + public int materialFlags() { + return 0; + } + } + + private static final class CombinedModel extends DelegateBlockStateModel { + + private final List parts; + + private CombinedModel(List parts) { + super(parts.getFirst()); + this.parts = parts; + } + + @Override + @Deprecated + public void collectParts(RandomSource random, List output) { + long seed = random.nextLong(); + for (BlockStateModel model : parts) { + random.setSeed(seed); + model.collectParts(random, output); + } + } + + @Override + public void collectParts(BlockAndTintGetter level, BlockPos pos, BlockState state, + RandomSource random, List output) { + long seed = random.nextLong(); + for (BlockStateModel model : parts) { + random.setSeed(seed); + model.collectParts(level, pos, state, random, output); + } + } + + @Override + @Deprecated + public int materialFlags() { + int flags = 0; + for (BlockStateModel model : parts) flags |= model.materialFlags(); + return flags; + } + + @Override + public int materialFlags(BlockAndTintGetter level, BlockPos pos, BlockState state) { + int flags = 0; + for (BlockStateModel model : parts) flags |= model.materialFlags(level, pos, state); + return flags; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/MutableQuadView.java b/src/main/java/com/modularmc/mmclutils/client/model/MutableQuadView.java new file mode 100644 index 0000000..a715350 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/MutableQuadView.java @@ -0,0 +1,182 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.model.geom.builders.UVPair; +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.core.Direction; +import net.neoforged.neoforge.client.model.quad.BakedColors; +import net.neoforged.neoforge.client.model.quad.BakedNormals; + +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; + +/** 可复用的四边形编辑器。调用方负责线程隔离,烘焙结果拥有独立顶点。 */ +public final class MutableQuadView implements QuadView { + + private final Vector3f[] positions = { new Vector3f(), new Vector3f(), new Vector3f(), new Vector3f() }; + private final long[] uv = new long[VERTEX_COUNT]; + private final int[] normals = new int[VERTEX_COUNT]; + private final int[] colors = new int[VERTEX_COUNT]; + private Direction lightFace = Direction.UP; + private @Nullable Direction cullFace; + private MaterialInfo material; + + /** 创建一个编辑器,顶点初始在原点,调制色为白色。 */ + public MutableQuadView(MaterialInfo material) { + clear(material); + } + + /** 复制源四边形的顶点和属性,后续编辑与源视图相互独立。 */ + public MutableQuadView(QuadView source) { + this(source.material()); + copyFrom(source); + } + + /** 覆盖当前几何和材质,并返回当前编辑器。 */ + public MutableQuadView copyFrom(QuadView source) { + for (int vertex = 0; vertex < VERTEX_COUNT; vertex++) { + positions[vertex].set(source.position(vertex)); + uv[vertex] = source.packedUv(vertex); + normals[vertex] = source.packedNormal(vertex); + colors[vertex] = source.color(vertex); + } + lightFace = source.lightFace(); + cullFace = source.cullFace(); + material = source.material(); + return this; + } + + /** 重置编辑器以构造另一个面。位置、UV 和法线清零,颜色恢复为白色。 */ + public MutableQuadView clear(MaterialInfo material) { + for (Vector3f position : positions) position.zero(); + Arrays.fill(uv, 0); + Arrays.fill(normals, 0); + Arrays.fill(colors, -1); + lightFace = Direction.UP; + cullFace = null; + this.material = material; + return this; + } + + @Override + public Vector3fc position(int vertex) { + return positions[vertex]; + } + + /** 修改一个顶点的模型局部坐标,并返回当前编辑器。 */ + public MutableQuadView position(int vertex, float x, float y, float z) { + positions[vertex].set(x, y, z); + return this; + } + + /** 复制向量到指定顶点。向量随后可由调用方复用。 */ + public MutableQuadView position(int vertex, Vector3fc position) { + positions[vertex].set(position); + return this; + } + + @Override + public long packedUv(int vertex) { + return uv[vertex]; + } + + /** 写入以原版格式打包的 UV,返回当前编辑器。 */ + public MutableQuadView packedUv(int vertex, long packedUv) { + uv[vertex] = packedUv; + return this; + } + + /** 写入 UV。烘焙时以当前值为图集坐标,使用局部 UV 时须事先映射到材质精灵。 */ + public MutableQuadView uv(int vertex, float u, float v) { + return packedUv(vertex, UVPair.pack(u, v)); + } + + @Override + public int packedNormal(int vertex) { + return normals[vertex]; + } + + /** 写入 NeoForge 打包的顶点法线,零值沿用光照面。 */ + public MutableQuadView packedNormal(int vertex, int normal) { + normals[vertex] = normal; + return this; + } + + /** 将单位向量打包为指定顶点的法线。 */ + public MutableQuadView normal(int vertex, Vector3fc normal) { + return packedNormal(vertex, BakedNormals.pack(normal)); + } + + /** 用几何面法线填充未设置的顶点法线。退化面沿用光照方向。 */ + public MutableQuadView populateMissingNormals() { + int flags = normalFlags(); + if (flags == (1 << VERTEX_COUNT) - 1) return this; + var normal = QuadUtils.normal(this, new Vector3f()); + if (normal.lengthSquared() == 0) normal.set(lightFace.getStepX(), lightFace.getStepY(), lightFace.getStepZ()); + int packed = BakedNormals.pack(normal); + for (int vertex = 0; vertex < VERTEX_COUNT; vertex++) { + if ((flags & (1 << vertex)) == 0) normals[vertex] = packed; + } + return this; + } + + @Override + public int color(int vertex) { + return colors[vertex]; + } + + /** 设置单个顶点的 ARGB 调制色。 */ + public MutableQuadView color(int vertex, int argb) { + colors[vertex] = argb; + return this; + } + + /** 为四个顶点应用相同的 ARGB 调制色。 */ + public MutableQuadView colorAll(int argb) { + Arrays.fill(colors, argb); + return this; + } + + @Override + public Direction lightFace() { + return lightFace; + } + + /** 设置用于光照的朝向,保留邻面剔除分组。 */ + public MutableQuadView lightFace(Direction face) { + lightFace = face; + return this; + } + + @Override + public @Nullable Direction cullFace() { + return cullFace; + } + + /** 设置邻面剔除分组,空值表示不按邻面剔除。 */ + public MutableQuadView cullFace(@Nullable Direction face) { + cullFace = face; + return this; + } + + @Override + public MaterialInfo material() { + return material; + } + + /** 替换材质并保留原 UV。需要重映射 UV 时使用 {@link QuadUtils#replace}。 */ + public MutableQuadView material(MaterialInfo value) { + material = value; + return this; + } + + /** 产生可直接提交给原版的四边形。剔除分组仍由调用者维护。 */ + public BakedQuad bake() { + return new BakedQuad(new Vector3f(positions[0]), new Vector3f(positions[1]), new Vector3f(positions[2]), new Vector3f(positions[3]), + uv[0], uv[1], uv[2], uv[3], lightFace, material, + BakedNormals.of(normals[0], normals[1], normals[2], normals[3]), BakedColors.of(colors[0], colors[1], colors[2], colors[3])); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/QuadInterpolator.java b/src/main/java/com/modularmc/mmclutils/client/model/QuadInterpolator.java new file mode 100644 index 0000000..0002a42 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/QuadInterpolator.java @@ -0,0 +1,121 @@ +/* + * This file is part of CodeChickenLib. + * Copyright (c) 2018, covers1624, All rights reserved. + * + * CodeChickenLib is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 2.1 of the License, or + * (at your option) any later version. + * + * CodeChickenLib is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with CodeChickenLib. If not, see . + */ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.util.Mth; + +/** + * 在矩形的四个角之间做双线性插值。依次调用 {@link #reset} 和 {@link #setup} 设定角点, + * 再用 {@link #locate} 选定位置。同一位置可用于连续插值 UV 和颜色,各线程须各自持有实例。 + */ +public class QuadInterpolator { + + private final float[][] posCache = new float[4][2]; + private final float[] valCache = new float[4]; + + private float x0; + private float x1; + private float y0; + private float y1; + + private float rX; + private float rY; + + private int p00; + private int p10; + private int p11; + private int p01; + + /** + * 用沿两轴对齐的四边形重置插值数据。以第一个顶点为原点,其余顶点可按任意顺序传入。 + */ + public void reset(float dx0, float dy0, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { + float[] vec0 = this.posCache[0]; + float[] vec1 = this.posCache[1]; + float[] vec2 = this.posCache[2]; + float[] vec3 = this.posCache[3]; + + vec0[0] = dx0; + vec1[0] = dx1; + vec2[0] = dx2; + vec3[0] = dx3; + + vec0[1] = dy0; + vec1[1] = dy1; + vec2[1] = dy2; + vec3[1] = dy3; + } + + /** + * 在开始插值前结束顶点坐标采集。 + */ + public void setup() { + this.p00 = 0; // 第一个顶点为插值原点。 + this.x0 = this.posCache[this.p00][0]; + this.y0 = this.posCache[this.p00][1]; + + for (int i = 1; i < 4; i++) { + float x = this.posCache[i][0]; + float y = this.posCache[i][1]; + + if (this.y0 == y) { + // 右下。 + this.p10 = i; + this.x1 = x; + } else if (this.x0 == x) { + // 左上。 + this.p01 = i; + this.y1 = y; + } else { + // 右上。 + this.p11 = i; + } + } + } + + /** + * 按给定点计算双线性插值权重。 + * + * @param x 插值点的横坐标 + * @param y 插值点的纵坐标 + */ + public void locate(float x, float y) { + this.rX = Mth.inverseLerp(x, this.x0, this.x1); + this.rY = Mth.inverseLerp(y, this.y0, this.y1); + } + + /** + * 使用已计算的系数插值。 + * + * @param q0 第一个顶点的数值 + * @param q1 第二个顶点的数值 + * @param q2 第三个顶点的数值 + * @param q3 第四个顶点的数值 + * @return 插值结果 + */ + public float interpolate(float q0, float q1, float q2, float q3) { + this.valCache[0] = q0; + this.valCache[1] = q1; + this.valCache[2] = q2; + this.valCache[3] = q3; + float f0 = Mth.lerp(this.rX, this.valCache[this.p00], this.valCache[this.p10]); + float f1 = Mth.lerp(this.rX, this.valCache[this.p01], this.valCache[this.p11]); + + return Mth.lerp(this.rY, f0, f1); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/QuadTransforms.java b/src/main/java/com/modularmc/mmclutils/client/model/QuadTransforms.java new file mode 100644 index 0000000..8a56018 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/QuadTransforms.java @@ -0,0 +1,191 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.minecraft.world.phys.AABB; +import net.neoforged.neoforge.client.model.quad.BakedNormals; + +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +import java.util.function.Predicate; + +/** 可组合的四边形变换。返回假表示终止处理并丢弃该面。 */ +public final class QuadTransforms { + + private static final Direction[] DIRECTIONS = Direction.values(); + + private QuadTransforms() {} + + /** 生成模型局部平移,位移沿 X、Y、Z 分量表示。 */ + public static Transform offset(float x, float y, float z) { + return quad -> { + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + Vector3fc point = quad.position(vertex); + quad.position(vertex, point.x() + x, point.y() + y, point.z() + z); + } + return true; + }; + } + + /** 旋转、缩放或平移顶点,并重新计算光照面。几何变换后由调用方决定剔除分组。 */ + public static Transform transform(Matrix4fc matrix) { + var pose = new Matrix4f(matrix); + var normalMatrix = pose.normal(new Matrix3f()); + return quad -> { + var position = new Vector3f(); + var normal = new Vector3f(); + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + position.set(quad.position(vertex)).mulPosition(pose); + quad.position(vertex, position); + int packed = quad.packedNormal(vertex); + if (packed != 0) { + BakedNormals.unpack(packed, normal); + normal.mul(normalMatrix).normalize(); + quad.normal(vertex, normal); + } + } + quad.lightFace(QuadUtils.lightFace(QuadUtils.normal(quad, normal))); + quad.cullFace(null); + return true; + }; + } + + /** 创建绕模型局部中心的旋转。旋转后重算光照面并清除剔除分组。 */ + public static Transform rotate(Quaternionfc rotation, Vector3fc center) { + return transform(new Matrix4f().translate(center).rotate(rotation).translate(-center.x(), -center.y(), -center.z())); + } + + /** 创建相对于指定中心的轴向缩放。为保证法线可变换,各轴缩放系数须非零。 */ + public static Transform scale(float x, float y, float z, Vector3fc center) { + return transform(new Matrix4f().translate(center).scale(x, y, z).translate(-center.x(), -center.y(), -center.z())); + } + + /** 将面上各顶点限制在给定局部包围盒内,保留原顶点属性。 */ + public static Transform clamp(AABB bounds) { + return quad -> { + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + Vector3fc point = quad.position(vertex); + quad.position(vertex, (float) Math.clamp(point.x(), bounds.minX, bounds.maxX), + (float) Math.clamp(point.y(), bounds.minY, bounds.maxY), + (float) Math.clamp(point.z(), bounds.minZ, bounds.maxZ)); + } + return true; + }; + } + + /** 为所有顶点写入同一个 ARGB。指定 {@code clearTint} 时同时清除材质染色索引。 */ + public static Transform color(int argb, boolean clearTint) { + return quad -> { + quad.colorAll(argb); + if (clearTint) { + MaterialInfo material = quad.material(); + quad.material(new MaterialInfo(material.sprite(), material.layer(), material.itemRenderType(), -1, + material.shade(), material.lightEmission(), material.ambientOcclusion())); + } + return true; + }; + } + + /** 重映射图集 UV。新材质同时提供与图集匹配的渲染层。 */ + public static Transform retexture(MaterialInfo replacement) { + return quad -> { + QuadUtils.replace(quad, replacement); + return true; + }; + } + + /** 用指定方向的方块局部坐标投影 UV,再映射到当前材质精灵。 */ + public static Transform lockUv(Direction face) { + return quad -> { + QuadUtils.bake(QuadUtils.lockToFace(quad, face), quad.material().sprite()); + return true; + }; + } + + /** 在裁切前记录轴对齐面的属性,随后按裁切后的顶点重算 UV、颜色和显式法线。 */ + public static Transform clampInterpolated(AABB bounds) { + Transform clamp = clamp(bounds); + return quad -> { + Direction.Axis axis = quad.lightFace().getAxis(); + if (!QuadUtils.isParallel(quad, axis, 0.00001f)) return clamp.apply(quad); + var source = new MutableQuadView(quad); + clamp.apply(quad); + QuadUtils.interpolate(source, quad, axis); + return true; + }; + } + + /** + * 将薄片内侧边面与相邻薄片重合的角点往内移动,用于消除重叠面的闪烁。 + * 角部避让算法源自 CodeChickenLib,版权所有 (c) 2018 covers1624,采用 LGPL 2.1 或更新版本。 + * + * @param side 薄片所贴的方块外侧方向 + * @param adjacentMask 相邻薄片的位置,每个方向使用原版三维方向编号对应的位 + * @param bounds 整块薄片的模型局部包围盒 + * @param thickness 避让距离,使用模型局部单位 + * @return 可复用的原地变换,保留剔除分组和其他顶点属性 + * @throws IllegalArgumentException 距离为负或非有限值 + */ + public static Transform insetCorners(Direction side, int adjacentMask, AABB bounds, float thickness) { + if (!Float.isFinite(thickness) || thickness < 0) throw new IllegalArgumentException("避让距离须为有限非负值"); + Direction innerSide = side.getOpposite(); + Direction.Axis depthAxis = side.getAxis(); + float inner = bound(bounds, innerSide); + return quad -> { + Direction face = quad.lightFace(); + Direction.Axis faceAxis = face.getAxis(); + if (faceAxis == depthAxis) return true; + float edge = bound(bounds, face); + for (Direction neighbor : DIRECTIONS) { + Direction.Axis axis = neighbor.getAxis(); + if (axis == depthAxis || axis == faceAxis || (adjacentMask & (1 << neighbor.get3DDataValue())) == 0) continue; + float corner = bound(bounds, neighbor); + for (int i = 0; i < QuadView.VERTEX_COUNT; i++) { + Vector3fc pos = quad.position(i); + float x = pos.x(), y = pos.y(), z = pos.z(); + if (Mth.equal(depthAxis.choose(x, y, z), inner) && Mth.equal(faceAxis.choose(x, y, z), edge) && + Mth.equal(axis.choose(x, y, z), corner)) { + quad.position(i, x - neighbor.getStepX() * thickness, y - neighbor.getStepY() * thickness, + z - neighbor.getStepZ() * thickness); + } + } + } + return true; + }; + } + + private static float bound(AABB bounds, Direction side) { + return (float) switch (side) { + case DOWN -> bounds.minY; + case UP -> bounds.maxY; + case NORTH -> bounds.minZ; + case SOUTH -> bounds.maxZ; + case WEST -> bounds.minX; + case EAST -> bounds.maxX; + }; + } + + /** 用谓词决定是否保留该面。谓词只在变换期间读取当前视图。 */ + public static Transform filter(Predicate predicate) { + return predicate::test; + } + + /** 在调用线程中原地修改可写视图。调用方不得在之后复用被拒绝的面。 */ + @FunctionalInterface + public interface Transform { + + /** 返回真允许该面继续执行后续变换。 */ + boolean apply(MutableQuadView quad); + + /** 将两个变换按顺序组合。前一变换丢弃面时跳过后一变换。 */ + default Transform andThen(Transform next) { + return quad -> apply(quad) && next.apply(quad); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/QuadUtils.java b/src/main/java/com/modularmc/mmclutils/client/model/QuadUtils.java new file mode 100644 index 0000000..ef029c0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/QuadUtils.java @@ -0,0 +1,314 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.client.resources.model.geometry.QuadCollection; +import net.minecraft.core.Direction; +import net.minecraft.util.ARGB; +import net.minecraft.world.phys.AABB; +import net.neoforged.neoforge.client.model.quad.BakedNormals; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectImmutableList; +import it.unimi.dsi.fastutil.objects.ObjectList; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.jspecify.annotations.Nullable; + +/** 构造和变换原版四边形,处理顶点法线、光照方向、颜色插值和图集 UV。 */ +public final class QuadUtils { + + private QuadUtils() {} + + /** 逐面应用变换,收集通过变换的烘焙面。变换收到可复用编辑器,应在返回前完成修改。 */ + public static ObjectList transform(Iterable source, QuadTransforms.Transform transform) { + var output = new ObjectArrayList(); + MutableQuadView editor = null; + for (Face face : source) { + QuadView view = QuadView.of(face.quad(), face.cullFace()); + if (editor == null) editor = new MutableQuadView(view); + else editor.copyFrom(view); + if (transform.apply(editor)) output.add(new Face(editor.bake(), editor.cullFace())); + } + return new ObjectImmutableList<>(output); + } + + /** 取出同一剔除分组的烘焙面。空值选择无需邻面剔除的分组。 */ + public static ObjectList forFace(Iterable source, @Nullable Direction cullFace) { + var output = new ObjectArrayList(); + for (Face face : source) { + if (face.cullFace() == cullFace) output.add(face.quad()); + } + return new ObjectImmutableList<>(output); + } + + /** 将烘焙面按剔除方向收集为可交给原版模型的四边形集合。各组内保持输入顺序。 */ + public static QuadCollection collect(Iterable faces) { + var output = new QuadCollection.Builder(); + for (Face face : faces) add(output, face.quad(), face.cullFace()); + return output.build(); + } + + private static void add(QuadCollection.Builder output, BakedQuad quad, @Nullable Direction cullFace) { + if (cullFace == null) output.addUnculledFace(quad); + else output.addCulledFace(cullFace, quad); + } + + /** 以方块单位构造盒子一面。盒子内侧的面不参与邻方块剔除。 */ + public static Face boxFace(AABB box, Direction face, MaterialInfo material) { + var quad = new MutableQuadView(material).lightFace(face); + float x0 = (float) box.minX, y0 = (float) box.minY, z0 = (float) box.minZ; + float x1 = (float) box.maxX, y1 = (float) box.maxY, z1 = (float) box.maxZ; + boolean onEdge = switch (face) { + case DOWN -> { + quad.position(0, x0, y0, z0).position(1, x1, y0, z0).position(2, x1, y0, z1).position(3, x0, y0, z1); + yield y0 == 0; + } + case UP -> { + quad.position(0, x0, y1, z1).position(1, x1, y1, z1).position(2, x1, y1, z0).position(3, x0, y1, z0); + yield y1 == 1; + } + case NORTH -> { + quad.position(0, x1, y0, z0).position(1, x0, y0, z0).position(2, x0, y1, z0).position(3, x1, y1, z0); + yield z0 == 0; + } + case SOUTH -> { + quad.position(0, x0, y0, z1).position(1, x1, y0, z1).position(2, x1, y1, z1).position(3, x0, y1, z1); + yield z1 == 1; + } + case WEST -> { + quad.position(0, x0, y0, z0).position(1, x0, y0, z1).position(2, x0, y1, z1).position(3, x0, y1, z0); + yield x0 == 0; + } + case EAST -> { + quad.position(0, x1, y0, z1).position(1, x1, y0, z0).position(2, x1, y1, z0).position(3, x1, y1, z1); + yield x1 == 1; + } + }; + bake(lockToFace(quad, face), material.sprite()); + return new Face(quad.bake(), onEdge ? face : null); + } + + /** 用指定材质生成包围盒的六个烘焙面。 */ + public static ObjectList box(AABB bounds, MaterialInfo material) { + var faces = new ObjectArrayList(6); + for (Direction direction : Direction.values()) faces.add(boxFace(bounds, direction, material)); + return new ObjectImmutableList<>(faces); + } + + /** 烘焙四边形及其剔除分组。空方向表示通用面。 */ + public record Face(BakedQuad quad, @Nullable Direction cullFace) {} + + /** 使用单个可写视图收集四边形。构建过程由同一线程操作,烘焙后的顶点与编辑器独立。 */ + public static final class Builder { + + private final MutableQuadView editor; + private final QuadCollection.Builder faces = new QuadCollection.Builder(); + + /** 创建构建器并指定首个面的材质。 */ + public Builder(MaterialInfo material) { + editor = new MutableQuadView(material); + } + + /** 返回当前可写视图,调用 {@link #emit()} 后可继续构造下一面。 */ + public MutableQuadView editor() { + return editor; + } + + /** 清空视图并为下一面指定材质。 */ + public MutableQuadView begin(MaterialInfo material) { + return editor.clear(material); + } + + /** 从源面复制顶点、材质和剔除方向,返回当前可写视图。 */ + public MutableQuadView begin(QuadView source) { + return editor.copyFrom(source); + } + + /** 烘焙当前视图并追加到相应剔除组。 */ + public Builder emit() { + QuadUtils.add(faces, editor.bake(), editor.cullFace()); + return this; + } + + /** 追加已经烘焙的面,保留剔除分组。 */ + public Builder add(Face face) { + QuadUtils.add(faces, face.quad(), face.cullFace()); + return this; + } + + /** 返回已提交的原版四边形集合。当前视图须先经 {@link #emit()} 提交。 */ + public QuadCollection build() { + return faces.build(); + } + } + + /** 将顶点法线写入调用方的向量。缺少独立法线时使用光照朝向。 */ + public static Vector3f vertexNormal(QuadView quad, int vertex, Vector3f output) { + int packed = quad.packedNormal(vertex); + if (packed != 0) { + BakedNormals.unpack(packed, output); + return output; + } + Direction face = quad.lightFace(); + return output.set(face.getStepX(), face.getStepY(), face.getStepZ()); + } + + /** 按顶点顺序计算面法线。退化的面返回零向量。 */ + public static Vector3f normal(QuadView quad, Vector3f result) { + Vector3fc a = quad.position(0), b = quad.position(1), c = quad.position(2), d = quad.position(3); + float x = d.x() - b.x(), y = d.y() - b.y(), z = d.z() - b.z(); + result.set(c).sub(a).cross(x, y, z); + return result.lengthSquared() == 0 ? result : result.normalize(); + } + + /** 按单位法线的主要分量选择用于光照的原版方向。 */ + public static Direction lightFace(Vector3fc normal) { + float x = Math.abs(normal.x()), y = Math.abs(normal.y()), z = Math.abs(normal.z()); + if (x > y && x >= z) return normal.x() > 0 ? Direction.EAST : Direction.WEST; + if (z > y) return normal.z() > 0 ? Direction.SOUTH : Direction.NORTH; + return normal.y() < 0 ? Direction.DOWN : Direction.UP; + } + + /** 判断四个顶点是否落在垂直于指定轴的同一平面内。 */ + public static boolean isParallel(QuadView quad, Direction.Axis axis, float tolerance) { + Vector3fc first = quad.position(0); + double coordinate = axis.choose(first.x(), first.y(), first.z()); + for (int i = 1; i < QuadView.VERTEX_COUNT; i++) { + Vector3fc point = quad.position(i); + if (Math.abs(axis.choose(point.x(), point.y(), point.z()) - coordinate) > tolerance) return false; + } + return true; + } + + /** 以源四边形的两个三角形插值颜色、UV 和显式顶点法线。两视图须来自同一平面且相互独立。 */ + public static void interpolate(QuadView source, MutableQuadView target, Direction.Axis droppedAxis) { + int x = droppedAxis == Direction.Axis.X ? 1 : 0; + int y = droppedAxis == Direction.Axis.Z ? 1 : 2; + Vector3f normal = source.hasVertexNormals() ? new Vector3f() : null; + for (int i = 0; i < QuadView.VERTEX_COUNT; i++) { + Vector3fc point = target.position(i); + if (!sample(source, target, i, point.get(x), point.get(y), x, y, 1, 2, false, normal)) { + sample(source, target, i, point.get(x), point.get(y), x, y, 2, 3, true, normal); + } + } + } + + private static boolean sample(QuadView source, MutableQuadView target, int index, float px, float py, + int axisX, int axisY, int b, int c, boolean extend, @Nullable Vector3f normal) { + Vector3fc origin = source.position(0), v1 = source.position(b), v2 = source.position(c); + float x1 = v1.get(axisX) - origin.get(axisX), y1 = v1.get(axisY) - origin.get(axisY); + float x2 = v2.get(axisX) - origin.get(axisX), y2 = v2.get(axisY) - origin.get(axisY); + float x = px - origin.get(axisX), y = py - origin.get(axisY); + float area = x1 * y2 - y1 * x2; + if (area == 0) return false; + float w1 = (x * y2 - y * x2) / area, w2 = (x1 * y - y1 * x) / area; + float w0 = 1 - w1 - w2; + if (!extend && Math.min(w0, Math.min(w1, w2)) < -0.00001f) return false; + target.uv(index, w0 * source.u(0) + w1 * source.u(b) + w2 * source.u(c), + w0 * source.v(0) + w1 * source.v(b) + w2 * source.v(c)); + int aColor = source.color(0), bColor = source.color(b), cColor = source.color(c); + target.color(index, ARGB.color(channel(aColor, bColor, cColor, 24, w0, w1, w2), + channel(aColor, bColor, cColor, 16, w0, w1, w2), channel(aColor, bColor, cColor, 8, w0, w1, w2), + channel(aColor, bColor, cColor, 0, w0, w1, w2))); + if (normal != null) { + vertexNormal(source, 0, normal).mul(w0); + float nx = normal.x, ny = normal.y, nz = normal.z; + vertexNormal(source, b, normal).mul(w1).add(nx, ny, nz); + nx = normal.x; + ny = normal.y; + nz = normal.z; + vertexNormal(source, c, normal).mul(w2).add(nx, ny, nz); + if (normal.lengthSquared() == 0) target.packedNormal(index, 0); + else target.normal(index, normal.normalize()); + } + return true; + } + + private static int channel(int a, int b, int c, int shift, float w0, float w1, float w2) { + return Math.clamp(Math.round(w0 * (a >>> shift & 255) + w1 * (b >>> shift & 255) + w2 * (c >>> shift & 255)), 0, 255); + } + + /** 将图集横坐标转换到贴图以零至一表示的局部坐标。 */ + public static float localU(TextureAtlasSprite sprite, float atlasU) { + return (atlasU - sprite.getU0()) / (sprite.getU1() - sprite.getU0()); + } + + /** 将图集纵坐标转换到贴图以零至一表示的局部坐标。 */ + public static float localV(TextureAtlasSprite sprite, float atlasV) { + return (atlasV - sprite.getV0()) / (sprite.getV1() - sprite.getV0()); + } + + /** 将面上的精灵局部 UV 原地换算为图集 UV。 */ + public static MutableQuadView bake(MutableQuadView quad, TextureAtlasSprite sprite) { + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + quad.uv(vertex, sprite.getU(quad.u(vertex)), sprite.getV(quad.v(vertex))); + } + return quad; + } + + /** 将面上的图集 UV 原地换算为指定精灵的局部 UV。 */ + public static MutableQuadView unbake(MutableQuadView quad, TextureAtlasSprite sprite) { + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + quad.uv(vertex, localU(sprite, quad.u(vertex)), localV(sprite, quad.v(vertex))); + } + return quad; + } + + /** 替换材质并将旧图集 UV 重映射到新精灵,保留 UV 在精灵内的位置。 */ + public static MutableQuadView replace(MutableQuadView quad, MaterialInfo material) { + return bake(unbake(quad, quad.material().sprite()), material.sprite()).material(material); + } + + /** 在局部 UV 中顺时针旋转四分之一圈的整数倍,再按需要翻转横轴和纵轴。 */ + public static MutableQuadView transform(MutableQuadView quad, int turns, boolean flipU, boolean flipV) { + return transform(quad, turns, flipU, flipV, false); + } + + /** 撤销使用同样参数的 UV 变换,翻转与旋转按逆序应用。 */ + public static MutableQuadView inverse(MutableQuadView quad, int turns, boolean flipU, boolean flipV) { + return transform(quad, -turns, flipU, flipV, true); + } + + private static MutableQuadView transform(MutableQuadView quad, int turns, boolean flipU, boolean flipV, boolean inverse) { + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + float u = quad.u(vertex), v = quad.v(vertex); + if (inverse && flipU) u = 1 - u; + if (inverse && flipV) v = 1 - v; + float x = u, y = v; + switch (turns & 3) { + case 1 -> { + x = 1 - v; + y = u; + } + case 2 -> { + x = 1 - u; + y = 1 - v; + } + case 3 -> { + x = v; + y = 1 - u; + } + } + quad.uv(vertex, !inverse && flipU ? 1 - x : x, !inverse && flipV ? 1 - y : y); + } + return quad; + } + + /** 根据相对于方块原点的位置生成指定方向的局部 UV。 */ + public static MutableQuadView lockToFace(MutableQuadView quad, Direction face) { + for (int vertex = 0; vertex < QuadView.VERTEX_COUNT; vertex++) { + Vector3fc pos = quad.position(vertex); + switch (face) { + case DOWN -> quad.uv(vertex, pos.x(), 1 - pos.z()); + case UP -> quad.uv(vertex, pos.x(), pos.z()); + case NORTH -> quad.uv(vertex, 1 - pos.x(), 1 - pos.y()); + case SOUTH -> quad.uv(vertex, pos.x(), 1 - pos.y()); + case WEST -> quad.uv(vertex, pos.z(), 1 - pos.y()); + case EAST -> quad.uv(vertex, 1 - pos.z(), 1 - pos.y()); + } + } + return quad; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/QuadView.java b/src/main/java/com/modularmc/mmclutils/client/model/QuadView.java new file mode 100644 index 0000000..4d65c81 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/QuadView.java @@ -0,0 +1,101 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.client.model.geom.builders.UVPair; +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.core.Direction; + +import org.joml.Vector3fc; +import org.jspecify.annotations.Nullable; + +/** 读取一个四边形的四个顶点和材质。视图可以复用,回调退出后应保留副本。 */ +public interface QuadView { + + /** 一个四边形的顶点数。 */ + int VERTEX_COUNT = BakedQuad.VERTEX_COUNT; + + /** 返回只读顶点坐标,索引范围为零至三。 */ + Vector3fc position(int vertex); + + /** 返回使用原版 UVPair 编码的图集坐标。 */ + long packedUv(int vertex); + + /** 返回 NeoForge 编码的法线。零值表示使用面朝向。 */ + int packedNormal(int vertex); + + /** 返回顶点的 ARGB 调制色。 */ + int color(int vertex); + + /** 返回用于光照的面朝向。 */ + Direction lightFace(); + + /** 返回用于邻面遮挡判断的朝向。空值表示始终绘制。 */ + @Nullable + Direction cullFace(); + + /** 返回原版材质设置。 */ + MaterialInfo material(); + + /** 返回指定顶点的图集横坐标,范围取决于材质精灵。 */ + default float u(int vertex) { + return UVPair.unpackU(packedUv(vertex)); + } + + /** 返回指定顶点的图集纵坐标,范围取决于材质精灵。 */ + default float v(int vertex) { + return UVPair.unpackV(packedUv(vertex)); + } + + /** 返回显式顶点法线的位掩码,第零位至第三位按顶点顺序排列。 */ + default int normalFlags() { + int flags = 0; + for (int vertex = 0; vertex < VERTEX_COUNT; vertex++) { + if (packedNormal(vertex) != 0) flags |= 1 << vertex; + } + return flags; + } + + /** 判断是否存在至少一个显式顶点法线。 */ + default boolean hasVertexNormals() { + return (packedNormal(0) | packedNormal(1) | packedNormal(2) | packedNormal(3)) != 0; + } + + /** 包装原版烘焙四边形。传入该面所在的剔除分组,通用面传空值。 */ + static QuadView of(BakedQuad quad, @Nullable Direction cullFace) { + return new Baked(quad, cullFace); + } + + /** 提供原版烘焙面的只读视图,保留调用者指定的剔除分组。 */ + record Baked(BakedQuad quad, @Nullable Direction cullFace) implements QuadView { + + @Override + public Vector3fc position(int vertex) { + return quad.position(vertex); + } + + @Override + public long packedUv(int vertex) { + return quad.packedUV(vertex); + } + + @Override + public int packedNormal(int vertex) { + return quad.bakedNormals().normal(vertex); + } + + @Override + public int color(int vertex) { + return quad.bakedColors().color(vertex); + } + + @Override + public Direction lightFace() { + return quad.direction(); + } + + @Override + public MaterialInfo material() { + return quad.materialInfo(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamEffects.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamEffects.java new file mode 100644 index 0000000..a83dfc3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamEffects.java @@ -0,0 +1,177 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.client.render.effect.BurstEffects.BurstStyle; +import com.modularmc.mmclutils.client.render.effect.ParticleEffects.MoteLook; + +import net.minecraft.util.Mth; + +import org.jspecify.annotations.Nullable; + +import java.util.SplittableRandom; + +/** 在客户端渲染线程提交端点之间的定点连线、循环粒子流和传播脉冲。 */ +public final class BeamEffects { + + private static final SplittableRandom RANDOM = new SplittableRandom(0x2545F4914F6CDD1DL); + + private BeamEffects() {} + + static float unit(long seed, int salt) { + long z = seed + 0x9E3779B97F4A7C15L * (salt + 1); + z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L; + z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL; + z ^= z >>> 31; + return (z >>> 40) * 0x1.0p-24F; + } + + /** + * 为当帧创建沿线循环的光点流,应在 {@link EffectRenderer.Source#collect} 中每帧提交。 + * + * @param x0 起点世界坐标 X + * @param y0 起点世界坐标 Y + * @param z0 起点世界坐标 Z + * @param x1 终点世界坐标 X + * @param y1 终点世界坐标 Y + * @param z1 终点世界坐标 Z + * @param rgb 光点颜色的低 24 位 RGB + * @param seed 固定同一束流的发射相位和扰动 + * @param style 发射周期、行进时间和扰动参数 + * @param look 光点外观 + */ + public static void flow(double x0, double y0, double z0, double x1, double y1, double z1, int rgb, long seed, FlowStyle style, MoteLook look) { + if (!EffectRenderer.open()) return; + GpuParticleRenderer.rel(EffectRenderer.frameTime()); + int period = Math.max(1, style.period()); + int travel = Math.max(1, style.travel()); + int lanes = (travel + period - 1) / period + 1; + float phase = unit(seed, 0) * period; + float hashSeed = unit(seed, 1) * 1000; + for (int k = 0; k < lanes; k++) { + GpuParticleRenderer.write(GpuParticleRenderer.FLOW, x0, y0, z0, x1 - x0, y1 - y0, z1 - z0, 0, 0, style.sizeJitter(), style.jitter(), style.size(), style.alpha(), rgb, + GpuParticleRenderer.CONSTANT, 0, hashSeed, 0, period, travel, phase, k, look, false); + } + } + + static double pulseDuration(double length, PulseStyle style) { + double v = Math.max(0.01, style.speed()), lag = Math.max(0.01, style.lag()); + double t = length / v + lag; + for (int i = 0; i < 6; i++) { + double e = Math.exp(-t / lag); + double s = v * (t - lag * (1 - e)) - length; + double ds = v * (1 - e); + if (ds <= 1e-6) break; + t -= s / ds; + } + return Math.max(1, t); + } + + /** + * 向终点发送一次脉冲,并按样式生成延迟的尾迹和到达爆散。 + * + * @param x0 起点世界坐标 X + * @param y0 起点世界坐标 Y + * @param z0 起点世界坐标 Z + * @param x1 终点世界坐标 X + * @param y1 终点世界坐标 Y + * @param z1 终点世界坐标 Z + * @param rgb 光点颜色的低 24 位 RGB + * @param style 传播和尾迹参数 + * @param look 光点外观 + */ + public static void pulse(double x0, double y0, double z0, double x1, double y1, double z1, int rgb, PulseStyle style, MoteLook look) { + double now = EffectRenderer.now(); + if (Double.isNaN(now)) return; + double dx = x1 - x0, dy = y1 - y0, dz = z1 - z0; + float length = (float) Math.sqrt(dx * dx + dy * dy + dz * dz); + float duration = (float) pulseDuration(length, style); + float lag = Math.max(0.01F, style.lag()); + GpuParticleRenderer.write(GpuParticleRenderer.PULSE, x0, y0, z0, dx, dy, dz, now, duration, style.speed(), lag, style.size(), style.alpha(), rgb, GpuParticleRenderer.CONSTANT, 0, 0, + look.rollSpeed(), 0, 1, length, duration, look, false); + float trailLife = Math.max(0.5F, style.trailLife()); + float w = style.size() * 0.45F; + for (int i = 1; i <= style.trail(); i++) { + float delay = i * style.trailStep(); + float a = 1 - delay / trailLife; + if (a <= 0) break; + double ox = (RANDOM.nextFloat() - 0.5F) * w, oy = (RANDOM.nextFloat() - 0.5F) * w, oz = (RANDOM.nextFloat() - 0.5F) * w; + GpuParticleRenderer.write(GpuParticleRenderer.PULSE, x0 + ox, y0 + oy, z0 + oz, dx, dy, dz, now, duration + delay, style.speed(), lag, style.size(), style.alpha() * a, rgb, + GpuParticleRenderer.CONSTANT, 0, 0, look.rollSpeed(), delay, 0.7F + 0.3F * a, length, duration, look, false); + } + var arrival = style.arrival(); + if (arrival != null) BurstEffects.burstAt(x1, y1, z1, rgb, arrival, look, now + duration); + } + + /** + * 沿线段一次性生成一排短寿命的静止光点。两端重合或没有客户端世界时直接返回。 + * + * @param x0 起点世界坐标 X + * @param y0 起点世界坐标 Y + * @param z0 起点世界坐标 Z + * @param x1 终点世界坐标 X + * @param y1 终点世界坐标 Y + * @param z1 终点世界坐标 Z + * @param rgb 使用固定颜色时的低 24 位 RGB + * @param style 间距、寿命和颜色参数 + * @param look 光点外观 + */ + public static void beam(double x0, double y0, double z0, double x1, double y1, double z1, int rgb, BeamStyle style, MoteLook look) { + double now = EffectRenderer.now(); + if (Double.isNaN(now)) return; + double dx = x1 - x0, dy = y1 - y0, dz = z1 - z0; + double length = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (length <= 1e-4) return; + float step = Math.max(0.05F, style.spacing()); + int n = Math.min(512, (int) (length / step)); + float hue = RANDOM.nextFloat(); + for (int i = 0; i <= n; i++) { + double d = (i + (RANDOM.nextFloat() - 0.5F) * style.spacingJitter()) * step / length; + if (d < 0 || d > 1) continue; + int color = rgb; + if (style.rainbow()) { + int c = Mth.hsvToRgb(Mth.frac(hue + (float) d), 1, 1); + int r = Math.min(255, (c >> 16 & 0xFF) + 102), g = Math.min(255, (c >> 8 & 0xFF) + 102), b = Math.min(255, (c & 0xFF) + 102); + color = r << 16 | g << 8 | b; + } + GpuParticleRenderer.write(GpuParticleRenderer.BALLISTIC, x0 + dx * d, y0 + dy * d, z0 + dz * d, 0, 0, 0, now, Math.max(1, style.life()), 1, 0, style.size(), + style.alpha(), color, look.animated() ? GpuParticleRenderer.SHRINK : GpuParticleRenderer.CONSTANT, look.animated() ? 0 : GpuParticleRenderer.FADE, 0, look.rollSpeed(), 0, 0, 0, 0, look, false); + } + } + + /** + * 沿直线生成的粒子间距、寿命和着色参数。 + * + * @param spacing 间距,单位为方块,有效值至少为 0.05 + * @param spacingJitter 单个光点沿连线的偏移范围,以间距为单位 + * @param life 寿命,单位为 Tick,有效值至少为 1 + * @param size 光点边长,单位为方块 + * @param alpha 光点不透明度或亮度,范围为 0~1 + * @param rainbow 是否沿连线使用虹彩 + */ + public record BeamStyle(float spacing, float spacingJitter, int life, float size, float alpha, boolean rainbow) {} + + /** + * 端点间循环移动的粒子流样式。 + * + * @param period 相邻两次发射的间隔,单位为 Tick + * @param travel 光点从起点到终点耗时,单位为 Tick + * @param size 基础边长,单位为方块 + * @param sizeJitter 边长随机增加的最大比例 + * @param jitter 光点在各轴上的随机偏移范围,单位为方块 + * @param alpha 不透明度或亮度,范围为 0~1 + */ + public record FlowStyle(int period, int travel, float size, float sizeJitter, float jitter, float alpha) {} + + /** + * 沿线传播的脉冲参数。 + * + * @param speed 巡航速度,单位为方块每 Tick,应为正数 + * @param lag 从起点加速的时间常数,单位为 Tick + * @param trail 尾迹粒子数量上限 + * @param trailStep 相邻尾迹粒子的延时,单位为 Tick + * @param trailLife 用于计算尾迹衰减的寿命,单位为 Tick + * @param size 光点边长,单位为方块 + * @param alpha 不透明度或亮度,范围为 0~1 + * @param arrival 到达后使用的爆散样式,空值时省略爆散 + */ + public record PulseStyle(float speed, float lag, int trail, float trailStep, float trailLife, float size, float alpha, @Nullable BurstStyle arrival) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/BurstEffects.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/BurstEffects.java new file mode 100644 index 0000000..ca5c3f2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/BurstEffects.java @@ -0,0 +1,59 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.client.render.effect.ParticleEffects.MoteLook; + +import net.minecraft.util.Mth; + +import java.util.SplittableRandom; + +/** 在客户端渲染线程提交由光点组成的一次性球形爆散。 */ +public final class BurstEffects { + + private static final SplittableRandom RANDOM = new SplittableRandom(0x5DEECE66DL); + + private BurstEffects() {} + + /** + * 在给定世界坐标生成一组逐渐扩散的光点,当前没有客户端世界时直接返回。 + * + * @param x 中心坐标 X + * @param y 中心坐标 Y + * @param z 中心坐标 Z + * @param rgb 光点颜色的低 24 位 RGB + * @param style 扩散范围和寿命等参数 + * @param look 光点外观 + */ + public static void burst(double x, double y, double z, int rgb, BurstStyle style, MoteLook look) { + double now = EffectRenderer.now(); + if (!Double.isNaN(now)) burstAt(x, y, z, rgb, style, look, now); + } + + static void burstAt(double x, double y, double z, int rgb, BurstStyle style, MoteLook look, double start) { + float life = Math.max(1, style.life()); + for (int i = 0; i < style.count(); i++) { + float u = RANDOM.nextFloat() * 2 - 1; + float t = RANDOM.nextFloat() * Mth.TWO_PI; + float s = Mth.sqrt(1 - u * u); + float rad = style.radius() * (0.4F + 0.6F * RANDOM.nextFloat()); + double px = x + (RANDOM.nextFloat() - 0.5F) * style.spreadXZ(); + double py = y + (RANDOM.nextFloat() - 0.5F) * style.spreadY(); + double pz = z + (RANDOM.nextFloat() - 0.5F) * style.spreadXZ(); + GpuParticleRenderer.write(GpuParticleRenderer.BURST, px, py, pz, s * Mth.cos(t) * rad, u * rad, s * Mth.sin(t) * rad, start, life, 0, style.rise(), style.size(), + style.alpha(), rgb, GpuParticleRenderer.CONSTANT, GpuParticleRenderer.FADE, RANDOM.nextFloat() * Mth.TWO_PI, look.rollSpeed(), 0, 0, 0, 0, look, false); + } + } + + /** + * 一次爆散的粒子数量、寿命、初始分布与视觉参数。 + * + * @param count 生成的光点数 + * @param life 寿命,单位为 Tick,有效值至少为 1 + * @param radius 单个光点的最大径向位移,单位为方块 + * @param spreadXZ 起点在 X、Z 轴上各自的偏移范围,单位为方块 + * @param spreadY 起点在 Y 轴上的偏移范围,单位为方块 + * @param rise 附加的竖直速度,单位为方块每 Tick + * @param size 光点边长,单位为方块 + * @param alpha 不透明度或亮度,范围为 0~1 + */ + public record BurstStyle(int count, int life, float radius, float spreadXZ, float spreadY, float rise, float size, float alpha) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectClock.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectClock.java new file mode 100644 index 0000000..f9d39a9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectClock.java @@ -0,0 +1,86 @@ +package com.modularmc.mmclutils.client.render.effect; + +import java.util.Map; +import java.util.WeakHashMap; + +/** + * 为客户端渲染状态推进渐入、渐出与本地动画时间。 + * 以弱引用缓存所有者。时钟和缓存均在客户端渲染线程访问。 + */ +public final class EffectClock { + + private static final Map CLOCKS = new WeakHashMap<>(); + private static final double MAX_STEP = 20; + + private final float riseTicks; + private final float fallTicks; + private float intensity; + private double time; + private double lastNow = Double.NaN; + private int color = -1; + + private EffectClock(float riseTicks, float fallTicks) { + this.riseTicks = riseTicks; + this.fallTicks = fallTicks; + } + + /** + * 取得与所有者关联的时钟。首次调用确定渐入与渐出时长。 + * + * @param owner 用于查找时钟的所有者,按相等性查找 + * @param riseTicks 从零到完全可见的 Tick 数,应为有限正数 + * @param fallTicks 从完全可见到零的 Tick 数,应为有限正数 + * @return 可跨帧复用的效果时钟 + */ + public static EffectClock of(Object owner, float riseTicks, float fallTicks) { + var clock = CLOCKS.get(owner); + if (clock == null) { + clock = new EffectClock(riseTicks, fallTicks); + CLOCKS.put(owner, clock); + } + return clock; + } + + /** + * 推进效果。首次调用以当前时间为起点,时间倒退时本步保持原进度。 + * 暂停或掉帧后的单次步长最多按 20 Tick 计算。 + * + * @param active 效果是否应当显现 + * @param now 当前动画时间,单位为 Tick,须为有限值 + */ + public void update(boolean active, double now) { + double step = Double.isNaN(lastNow) ? 0 : Math.max(0, Math.min(now - lastNow, MAX_STEP)); + lastNow = now; + if (active) intensity = (float) Math.min(1, intensity + step / riseTicks); + else intensity = (float) Math.max(0, intensity - step / fallTicks); + float speed = intensity * intensity * (3 - 2 * intensity); + time += step * speed; + } + + /** 当前强度大于零时返回真,包括渐出期间。 */ + public boolean visible() { + return intensity > 0; + } + + /** 返回 0~1 的当前效果强度。 */ + public float intensity() { + return intensity; + } + + /** 返回按效果强度推进的本地动画时间,单位为 Tick。 */ + public double time() { + return time; + } + + /** + * 更新并读取效果颜色。使用 -1 表示没有新颜色,可在渐出时沿用最近颜色。 + * + * @param current 新的低 24 位 RGB 或 -1 + * @param fallback 时钟尚未记录颜色时使用的默认值 + * @return 最新有效颜色,或指定的默认值 + */ + public int color(int current, int fallback) { + if (current != -1) color = current; + return color == -1 ? fallback : color; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectPalette.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectPalette.java new file mode 100644 index 0000000..d73dab1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectPalette.java @@ -0,0 +1,70 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.util.Mth; + +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; + +import java.util.SplittableRandom; + +/** 根据基色生成可复用的粒子色板,在客户端渲染线程访问。 */ +public final class EffectPalette { + + /** 每份色板的颜色数。 */ + public static final int SIZE = 24; + private static final long SEED = 0x6A7E5L; + private static final float HOT_CHANCE = 0.16F; + private static final float HUE_JITTER = 0.045F; + private static final int CACHE_LIMIT = 64; + private static final Int2ObjectOpenHashMap CACHE = new Int2ObjectOpenHashMap<>(); + + private EffectPalette() {} + + /** + * 为给定基色生成固定序列的明暗与色相变化。同一基色可复用缓存结果。 + * + * @param rgb 低 24 位的基色 RGB + * @return 共享的 RGB 色板,调用方须将其视为只读 + */ + public static int[] shades(int rgb) { + rgb &= 0xFFFFFF; + var colors = CACHE.get(rgb); + if (colors == null) { + if (CACHE.size() >= CACHE_LIMIT) CACHE.clear(); + colors = build(rgb); + CACHE.put(rgb, colors); + } + return colors; + } + + private static int[] build(int rgb) { + float red = (rgb >> 16 & 0xFF) / 255F, green = (rgb >> 8 & 0xFF) / 255F, blue = (rgb & 0xFF) / 255F; + float max = Math.max(red, Math.max(green, blue)), min = Math.min(red, Math.min(green, blue)); + float delta = max - min; + float hue = 0; + if (delta > 0) { + if (max == red) hue = ((green - blue) / delta) / 6F; + else if (max == green) hue = ((blue - red) / delta + 2) / 6F; + else hue = ((red - green) / delta + 4) / 6F; + if (hue < 0) hue += 1; + } + float saturation = max == 0 ? 0 : delta / max; + var random = new SplittableRandom(SEED); + var colors = new int[SIZE]; + for (int i = 0; i < SIZE; i++) { + float h = hue + (float) (random.nextDouble() - 0.5) * 2 * HUE_JITTER; + h -= Mth.floor(h); + float s = Mth.clamp(saturation * (0.7F + 0.4F * (float) random.nextDouble()), 0, 1); + float v = 0.72F + 0.28F * (float) random.nextDouble(); + int color = Mth.hsvToRgb(h, s, v); + if (random.nextDouble() < HOT_CHANCE) { + float white = 0.55F + 0.3F * (float) random.nextDouble(); + int r = (int) Mth.lerp(white, color >> 16 & 0xFF, 255); + int g = (int) Mth.lerp(white, color >> 8 & 0xFF, 255); + int b = (int) Mth.lerp(white, color & 0xFF, 255); + color = r << 16 | g << 8 | b; + } + colors[i] = color; + } + return colors; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java new file mode 100644 index 0000000..15bb4b6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java @@ -0,0 +1,93 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.mixin.mc.client.GlBufferAccessor; + +import net.minecraft.client.Minecraft; +import net.minecraft.resources.Identifier; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.VertexFormat; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector3f; +import org.joml.Vector4f; +import org.joml.Vector4fc; +import org.jspecify.annotations.Nullable; + +import java.nio.ByteBuffer; +import java.util.OptionalDouble; +import java.util.OptionalInt; + +/** 变换反馈和普通顶点写入共享相同的缓冲布局。 */ +final class EffectQuadBuffer implements AutoCloseable { + + static final int VERTEX_BYTES = 9 * Float.BYTES; + private static final Vector4f WHITE = new Vector4f(1); + private static final Vector3f ZERO = new Vector3f(); + private static final Matrix4f IDENTITY = new Matrix4f(); + + private @Nullable GpuBuffer verticesBuffer; + int buffer; + int vertices; + + void reserve(int vertexCapacity) { + long bytes = (long) vertexCapacity * VERTEX_BYTES; + if (verticesBuffer != null && verticesBuffer.size() >= bytes) return; + close(); + verticesBuffer = RenderSystem.getDevice().createBuffer( + () -> "mmclutils-effects", GpuBuffer.USAGE_VERTEX | GpuBuffer.USAGE_COPY_DST, Math.max(bytes, VERTEX_BYTES)); + if (verticesBuffer instanceof GlBufferAccessor accessor) buffer = accessor.mmclutils$handle(); + } + + void upload(ByteBuffer bytes) { + int count = bytes.remaining() / VERTEX_BYTES; + if (count != 0) { + reserve(count); + RenderSystem.getDevice().createCommandEncoder().writeToBuffer(verticesBuffer.slice(0, bytes.remaining()), bytes); + } + vertices = count; + } + + void draw(RenderPipeline pipeline, Identifier textureId) { + draw(pipeline, textureId, EffectRenderer.modelView(), WHITE); + } + + void draw(RenderPipeline pipeline, Identifier textureId, Matrix4fc pose) { + draw(pipeline, textureId, pose, WHITE); + } + + void draw(RenderPipeline pipeline, Identifier textureId, Matrix4fc pose, Vector4fc tint) { + if (vertices == 0) return; + var mc = Minecraft.getInstance(); + var target = mc.getMainRenderTarget(); + var color = RenderSystem.outputColorTextureOverride != null ? RenderSystem.outputColorTextureOverride : target.getColorTextureView(); + var depth = RenderSystem.outputDepthTextureOverride != null ? RenderSystem.outputDepthTextureOverride : target.getDepthTextureView(); + var texture = mc.getTextureManager().getTexture(textureId); + int indexCount = vertices / 4 * 6; + var indices = RenderSystem.getSequentialBuffer(VertexFormat.Mode.QUADS); + var indexBuffer = indices.getBuffer(indexCount); + var transform = RenderSystem.getDynamicUniforms().writeTransform(pose, tint, ZERO, IDENTITY); + try (var pass = RenderSystem.getDevice().createCommandEncoder() + .createRenderPass(() -> "mmclutils-effects", color, OptionalInt.empty(), depth, OptionalDouble.empty())) { + pass.setPipeline(pipeline); + RenderSystem.bindDefaultUniforms(pass); + pass.setUniform("DynamicTransforms", transform); + pass.bindTexture("Sampler0", texture.getTextureView(), texture.getSampler()); + pass.setVertexBuffer(0, verticesBuffer); + pass.setIndexBuffer(indexBuffer, indices.type()); + pass.drawIndexed(0, 0, indexCount, 1); + } + } + + @Override + public void close() { + if (verticesBuffer != null) { + verticesBuffer.close(); + verticesBuffer = null; + } + buffer = 0; + vertices = 0; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java new file mode 100644 index 0000000..0ab2ca9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java @@ -0,0 +1,115 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.resources.Identifier; +import net.neoforged.neoforge.client.event.RegisterRenderPipelinesEvent; + +import com.mojang.blaze3d.pipeline.BlendFunction; +import com.mojang.blaze3d.pipeline.ColorTargetState; +import com.mojang.blaze3d.pipeline.DepthStencilState; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.platform.CompareOp; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexFormatElement; +import org.jspecify.annotations.Nullable; + +import java.util.Optional; + +/** 环、光点和实体附着共用的原版绘制状态与纹理。 */ +public final class EffectRenderPipelines { + + /** 渐隐的环形光带纹理。 */ + public static final Identifier GLOW_TEXTURE = ModularMCLibUtils.id("effect/glow"); + /** 绘制纯色几何时使用的白色纹理。 */ + public static final Identifier WHITE_TEXTURE = ModularMCLibUtils.id("effect/white"); + /** RGB 已按透明度渐变的光点纹理,供加法混合使用。 */ + public static final Identifier MOTE_TEXTURE = ModularMCLibUtils.id("effect/mote"); + + private static final VertexFormat FORMAT = VertexFormat.builder() + .add("Position", VertexFormatElement.POSITION) + .add("Color", VertexFormatElement.register( + VertexFormatElement.findNextId(), 0, VertexFormatElement.Type.FLOAT, false, 4)) + .add("UV0", VertexFormatElement.UV0) + .build(); + + /** 使用场景深度测试与深度写入绘制实体四边形。 */ + public static final RenderPipeline VOXEL = program("voxel", null, true, false); + /** 使用场景深度测试,以加法混合写入颜色。 */ + public static final RenderPipeline GLOW = program("glow", BlendFunction.ADDITIVE, false, false); + /** 以透明度混合绘制穿过场景的高亮。 */ + public static final RenderPipeline HIGHLIGHT = program("highlight", BlendFunction.TRANSLUCENT, false, true); + private static final RenderPipeline GLOW_THROUGH = program("glow_through", BlendFunction.ADDITIVE, false, true); + private static final RenderPipeline ATLAS = program("particle", BlendFunction.TRANSLUCENT, false, false); + private static final RenderPipeline ATLAS_THROUGH = program("particle_through", BlendFunction.TRANSLUCENT, false, true); + private static boolean texturesReady; + + private EffectRenderPipelines() {} + + static void init(RegisterRenderPipelinesEvent event) { + for (RenderPipeline pipeline : new RenderPipeline[] { VOXEL, GLOW, HIGHLIGHT, GLOW_THROUGH, ATLAS, ATLAS_THROUGH }) { + event.registerPipeline(pipeline); + } + } + + /** 选择对应遮挡规则的加法混合管线。传入真时跳过场景深度测试。 */ + public static RenderPipeline glow(boolean throughWalls) { + return throughWalls ? GLOW_THROUGH : GLOW; + } + + /** 选择对应遮挡规则的粒子图集管线,颜色按透明度混合。 */ + public static RenderPipeline atlas(boolean throughWalls) { + return throughWalls ? ATLAS_THROUGH : ATLAS; + } + + private static RenderPipeline program(String path, @Nullable BlendFunction blend, boolean writeDepth, boolean throughWalls) { + return RenderPipeline.builder(RenderPipelines.MATRICES_PROJECTION_SNIPPET) + .withLocation(ModularMCLibUtils.id("pipeline/effect/" + path)) + .withVertexShader("core/position_tex_color") + .withFragmentShader("core/position_tex_color") + .withSampler("Sampler0") + .withCull(false) + .withDepthStencilState(throughWalls ? Optional.empty() : Optional.of(new DepthStencilState(CompareOp.LESS_THAN_OR_EQUAL, writeDepth))) + .withColorTargetState(blend == null ? ColorTargetState.DEFAULT : new ColorTargetState(blend)) + .withVertexFormat(FORMAT, VertexFormat.Mode.QUADS) + .build(); + } + + static void ensureTextures() { + if (texturesReady) return; + int size = 16; + var glow = new NativeImage(size, size, false); + var mote = new NativeImage(size, size, false); + float center = (size - 1) / 2f; + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + float dx = (x - center) / (size / 2f); + float dy = (y - center) / (size / 2f); + float fade = Math.max(0, 1 - (float) Math.sqrt(dx * dx + dy * dy)); + int alpha = Math.round((float) Math.ceil(fade * fade * 5) * 51); + glow.setPixel(x, y, alpha << 24 | 0xFFFFFF); + mote.setPixel(x, y, alpha * 0x01010101); + } + } + var white = new NativeImage(1, 1, false); + white.setPixel(0, 0, -1); + var textures = Minecraft.getInstance().getTextureManager(); + textures.register(GLOW_TEXTURE, new DynamicTexture(GLOW_TEXTURE::toString, glow)); + textures.register(MOTE_TEXTURE, new DynamicTexture(MOTE_TEXTURE::toString, mote)); + textures.register(WHITE_TEXTURE, new DynamicTexture(WHITE_TEXTURE::toString, white)); + texturesReady = true; + } + + static void releaseTextures() { + if (!texturesReady) return; + var textures = Minecraft.getInstance().getTextureManager(); + textures.release(GLOW_TEXTURE); + textures.release(WHITE_TEXTURE); + textures.release(MOTE_TEXTURE); + texturesReady = false; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java new file mode 100644 index 0000000..848498c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java @@ -0,0 +1,315 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.client.render.effect.ParticleRing.RingShape; +import com.modularmc.mmclutils.client.render.effect.ParticleRing.RingStyle; + +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.Direction; +import net.minecraft.server.packs.resources.ResourceManagerReloadListener; +import net.minecraft.util.Mth; +import net.minecraft.util.context.ContextKey; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.AddClientReloadListenersEvent; +import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.ExtractLevelRenderStateEvent; +import net.neoforged.neoforge.client.event.RenderLevelStageEvent; +import net.neoforged.neoforge.event.GameShuttingDownEvent; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.ApiStatus; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.jspecify.annotations.Nullable; + +/** + * 在客户端渲染线程收集环形和连续粒子流,在不透明世界几何体之后批量绘制。 + * 实体附着和球形高亮在半透明粒子之后提交,时间推进由客户端 Tick 驱动。 + */ +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID, value = Dist.CLIENT) +public final class EffectRenderer { + + private static final ContextKey FRAME = new ContextKey<>(ModularMCLibUtils.id("effect_frame")); + private static final ObjectArrayList RINGS = new ObjectArrayList<>(); + private static final ObjectArrayList SOURCES = new ObjectArrayList<>(); + private static final Matrix4f MODEL_VIEW = new Matrix4f(); + private static int ringCount; + private static long frame; + private static @Nullable ClientLevel collectingLevel; + private static double frameTime; + private static long clientTicks; + private static @Nullable ClientLevel lastLevel; + private static @Nullable Camera camera; + + private EffectRenderer() {} + + static final class RingCommand { + + ParticleRing ring; + float x, y, z; + Direction.Axis axis; + double time; + float scale; + int[] palette; + float spriteSize; + int spriteStrength; + RingStyle style; + int baseColor; + float intensity; + RingShape shape; + } + + /** + * 检查当前是否在指定世界的帧收集回调中。 + * + * @param level 欲提交效果的世界 + * @return 当前帧正在此世界采集时为 {@code true} + */ + public static boolean collecting(Level level) { + return open() && collectingLevel == level; + } + + static boolean open() { + return collectingLevel != null; + } + + /** + * 添加跨帧使用的采集入口。相同入口只登记一次,须在采集回调之外调用。 + * + * @param source 提交环形或连续粒子流的回调 + */ + public static void addSource(Source source) { + if (!SOURCES.contains(source)) SOURCES.add(source); + } + + /** + * 移除先前添加的采集入口。已经采集的命令仍可在当帧绘制。 + * + * @param source 要移除的回调 + */ + public static void removeSource(Source source) { + SOURCES.remove(source); + } + + /** + * 读取客户端效果时钟,以 Tick 计并包含当前 Tick 内插值。 + * + * @return 当前客户端时间,未进入世界时为 NaN + */ + public static double now() { + Minecraft client = Minecraft.getInstance(); + return client.level == null ? Double.NaN : clientTicks + client.getDeltaTracker().getGameTimeDeltaPartialTick(false); + } + + /** 返回最近一次世界帧采集使用的效果时间,单位为 Tick。 */ + public static double frameTime() { + return frameTime; + } + + /** 返回上一次提交给绘制管线的光点数。变换反馈路径以进入反馈的实例数计。 */ + public static int lastMoteCount() { + return GpuParticleRenderer.lastDrawn(); + } + + /** 返回当前帧尚未过期的光点记录数,包含连续粒子流。 */ + public static int activeTimedEffects() { + return GpuParticleRenderer.live(frameTime); + } + + static Matrix4fc modelView() { + return MODEL_VIEW; + } + + static float breathe(RingCommand command) { + return 0.9f + 0.1f * Mth.sin((float) (command.time * 0.21 % (2 * Math.PI))); + } + + /** + * 在 {@link Source#collect} 中提交完整闭环。参数遵循带 {@link RingShape} 的重载。 + * + * @param ring 可复用的粒子运动数据 + * @param style 发光精灵与光带参数 + * @param worldX 中心世界坐标 X + * @param worldY 中心世界坐标 Y + * @param worldZ 中心世界坐标 Z + * @param axis 环的轴线 + * @param time 环的动画时间,单位为 Tick + * @param intensity 效果强度,范围为 0~1 + * @param baseColor 光带的 RGB + * @param palette 粒子色板,至少含 {@link EffectPalette#SIZE} 种颜色 + */ + public static void ring(ParticleRing ring, RingStyle style, double worldX, double worldY, double worldZ, Direction.Axis axis, + double time, float intensity, int baseColor, int[] palette) { + ring(ring, style, RingShape.CLOSED, worldX, worldY, worldZ, axis, time, intensity, baseColor, palette); + } + + /** + * 提交闭环或螺旋。供 {@link Source#collect} 调用,帧采集之外提交时直接返回。 + * 渲染器在当帧读取色板,调用方须保持其内容稳定。 + * + * @param ring 可复用的粒子运动数据 + * @param style 发光精灵与光带参数 + * @param shape 环或多股螺旋的轮廓 + * @param worldX 原点世界坐标 X + * @param worldY 原点世界坐标 Y + * @param worldZ 原点世界坐标 Z + * @param axis 环的轴线 + * @param time 环的动画时间,单位为 Tick + * @param intensity 效果强度,范围为 0~1 + * @param baseColor 光带的 RGB + * @param palette 粒子色板,至少含 {@link EffectPalette#SIZE} 种颜色 + * @throws IllegalArgumentException 正在采集且色板长度不足 + */ + public static void ring(ParticleRing ring, RingStyle style, RingShape shape, double worldX, double worldY, double worldZ, + Direction.Axis axis, double time, float intensity, int baseColor, int[] palette) { + if (!open()) return; + if (palette.length < EffectPalette.SIZE) throw new IllegalArgumentException("环的色板长度不足"); + if (ringCount == RINGS.size()) RINGS.add(new RingCommand()); + RingCommand command = RINGS.get(ringCount++); + Vec3 eye = camera.position(); + float scale = intensity * intensity * (3 - 2 * intensity); + command.ring = ring; + command.x = (float) (worldX - eye.x); + command.y = (float) (worldY - eye.y); + command.z = (float) (worldZ - eye.z); + command.axis = axis; + command.time = time; + command.scale = scale; + command.palette = palette; + command.spriteSize = ParticleRing.PIXEL * style.spriteScale() * scale; + command.spriteStrength = (int) (style.spriteStrength() * intensity); + command.style = style; + command.baseColor = baseColor; + command.intensity = intensity; + command.shape = shape; + } + + @SubscribeEvent + private static void collectFrame(ExtractLevelRenderStateEvent event) { + frameTime = now(); + camera = event.getCamera(); + ringCount = 0; + PlayerAttachmentRenderer.beginFrame(event.getRenderState().cameraRenderState.pos); + GpuParticleRenderer.beginFrame(); + event.getRenderState().setRenderData(FRAME, ++frame); + Vec3 eye = camera.position(); + ClientLevel level = event.getLevel(); + collectingLevel = level; + try { + for (int index = 0; index < SOURCES.size(); index++) { + SOURCES.get(index).collect(level, frameTime, eye.x, eye.y, eye.z); + } + } finally { + collectingLevel = null; + } + } + + private static boolean matchesFrame(RenderLevelStageEvent event) { + Long extracted = event.getLevelRenderState().getRenderData(FRAME); + return extracted != null && extracted.longValue() == frame && camera != null; + } + + @SubscribeEvent + private static void drawWorldEffects(RenderLevelStageEvent.AfterOpaqueFeatures event) { + if (!matchesFrame(event)) return; + EffectRenderPipelines.ensureTextures(); + MODEL_VIEW.set(event.getModelViewMatrix()); + if (ringCount != 0) { + RingRenderer.draw(RINGS, ringCount, camera); + ringCount = 0; + } + GpuParticleRenderer.flush(frameTime, camera); + } + + @SubscribeEvent + private static void drawAttachmentsAndHighlights(RenderLevelStageEvent.AfterTranslucentParticles event) { + if (!matchesFrame(event)) return; + PlayerAttachmentRenderer.drawPending(); + SphereHighlight.draw(camera.position(), MODEL_VIEW); + } + + @SubscribeEvent + private static void tickEffects(ClientTickEvent.Post event) { + Minecraft client = Minecraft.getInstance(); + ClientLevel level = client.level; + if (level != lastLevel) { + clearWorldEffects(); + lastLevel = level; + } + if (level == null || client.isPaused()) return; + clientTicks++; + SphereHighlight.tick(); + ParticleEmitters.tick(level); + } + + private static void clearWorldEffects() { + GpuParticleRenderer.clear(); + ParticleEmitters.clear(); + PlayerAttachmentRenderer.clearFrame(); + PlayerAttachmentRenderer.releaseBuffers(); + SphereHighlight.clear(); + RINGS.clear(); + camera = null; + ringCount = 0; + } + + /** 将管线、资源重载和玩家模型层接入客户端模组总线。 */ + @ApiStatus.Internal + public static void init(IEventBus modBus) { + modBus.addListener(EffectRenderPipelines::init); + modBus.addListener(EffectRenderer::initResourceReload); + modBus.addListener(PlayerAttachmentRenderer::initLayers); + } + + private static void initResourceReload(AddClientReloadListenersEvent event) { + event.addListener(ModularMCLibUtils.id("effects"), (ResourceManagerReloadListener) manager -> releaseRenderBuffers()); + } + + private static void releaseRenderBuffers() { + MoteSprite.generation++; + GpuParticleRenderer.reload(); + RingRenderer.reload(); + PlayerAttachmentRenderer.releaseBuffers(); + SphereHighlight.release(); + EffectRenderPipelines.releaseTextures(); + } + + @SubscribeEvent + private static void clearOnDisconnect(ClientPlayerNetworkEvent.LoggingOut event) { + clearWorldEffects(); + lastLevel = null; + } + + @SubscribeEvent + private static void releaseOnShutdown(GameShuttingDownEvent event) { + clearWorldEffects(); + releaseRenderBuffers(); + } + + /** + * 在世界状态提取时提交一帧的绘制指令。 + * 回调在客户端渲染线程执行,可利用世界和相机状态决定要提交的效果。 + */ + @FunctionalInterface + public interface Source { + + /** + * 采集本帧的效果。请在回调返回前完成命令提交。 + * + * @param level 本次绘制的客户端世界 + * @param time 动画时间,单位为 Tick + * @param camX 相机世界坐标 X + * @param camY 相机世界坐标 Y + * @param camZ 相机世界坐标 Z + */ + void collect(ClientLevel level, double time, double camX, double camY, double camZ); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectVertices.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectVertices.java new file mode 100644 index 0000000..f283bfd --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectVertices.java @@ -0,0 +1,58 @@ +package com.modularmc.mmclutils.client.render.effect; + +import org.joml.Vector3fc; +import org.jspecify.annotations.Nullable; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +/** 按变换反馈的排列写入四边形,供没有 OpenGL 反馈能力的设备使用。 */ +final class EffectVertices { + + private static final float[] X = { 1, -1, -1, 1 }; + private static final float[] Y = { -1, -1, 1, 1 }; + private @Nullable ByteBuffer bytes; + + void begin(int quads) { + int length = Math.multiplyExact(Math.max(1, quads), 4 * EffectQuadBuffer.VERTEX_BYTES); + if (bytes == null) bytes = MemoryUtil.memAlloc(length); + else if (bytes.capacity() < length) bytes = MemoryUtil.memRealloc(bytes, length); + bytes.clear(); + } + + void facing(float x, float y, float z, Vector3fc left, Vector3fc up, float size, float angle, + float red, float green, float blue, float alpha, float u0, float v0, float u1, float v1) { + float cosine = (float) Math.cos(angle); + float sine = (float) Math.sin(angle); + float half = size * 0.5f; + for (int vertex = 0; vertex < 4; vertex++) { + float horizontal = (X[vertex] * cosine - Y[vertex] * sine) * half; + float vertical = (X[vertex] * sine + Y[vertex] * cosine) * half; + bytes.putFloat(x + left.x() * horizontal + up.x() * vertical); + bytes.putFloat(y + left.y() * horizontal + up.y() * vertical); + bytes.putFloat(z + left.z() * horizontal + up.z() * vertical); + bytes.putFloat(red).putFloat(green).putFloat(blue).putFloat(alpha); + bytes.putFloat(X[vertex] > 0 ? u0 : u1).putFloat(Y[vertex] > 0 ? v0 : v1); + } + } + + void writeVertex(float x, float y, float z, int rgb, float alpha, float u, float v) { + writeVertex(x, y, z, (rgb >> 16 & 255) / 255f, (rgb >> 8 & 255) / 255f, (rgb & 255) / 255f, alpha, u, v); + } + + void writeVertex(float x, float y, float z, float red, float green, float blue, float alpha, float u, float v) { + bytes.putFloat(x).putFloat(y).putFloat(z); + bytes.putFloat(red).putFloat(green).putFloat(blue).putFloat(alpha).putFloat(u).putFloat(v); + } + + void upload(EffectQuadBuffer output) { + output.upload(bytes.flip()); + } + + void release() { + if (bytes != null) { + MemoryUtil.memFree(bytes); + bytes = null; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java new file mode 100644 index 0000000..40374e0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java @@ -0,0 +1,422 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.client.render.effect.ParticleEffects.MoteLook; + +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.texture.TextureAtlas; + +import com.mojang.blaze3d.opengl.GlStateManager; +import org.joml.Vector3f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL33; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.SplittableRandom; + +/** + * 光点产生时写入槽位池。每帧通过变换反馈批量展开为朝向相机的四边形,再用原版管线绘制。 + */ +final class GpuParticleRenderer { + + static final int BALLISTIC = 0, SLIDE = 1, PULSE = 2, BURST = 3, FLOW = 4; + static final int FADE = 1, ANIMATED = 4; + static final int SHRINK = 0, PULSE_SIZE = 1, CONSTANT = 2; + static final float CULL = (float) ParticleEffects.SPAWN_DISTANCE + 8; + private static final int RECORD_BYTES = 128; + private static final int FRAME_COLUMNS = MoteSprite.MAX_FRAMES; + private static final int FRAME_ROWS = 64; + private static final int PROBES = 64; + + static final class Pool { + + final boolean atlas, throughWalls, stream; + final int capacity; + final ByteBuffer mirror; + final long address; + final float[] ends; + int cursor, highWater, dirtyMin = Integer.MAX_VALUE, dirtyMax = -1, count; + double maxEnd; + int buffer = -1; + final EffectQuadBuffer out = new EffectQuadBuffer(); + final EffectQuadBuffer coreOut = new EffectQuadBuffer(); + + Pool(int capacity, boolean atlas, boolean throughWalls, boolean stream) { + this.capacity = capacity; + this.atlas = atlas; + this.throughWalls = throughWalls; + this.stream = stream; + this.mirror = MemoryUtil.memAlloc(capacity * RECORD_BYTES); + this.address = MemoryUtil.memAddress(mirror); + this.ends = new float[capacity]; + } + + long slot(double now, double end) { + int slot; + if (stream) { + if (count >= capacity) return -1; + slot = count++; + } else { + slot = -1; + for (int i = 0; i < PROBES && highWater > 0; i++) { + if (cursor >= highWater) cursor = 0; + int s = cursor++; + if (ends[s] <= now) { + slot = s; + break; + } + } + if (slot < 0) { + if (highWater < capacity) { + slot = highWater; + } else { + if (cursor >= capacity) cursor = 0; + slot = cursor++; + } + } + ends[slot] = (float) end; + maxEnd = Math.max(maxEnd, end); + dirtyMin = Math.min(dirtyMin, slot); + dirtyMax = Math.max(dirtyMax, slot); + } + highWater = Math.max(highWater, slot + 1); + return address + (long) slot * RECORD_BYTES; + } + + void trim(double now) { + while (highWater > 0 && ends[highWater - 1] <= now) highWater--; + } + + void clear() { + cursor = highWater = count = 0; + maxEnd = 0; + dirtyMin = Integer.MAX_VALUE; + dirtyMax = -1; + Arrays.fill(ends, 0); + } + } + + private static final Pool GLOW = new Pool(16384, false, false, false); + private static final Pool GLOW_X = new Pool(4096, false, true, false); + private static final Pool ATLAS = new Pool(32768, true, false, false); + private static final Pool ATLAS_X = new Pool(8192, true, true, false); + private static final Pool FLOW_GLOW = new Pool(4096, false, false, true); + private static final Pool FLOW_ATLAS = new Pool(4096, true, false, true); + private static final Pool[] POOLS = { GLOW, GLOW_X, ATLAS, ATLAS_X, FLOW_GLOW, FLOW_ATLAS }; + private static final SplittableRandom RANDOM = new SplittableRandom(0x6D2B79F5L); + private static final ByteBuffer FRAME_PIXELS = MemoryUtil.memAlloc(FRAME_COLUMNS * FRAME_ROWS * 16); + private static TransformFeedbackProgram program; + private static int programState = -1; + private static int simulateVao = -1; + private static int frameTexture = -1; + private static int frameRows; + private static int frameGeneration = -1; + private static boolean framesDirty; + private static double epoch = Double.NaN; + private static int lastDrawn; + + private GpuParticleRenderer() {} + + static boolean available() { + if (programState < 0) { + boolean ok = TransformFeedbackProgram.supported(); + if (ok) program = TransformFeedbackProgram.load("mote.vsh"); + programState = ok && program != null ? 1 : 0; + if (programState == 0) ModularMCLibUtils.LOGGER.info("光点采用普通顶点绘制"); + } + return programState == 1; + } + + static float rel(double time) { + if (Double.isNaN(epoch)) epoch = Math.floor(time); + return (float) (time - epoch); + } + + static void clear() { + for (var pool : POOLS) pool.clear(); + epoch = Double.NaN; + } + + static void beginFrame() { + FLOW_GLOW.clear(); + FLOW_ATLAS.clear(); + } + + static int lastDrawn() { + return lastDrawn; + } + + static int live(double now) { + int n = 0; + for (var pool : POOLS) { + if (pool.stream) { + n += pool.count; + continue; + } + for (int i = 0; i < pool.highWater; i++) { + if (pool.ends[i] > now) n++; + } + } + return n; + } + + private static Pool pool(MoteLook look, boolean throughWalls, boolean stream) { + boolean atlas = look.sprite() != null; + if (stream) return atlas ? FLOW_ATLAS : FLOW_GLOW; + if (atlas) return throughWalls ? ATLAS_X : ATLAS; + return throughWalls ? GLOW_X : GLOW; + } + + private static int frameRow(MoteSprite sprite) { + if (frameGeneration != MoteSprite.generation) { + frameGeneration = MoteSprite.generation; + frameRows = 0; + } + if (sprite.tableRow >= 0 && sprite.tableRow < frameRows) return sprite.tableRow; + if (frameRows >= FRAME_ROWS) return -1; + float[] uvs = sprite.uvs(); + int row = frameRows++; + int frames = Math.min(FRAME_COLUMNS, uvs.length / 4); + long base = MemoryUtil.memAddress(FRAME_PIXELS) + (long) row * FRAME_COLUMNS * 16; + for (int i = 0; i < frames * 4; i++) MemoryUtil.memPutFloat(base + i * 4L, uvs[i]); + sprite.tableRow = row; + framesDirty = true; + return row; + } + + static long write(int motion, double x, double y, double z, double ax, double ay, double az, double start, float life, float drag, float gravity, + float size, float alpha, int rgb, int curve, int flags, float roll, float rollSpeed, float e0, float e1, float e2, float e3, + MoteLook look, boolean throughWalls) { + boolean stream = motion == FLOW; + var pool = pool(look, throughWalls, stream); + float rectA = 0, rectB = 0, rectC = 1, rectD = 1; + var sprite = look.sprite(); + if (sprite != null) { + int frames = sprite.frames(); + if (frames == 0) return -1; + if (look.animated() && frames > 1) { + int row = frameRow(sprite); + if (row < 0) return -1; + flags |= ANIMATED; + rectA = row; + rectB = frames; + } else { + float[] uvs = sprite.uvs(); + int f = frames == 1 ? 0 : RANDOM.nextInt(frames); + rectA = uvs[f * 4]; + rectB = uvs[f * 4 + 1]; + rectC = uvs[f * 4 + 2]; + rectD = uvs[f * 4 + 3]; + } + } + long a = pool.slot(start, start + life); + if (a < 0) return -1; + double hx = Math.floor(x / 1024) * 1024, hy = Math.floor(y / 1024) * 1024, hz = Math.floor(z / 1024) * 1024; + MemoryUtil.memPutFloat(a, (float) (x - hx)); + MemoryUtil.memPutFloat(a + 4, (float) (y - hy)); + MemoryUtil.memPutFloat(a + 8, (float) (z - hz)); + MemoryUtil.memPutFloat(a + 12, stream ? 0 : rel(start)); + MemoryUtil.memPutFloat(a + 16, (float) hx); + MemoryUtil.memPutFloat(a + 20, (float) hy); + MemoryUtil.memPutFloat(a + 24, (float) hz); + MemoryUtil.memPutFloat(a + 28, life); + MemoryUtil.memPutFloat(a + 32, (float) ax); + MemoryUtil.memPutFloat(a + 36, (float) ay); + MemoryUtil.memPutFloat(a + 40, (float) az); + MemoryUtil.memPutFloat(a + 44, motion); + MemoryUtil.memPutFloat(a + 48, drag); + MemoryUtil.memPutFloat(a + 52, gravity); + MemoryUtil.memPutFloat(a + 56, size); + MemoryUtil.memPutFloat(a + 60, alpha); + MemoryUtil.memPutFloat(a + 64, (rgb >> 16 & 0xFF) / 255F); + MemoryUtil.memPutFloat(a + 68, (rgb >> 8 & 0xFF) / 255F); + MemoryUtil.memPutFloat(a + 72, (rgb & 0xFF) / 255F); + MemoryUtil.memPutFloat(a + 76, sprite == null ? look.core() : 0); + MemoryUtil.memPutFloat(a + 80, rectA); + MemoryUtil.memPutFloat(a + 84, rectB); + MemoryUtil.memPutFloat(a + 88, rectC); + MemoryUtil.memPutFloat(a + 92, rectD); + MemoryUtil.memPutFloat(a + 96, curve); + MemoryUtil.memPutFloat(a + 100, flags); + MemoryUtil.memPutFloat(a + 104, roll); + MemoryUtil.memPutFloat(a + 108, rollSpeed); + MemoryUtil.memPutFloat(a + 112, e0); + MemoryUtil.memPutFloat(a + 116, e1); + MemoryUtil.memPutFloat(a + 120, e2); + MemoryUtil.memPutFloat(a + 124, e3); + return a; + } + + private static void upload(Pool pool) { + if (pool.buffer == -1) { + pool.buffer = GlStateManager._glGenBuffers(); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, pool.buffer); + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, (long) pool.capacity * RECORD_BYTES, GL15.GL_DYNAMIC_DRAW); + } else { + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, pool.buffer); + } + int from, to; + if (pool.stream) { + from = 0; + to = pool.count - 1; + } else { + from = pool.dirtyMin; + to = pool.dirtyMax; + pool.dirtyMin = Integer.MAX_VALUE; + pool.dirtyMax = -1; + } + if (to < from) return; + pool.mirror.position(from * RECORD_BYTES); + pool.mirror.limit((to + 1) * RECORD_BYTES); + GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, (long) from * RECORD_BYTES, pool.mirror); + pool.mirror.clear(); + } + + private static void uploadFrames() { + if (frameTexture == -1) { + frameTexture = GlStateManager._genTexture(); + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(frameTexture); + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + framesDirty = true; + } + if (!framesDirty) return; + framesDirty = false; + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(frameTexture); + GlStateManager._pixelStore(GL11.GL_UNPACK_ROW_LENGTH, 0); + GlStateManager._pixelStore(GL11.GL_UNPACK_SKIP_ROWS, 0); + GlStateManager._pixelStore(GL11.GL_UNPACK_SKIP_PIXELS, 0); + GlStateManager._pixelStore(GL11.GL_UNPACK_ALIGNMENT, 4); + FRAME_PIXELS.clear(); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_RGBA32F, FRAME_COLUMNS, FRAME_ROWS, 0, GL11.GL_RGBA, GL11.GL_FLOAT, FRAME_PIXELS); + } + + private static boolean active(Pool pool, double now) { + if (pool.stream) return pool.count > 0; + if (pool.highWater == 0) return false; + if (pool.maxEnd <= now) { + pool.clear(); + return false; + } + pool.trim(now); + return pool.highWater > 0; + } + + private static void capture(EffectQuadBuffer output, int instances) { + int vertices = instances * 4; + output.reserve(vertices); + GL30.glBindBufferRange(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, output.buffer, 0, (long) vertices * EffectQuadBuffer.VERTEX_BYTES); + GL30.glBeginTransformFeedback(GL11.GL_POINTS); + GL31.glDrawArraysInstanced(GL11.GL_POINTS, 0, 4, instances); + GL30.glEndTransformFeedback(); + output.vertices = vertices; + } + + private static void pointPool(Pool pool) { + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, pool.buffer); + for (int i = 0; i < program.ring.length; i++) { + int location = program.ring[i]; + if (location < 0) continue; + GL20.glEnableVertexAttribArray(location); + GL20.glVertexAttribPointer(location, 4, GL11.GL_FLOAT, false, RECORD_BYTES, i * 16L); + GL33.glVertexAttribDivisor(location, 1); + } + } + + static void flush(double frameTime, Camera camera) { + double now = frameTime; + boolean any = false; + for (var pool : POOLS) any |= active(pool, now); + if (!any) { + lastDrawn = 0; + return; + } + if (!available()) { + lastDrawn = 0; + for (var pool : POOLS) { + if (!active(pool, now)) continue; + ParticleGeometry.generate(pool, now, epoch, camera, FRAME_PIXELS, FRAME_COLUMNS); + present(pool); + lastDrawn += pool.out.vertices / 4; + } + return; + } + var cam = camera.position(); + double hx = Math.floor(cam.x / 1024) * 1024, hy = Math.floor(cam.y / 1024) * 1024, hz = Math.floor(cam.z / 1024) * 1024; + var left = new Vector3f(-1, 0, 0).rotate(camera.rotation()); + var up = new Vector3f(0, 1, 0).rotate(camera.rotation()); + uploadFrames(); + if (simulateVao == -1) simulateVao = GlStateManager._glGenVertexArrays(); + GlStateManager._glBindVertexArray(simulateVao); + GlStateManager._glUseProgram(program.id); + GL20.glUniform1f(program.uniform("Now"), Double.isNaN(epoch) ? 0 : (float) (now - epoch)); + GL20.glUniform3f(program.uniform("CamHi"), (float) hx, (float) hy, (float) hz); + GL20.glUniform3f(program.uniform("CamLo"), (float) (cam.x - hx), (float) (cam.y - hy), (float) (cam.z - hz)); + GL20.glUniform3f(program.uniform("CameraLeft"), left.x(), left.y(), left.z()); + GL20.glUniform3f(program.uniform("CameraUp"), up.x(), up.y(), up.z()); + GL20.glUniform1f(program.uniform("CullDistance"), CULL); + GL20.glUniform1i(program.uniform("SpriteFrames"), 0); + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(frameTexture); + int corePass = program.uniform("CorePass"); + int premultiply = program.uniform("Premultiply"); + GL11.glEnable(GL30.GL_RASTERIZER_DISCARD); + int drawn = 0; + for (var pool : POOLS) { + pool.out.vertices = 0; + pool.coreOut.vertices = 0; + if (!active(pool, now)) continue; + upload(pool); + int instances = pool.stream ? pool.count : pool.highWater; + drawn += instances; + pointPool(pool); + GL20.glUniform1i(premultiply, pool.atlas ? 0 : 1); + GL20.glUniform1i(corePass, 0); + capture(pool.out, instances); + if (!pool.atlas) { + GL20.glUniform1i(corePass, 1); + capture(pool.coreOut, instances); + } + } + GL11.glDisable(GL30.GL_RASTERIZER_DISCARD); + GL30.glBindBufferBase(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0); + GlStateManager._glUseProgram(0); + GlStateManager._glBindVertexArray(0); + lastDrawn = drawn; + for (var pool : POOLS) present(pool); + } + + private static void present(Pool pool) { + if (pool.atlas) { + pool.out.draw(EffectRenderPipelines.atlas(pool.throughWalls), TextureAtlas.LOCATION_PARTICLES); + } else { + pool.out.draw(EffectRenderPipelines.glow(pool.throughWalls), EffectRenderPipelines.MOTE_TEXTURE); + pool.coreOut.draw(EffectRenderPipelines.glow(pool.throughWalls), EffectRenderPipelines.WHITE_TEXTURE); + } + } + + static void reload() { + for (var pool : POOLS) { + pool.out.close(); + pool.coreOut.close(); + if (pool.buffer != -1) GlStateManager._glDeleteBuffers(pool.buffer); + pool.buffer = -1; + } + if (frameTexture != -1) GlStateManager._deleteTexture(frameTexture); + if (simulateVao != -1) GL30.glDeleteVertexArrays(simulateVao); + if (program != null) GL20.glDeleteProgram(program.id); + frameTexture = simulateVao = programState = -1; + program = null; + ParticleGeometry.release(); + clear(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/MoteSprite.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/MoteSprite.java new file mode 100644 index 0000000..4161b6e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/MoteSprite.java @@ -0,0 +1,66 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.particle.SpriteSet; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +/** + * 从粒子图集读取并缓存各帧的 UV,资源重载后重新解析。 + */ +public final class MoteSprite { + + /** 最多从精灵集合取样的帧数。 */ + public static final int MAX_FRAMES = 64; + + static int generation; + private final SpriteSet set; + private int seen = -1; + private float[] uvs = new float[0]; + private int frames; + int tableRow = -1; + + private MoteSprite(SpriteSet set) { + this.set = set; + } + + /** + * 包装粒子工厂收到的精灵集合。首次绘制时才读取 UV。 + * + * @param set 粒子图集的精灵集合,首次生成光点前须完成原版绑定 + * @return 可在多个光点样式中复用的精灵序列 + */ + public static MoteSprite of(SpriteSet set) { + return new MoteSprite(set); + } + + private void resolve() { + if (seen == generation) return; + var list = new ObjectArrayList(); + for (int i = 0; i < MAX_FRAMES; i++) { + TextureAtlasSprite s = set.get(i, MAX_FRAMES - 1); + if (!list.contains(s)) list.add(s); + } + frames = list.size(); + uvs = new float[frames * 4]; + for (int i = 0; i < frames; i++) { + var s = list.get(i); + uvs[i * 4] = s.getU0(); + uvs[i * 4 + 1] = s.getV0(); + uvs[i * 4 + 2] = s.getU1(); + uvs[i * 4 + 3] = s.getV1(); + } + tableRow = -1; + seen = generation; + } + + int frames() { + resolve(); + return frames; + } + + float[] uvs() { + resolve(); + return uvs; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEffects.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEffects.java new file mode 100644 index 0000000..c122e8d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEffects.java @@ -0,0 +1,114 @@ +package com.modularmc.mmclutils.client.render.effect; + +import org.jspecify.annotations.Nullable; + +/** + * 在客户端提交带阻力和重力的光点,或提交向指定位置移动的光点。 + * 在客户端渲染线程调用。粒子工厂可以传入自己的精灵,由批量管线统一计算和绘制。 + * 超出批次容量或没有客户端世界时跳过生成。 + */ +public final class ParticleEffects { + + /** 光点的边长随寿命线性缩小。 */ + public static final int SHRINK = GpuParticleRenderer.SHRINK; + /** 在寿命中点达到最大边长,两端收缩到零。 */ + public static final int PULSE = GpuParticleRenderer.PULSE_SIZE; + /** 整个寿命使用固定边长。 */ + public static final int CONSTANT = GpuParticleRenderer.CONSTANT; + /** 使光点的亮度或不透明度随寿命线性衰减。 */ + public static final int FADE = 1; + /** 跳过场景深度测试,可与 {@link #FADE} 按位组合。 */ + public static final int THROUGH_WALLS = 2; + /** 原版粒子发射器的相机距离上限,单位为方块。 */ + public static final double SPAWN_DISTANCE = 64; + + private ParticleEffects() {} + + /** + * 发射受阻力和重力影响的光点。寿命、边长或亮度非正时直接返回。 + * + * @param x 起点世界坐标 X + * @param y 起点世界坐标 Y + * @param z 起点世界坐标 Z + * @param vx X 轴初速度,单位为方块每 Tick + * @param vy Y 轴初速度,单位为方块每 Tick + * @param vz Z 轴初速度,单位为方块每 Tick + * @param drag 每 Tick 的速度保留比例,范围为 0~1 + * @param gravity 竖直向下加速度,单位为方块每 Tick 的平方 + * @param life 寿命,单位为 Tick + * @param size 基础边长,单位为方块 + * @param sizeCurve {@link #SHRINK}、{@link #PULSE} 或 {@link #CONSTANT} + * @param rgb 打包在低 24 位的 RGB + * @param alpha 亮度或不透明度,范围为 0~1 + * @param flags 由 {@link #FADE} 与 {@link #THROUGH_WALLS} 组合的位掩码 + * @param look 光点外观 + */ + public static void spawn(double x, double y, double z, double vx, double vy, double vz, float drag, float gravity, float life, float size, int sizeCurve, + int rgb, float alpha, int flags, MoteLook look) { + if (life <= 0 || size <= 0 || alpha <= 0) return; + double now = EffectRenderer.now(); + if (Double.isNaN(now)) return; + GpuParticleRenderer.write(GpuParticleRenderer.BALLISTIC, x, y, z, vx, vy, vz, now, life, drag, gravity, size, alpha, rgb, sizeCurve, flags & FADE, 0, look.rollSpeed(), 0, 0, + 0, 0, look, (flags & THROUGH_WALLS) != 0); + } + + /** + * 生成从起点匀速滑向终点的光点,滑行时间等于寿命。 + * + * @param x0 起点世界坐标 X + * @param y0 起点世界坐标 Y + * @param z0 起点世界坐标 Z + * @param x1 终点世界坐标 X + * @param y1 终点世界坐标 Y + * @param z1 终点世界坐标 Z + * @param life 寿命,单位为 Tick + * @param size 基础边长,单位为方块 + * @param sizeCurve {@link #SHRINK}、{@link #PULSE} 或 {@link #CONSTANT} + * @param rgb 打包在低 24 位的 RGB + * @param alpha 亮度或不透明度,范围为 0~1 + * @param flags 由 {@link #FADE} 与 {@link #THROUGH_WALLS} 组合的位掩码 + * @param look 光点外观 + */ + public static void slide(double x0, double y0, double z0, double x1, double y1, double z1, float life, float size, int sizeCurve, int rgb, float alpha, + int flags, MoteLook look) { + if (life <= 0 || size <= 0 || alpha <= 0) return; + double now = EffectRenderer.now(); + if (Double.isNaN(now)) return; + GpuParticleRenderer.write(GpuParticleRenderer.SLIDE, x0, y0, z0, x1 - x0, y1 - y0, z1 - z0, now, life, 1, 0, size, alpha, rgb, sizeCurve, flags & FADE, 0, look.rollSpeed(), + 0, 0, 0, 0, look, (flags & THROUGH_WALLS) != 0); + } + + /** + * 光点样式可选择带亮芯的像素光晕,或由调用方提供的粒子精灵。 + * + * @param sprite 粒子图集精灵,空值表示使用内置光晕 + * @param animated 是否在寿命内顺序播放各帧 + * @param rollSpeed 绕朝向相机的轴旋转的速度,单位为弧度每 Tick + * @param core 内置光晕亮芯相对光点的边长倍率,非正值时省略亮芯 + */ + public record MoteLook(@Nullable MoteSprite sprite, boolean animated, float rollSpeed, float core) { + + /** 默认光晕样式,亮芯边长为光点边长的 30%。 */ + public static final MoteLook GLOW = new MoteLook(null, false, 0, 0.3F); + + /** 使用内置光晕与给定亮芯边长倍率。 */ + public static MoteLook glow(float core) { + return new MoteLook(null, false, 0, core); + } + + /** 从精灵集合选定一帧,在光点寿命内保留该帧。 */ + public static MoteLook sprite(MoteSprite sprite) { + return new MoteLook(sprite, false, 0, 0); + } + + /** 在光点寿命内顺序播放精灵帧。 */ + public static MoteLook animated(MoteSprite sprite) { + return new MoteLook(sprite, true, 0, 0); + } + + /** 从精灵集合选定一帧并按指定角速度旋转,单位为弧度每 Tick。 */ + public static MoteLook spinning(MoteSprite sprite, float rollSpeed) { + return new MoteLook(sprite, false, rollSpeed, 0); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java new file mode 100644 index 0000000..d1d747e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java @@ -0,0 +1,114 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.particles.ParticleOptions; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +/** + * 使用原版粒子工厂发射一次性高斯爆散,或在客户端 Tick 中持续发射粒子。 + * 须在客户端线程调用。生成时按相机距离裁剪,世界切换时清除仍在运行的发射器。 + */ +public final class ParticleEmitters { + + static final int MAX_EMITTERS = 1024; + + private static final class Emitter { + + ParticleOptions particle; + double x, y, z, dx, dy, dz, speed; + int ticks, chance; + } + + private static final ObjectArrayList ACTIVE = new ObjectArrayList<>(); + private static final ObjectArrayList POOL = new ObjectArrayList<>(); + + private ParticleEmitters() {} + + /** + * 立即使用原版工厂发射粒子。 + * + * @param particle 原版粒子选项 + * @param x 中心世界坐标 X + * @param y 中心世界坐标 Y + * @param z 中心世界坐标 Z + * @param count 爆散的粒子数。零时沿指定方向生成一个粒子 + * @param dx X 轴位置偏移的标准差,数量为零时是方向 X + * @param dy Y 轴位置偏移的标准差,数量为零时是方向 Y + * @param dz Z 轴位置偏移的标准差,数量为零时是方向 Z + * @param speed 各轴速度的标准差,数量为零时是方向速度倍率 + */ + public static void burst(ParticleOptions particle, double x, double y, double z, int count, double dx, double dy, double dz, double speed) { + var level = Minecraft.getInstance().level; + if (level != null) spawn(level, particle, x, y, z, count, dx, dy, dz, speed); + } + + /** + * 从后续的客户端 Tick 开始,每 Tick 按概率发射一个粒子。 + * 持续时间耗尽后回收发射器,达到并发发射器上限时跳过本次登记。 + * + * @param particle 原版粒子选项 + * @param x 中心世界坐标 X + * @param y 中心世界坐标 Y + * @param z 中心世界坐标 Z + * @param ticks 持续 Tick 数,非正值时直接返回 + * @param chance 每 Tick 以该值的倒数为发射概率。小于 1 时按 1 处理 + * @param dx X 轴位置偏移的标准差,单位为方块 + * @param dy Y 轴位置偏移的标准差,单位为方块 + * @param dz Z 轴位置偏移的标准差,单位为方块 + * @param speed 各轴速度的标准差,单位为方块每 Tick + */ + public static void emitter(ParticleOptions particle, double x, double y, double z, int ticks, int chance, double dx, double dy, double dz, + double speed) { + if (ticks <= 0 || ACTIVE.size() >= MAX_EMITTERS) return; + var e = POOL.isEmpty() ? new Emitter() : POOL.remove(POOL.size() - 1); + e.particle = particle; + e.x = x; + e.y = y; + e.z = z; + e.dx = dx; + e.dy = dy; + e.dz = dz; + e.speed = speed; + e.ticks = ticks; + e.chance = Math.max(1, chance); + ACTIVE.add(e); + } + + static void tick(ClientLevel level) { + for (int i = ACTIVE.size() - 1; i >= 0; i--) { + var e = ACTIVE.get(i); + if (e.chance == 1 || level.getRandom().nextInt(e.chance) == 0) spawn(level, e.particle, e.x, e.y, e.z, 1, e.dx, e.dy, e.dz, e.speed); + if (--e.ticks <= 0) remove(i); + } + } + + static void clear() { + for (int i = ACTIVE.size() - 1; i >= 0; i--) remove(i); + } + + private static void remove(int i) { + int last = ACTIVE.size() - 1; + var e = ACTIVE.get(i); + ACTIVE.set(i, ACTIVE.get(last)); + ACTIVE.remove(last); + e.particle = null; + POOL.add(e); + } + + private static void spawn(ClientLevel level, ParticleOptions particle, double x, double y, double z, int count, double dx, double dy, double dz, + double speed) { + var eye = Minecraft.getInstance().gameRenderer.getMainCamera().position(); + if (eye.distanceToSqr(x, y, z) > ParticleEffects.SPAWN_DISTANCE * ParticleEffects.SPAWN_DISTANCE) return; + var random = level.getRandom(); + if (count == 0) { + level.addParticle(particle, true, false, x, y, z, speed * dx, speed * dy, speed * dz); + return; + } + for (int i = 0; i < count; i++) { + level.addParticle(particle, true, false, x + random.nextGaussian() * dx, y + random.nextGaussian() * dy, z + random.nextGaussian() * dz, + random.nextGaussian() * speed, random.nextGaussian() * speed, random.nextGaussian() * speed); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java new file mode 100644 index 0000000..8505a8a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java @@ -0,0 +1,140 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.Camera; + +import org.joml.Vector3f; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +/** 在 CPU 上计算与光点着色器一致的轨迹、大小和颜色。 */ +final class ParticleGeometry { + + private static final int BALLISTIC = 0, SLIDE = 1, PULSE = 2, BURST = 3, FLOW = 4; + private static final int FADE = 1, ANIMATED = 4; + private static final Vector3f LEFT = new Vector3f(); + private static final Vector3f UP = new Vector3f(); + private static final EffectVertices HALOS = new EffectVertices(); + private static final EffectVertices CORES = new EffectVertices(); + + private ParticleGeometry() {} + + static void release() { + HALOS.release(); + CORES.release(); + } + + static void generate(GpuParticleRenderer.Pool pool, double now, double epoch, Camera camera, ByteBuffer frames, int frameColumns) { + int size = pool.stream ? pool.count : pool.highWater; + var eye = camera.position(); + LEFT.set(-1, 0, 0).rotate(camera.rotation()); + UP.set(0, 1, 0).rotate(camera.rotation()); + HALOS.begin(size); + CORES.begin(pool.atlas ? 0 : size); + for (int i = 0; i < size; i++) { + long base = pool.address + (long) i * 128; + float life = value(base, 7); + float age = (float) (now - epoch - value(base, 3)); + int mode = (int) value(base, 11); + int flags = (int) value(base, 25); + float fraction = age / life; + float alpha = value(base, 15); + float x = (float) (value(base, 0) + (value(base, 4) - eye.x)); + float y = (float) (value(base, 1) + (value(base, 5) - eye.y)); + float z = (float) (value(base, 2) + (value(base, 6) - eye.z)); + float vx = value(base, 8), vy = value(base, 9), vz = value(base, 10); + float scale = 1, progress = fraction, rise = 0; + if (mode == FLOW) { + float time = (float) (now - epoch); + float period = value(base, 28), travel = value(base, 29), phase = value(base, 30); + float slot = (float) Math.floor((time + phase) / period) - value(base, 31); + progress = (time - (slot * period - phase)) / travel; + if (progress < 0 || progress >= 1) continue; + float seed = value(base, 26) * 131 + slot * 0.6180339f; + float jitter = value(base, 13); + x += jitter * lerp(hash(seed + 1) - .5f, hash(seed + 4) - .5f, progress); + y += jitter * lerp(hash(seed + 2) - .5f, hash(seed + 5) - .5f, progress); + z += jitter * lerp(hash(seed + 3) - .5f, hash(seed + 6) - .5f, progress); + scale += value(base, 12) * hash(seed + 7); + alpha *= Math.min(1, Math.min(progress, 1 - progress) / .18f); + fraction = .5f; + } else { + if (age < 0 || fraction >= 1) continue; + switch (mode) { + case BALLISTIC -> { + float drag = value(base, 12); + double fall; + if (Math.abs(1 - drag) < .000001) { + progress = age; + fall = age * (age + 1) * .5; + } else { + progress = (float) ((1 - Math.pow(drag, age)) / (1 - drag)); + fall = (age - drag * progress) / (1 - drag); + } + rise = (float) (-value(base, 13) * fall); + } + case PULSE -> { + float delay = value(base, 28), length = value(base, 30), duration = value(base, 31); + float time = age - delay; + if (time < 0 || time > duration) continue; + float lag = Math.max(.01f, value(base, 13)); + float speed = value(base, 12); + progress = length > .0001f ? (float) Math.min(1, speed * (time - lag * (1 - Math.exp(-time / lag))) / length) : 0; + scale = value(base, 29); + } + case BURST -> { + progress = 1 - (1 - fraction) * (1 - fraction); + rise = value(base, 13) * age; + alpha *= Math.min(1, age / 1.5f); + } + case SLIDE -> {} + default -> throw new IllegalStateException("未知光点轨迹:" + mode); + } + if ((flags & FADE) != 0) alpha *= 1 - fraction; + } + x += vx * progress; + y += vy * progress + rise; + z += vz * progress; + if (alpha <= .004f || x * x + y * y + z * z > GpuParticleRenderer.CULL * GpuParticleRenderer.CULL) continue; + float curve = switch ((int) value(base, 24)) { + case 0 -> 1 - fraction; + case 1 -> 1 - Math.abs(2 * fraction - 1); + default -> 1; + }; + float width = value(base, 14) * scale * curve; + float red = value(base, 16), green = value(base, 17), blue = value(base, 18); + float angle = mode == FLOW ? 0 : value(base, 26) + value(base, 27) * age; + float u0 = value(base, 20), v0 = value(base, 21), u1 = value(base, 22), v1 = value(base, 23); + if ((flags & ANIMATED) != 0) { + int frame = (int) Math.min(v0 - 1, age * (v0 - 1) / life); + int offset = ((int) u0 * frameColumns + frame) * 16; + u0 = frames.getFloat(offset); + v0 = frames.getFloat(offset + 4); + u1 = frames.getFloat(offset + 8); + v1 = frames.getFloat(offset + 12); + } + float brightness = pool.atlas ? 1 : alpha; + HALOS.facing(x, y, z, LEFT, UP, width, angle, red * brightness, green * brightness, blue * brightness, alpha, u0, v0, u1, v1); + float core = value(base, 19); + if (!pool.atlas && core > 0) { + CORES.facing(x, y, z, LEFT, UP, width * core, angle, lerp(red, 1, .55f) * alpha, + lerp(green, 1, .55f) * alpha, lerp(blue, 1, .55f) * alpha, alpha, 0, 0, 1, 1); + } + } + HALOS.upload(pool.out); + CORES.upload(pool.coreOut); + } + + private static float value(long base, int index) { + return MemoryUtil.memGetFloat(base + (long) index * Float.BYTES); + } + + private static float lerp(float a, float b, float t) { + return a + (b - a) * t; + } + + private static float hash(float value) { + double product = Math.sin(value) * 43758.5453123; + return (float) (product - Math.floor(product)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleRing.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleRing.java new file mode 100644 index 0000000..8aabe8b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleRing.java @@ -0,0 +1,202 @@ +package com.modularmc.mmclutils.client.render.effect; + +import org.joml.Matrix3f; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.util.SplittableRandom; + +/** + * 固定随机种子的环粒子数据,可用同一个实例在多个位置绘制。 + * 实例保存粒子运动参数,渲染器负责缓存并释放上传到设备的数据。 + */ +public final class ParticleRing { + + /** 基础粒子边长,单位为方块。 */ + public static final float PIXEL = 1F / 16F; + /** 变换反馈路径中粒子数据纹理每行的像素数。 */ + public static final int DATA_WIDTH = 1024; + + private final float majorRadius; + private final float half; + private final int count; + private final float[] phase; + private final float[] orbit; + private final float[] driftFrequencyU; + private final float[] driftFrequencyV; + private final float[] driftPhaseU; + private final float[] driftPhaseV; + private final float[] spin; + private final float[] spinPhase; + private final float[] amplitudeU; + private final float[] amplitudeV; + private final float[] axisX; + private final float[] axisY; + private final float[] axisZ; + private final int[] tone; + + /** + * 根据固定种子分布粒子。粒子运动参数生成后可重复使用。 + * + * @param majorRadius 环中心到轨道中线的半径,须为有限正数 + * @param tubeRadius 轨道横截面半径,须为有限非负数 + * @param count 粒子数。零表示只绘制光带 + * @param minSpeed 最小轨道线速度,单位为方块每 Tick + * @param maxSpeed 最大轨道线速度,单位为方块每 Tick + * @param seed 控制分布的随机种子 + * @throws IllegalArgumentException 半径、粒子数或速度范围无效 + */ + public ParticleRing(float majorRadius, float tubeRadius, int count, float minSpeed, float maxSpeed, long seed) { + if (!(majorRadius > 0 && Float.isFinite(majorRadius) && tubeRadius >= 0 && Float.isFinite(tubeRadius))) { + throw new IllegalArgumentException("环的半径超出有效范围"); + } + if (count < 0 || !Float.isFinite(minSpeed) || !Float.isFinite(maxSpeed) || minSpeed > maxSpeed) { + throw new IllegalArgumentException("环的粒子数或速度范围无效"); + } + this.majorRadius = majorRadius; + this.half = PIXEL / 2; + this.count = count; + phase = new float[count]; + orbit = new float[count]; + driftFrequencyU = new float[count]; + driftFrequencyV = new float[count]; + driftPhaseU = new float[count]; + driftPhaseV = new float[count]; + spin = new float[count]; + spinPhase = new float[count]; + amplitudeU = new float[count]; + amplitudeV = new float[count]; + axisX = new float[count]; + axisY = new float[count]; + axisZ = new float[count]; + tone = new int[count]; + var random = new SplittableRandom(seed); + int[] order = new int[count]; + for (int i = 0; i < count; i++) order[i] = i; + for (int i = count - 1; i > 0; i--) { + int j = random.nextInt(i + 1); + int swap = order[i]; + order[i] = order[j]; + order[j] = swap; + } + float reach = Math.max(0, tubeRadius - half * 1.8F); + for (int k = 0; k < count; k++) { + int i = order[k]; + phase[i] = (float) ((k + random.nextDouble()) / count * Math.PI * 2); + orbit[i] = (float) ((minSpeed + (maxSpeed - minSpeed) * random.nextDouble()) / majorRadius); + driftFrequencyU[i] = (float) (0.03 + 0.07 * random.nextDouble()); + driftFrequencyV[i] = (float) (0.03 + 0.07 * random.nextDouble()); + driftPhaseU[i] = (float) (random.nextDouble() * Math.PI * 2); + driftPhaseV[i] = (float) (random.nextDouble() * Math.PI * 2); + double radius = reach * Math.sqrt(random.nextDouble()); + double angle = random.nextDouble() * Math.PI / 2; + amplitudeU[i] = (float) (radius * Math.cos(angle)); + amplitudeV[i] = (float) (radius * Math.sin(angle)); + spin[i] = (float) ((0.06 + 0.2 * random.nextDouble()) * (random.nextBoolean() ? 1 : -1)); + spinPhase[i] = (float) (random.nextDouble() * Math.PI * 2); + double z = random.nextDouble() * 2 - 1, azimuth = random.nextDouble() * Math.PI * 2, planar = Math.sqrt(1 - z * z); + axisX[i] = (float) (planar * Math.cos(azimuth)); + axisY[i] = (float) (planar * Math.sin(azimuth)); + axisZ[i] = (float) z; + tone[i] = random.nextInt(EffectPalette.SIZE); + } + } + + /** 返回环包含的粒子数量。 */ + public int count() { + return count; + } + + /** 返回轨道半径,单位为方块。 */ + public float majorRadius() { + return majorRadius; + } + + float phase(int index) { + return phase[index]; + } + + float orbit(int index) { + return orbit[index]; + } + + void spin(int index, float time, Matrix3f rotation) { + rotation.rotation(spin[index] * time + spinPhase[index], axisX[index], axisY[index], axisZ[index]); + } + + float radial(int index, double time) { + return majorRadius + amplitudeU[index] * (float) Math.sin(driftPhaseU[index] + time * driftFrequencyU[index]); + } + + float vertical(int index, double time) { + return amplitudeV[index] * (float) Math.sin(driftPhaseV[index] + time * driftFrequencyV[index]); + } + + int tone(int index) { + return tone[index]; + } + + float half() { + return half; + } + + int dataRows() { + return Math.ceilDiv(count, DATA_WIDTH / 4); + } + + ByteBuffer createData() { + var data = MemoryUtil.memCalloc(Math.multiplyExact(dataRows(), DATA_WIDTH * 4 * Float.BYTES)); + for (int i = 0; i < count; i++) { + data.putFloat(phase[i]).putFloat(orbit[i]).putFloat(driftFrequencyU[i]).putFloat(driftFrequencyV[i]); + data.putFloat(driftPhaseU[i]).putFloat(driftPhaseV[i]).putFloat(amplitudeU[i]).putFloat(amplitudeV[i]); + data.putFloat(spin[i]).putFloat(spinPhase[i]).putFloat(tone[i]).putFloat(0); + data.putFloat(axisX[i]).putFloat(axisY[i]).putFloat(axisZ[i]).putFloat(0); + } + data.clear(); + return data; + } + + /** + * 环效果中精灵、光晕与亮芯各自的宽度和强度。 + * + * @param spriteScale 发光精灵相对基础像素的半宽倍率 + * @param spriteStrength 精灵强度,范围为 0~255 + * @param hazeWidth 光晕带半宽,单位为方块 + * @param hazeStrength 光晕带强度,范围为 0~255 + * @param coreWidth 亮芯带半宽,单位为方块 + * @param coreStrength 亮芯带强度,范围为 0~255 + */ + public record RingStyle(float spriteScale, int spriteStrength, float hazeWidth, int hazeStrength, float coreWidth, int coreStrength) {} + + /** + * 定义闭环或由多条螺旋组成的环轮廓。螺旋沿环轴从原点开始延伸。 + * + * @param strands 螺旋股数,0 表示闭环,最多 192 股 + * @param height 沿环轴的长度,单位为方块 + * @param turns 每股绕轴旋转的圈数,可用符号改变方向 + * @param taper 轴向分布从均匀变化到渐密的比例,范围为 0~0.95 + * @param fadeIn 开头逐渐显现的长度比例,范围为 0~1 + * @param fadeOut 结尾逐渐淡出的长度比例,范围为 0~1 + */ + public record RingShape(int strands, float height, float turns, float taper, float fadeIn, float fadeOut) { + + /** 在垂直于环轴的平面内闭合的环。 */ + public static final RingShape CLOSED = new RingShape(0, 0, 0, 0, 0, 0); + + /** 创建环形轮廓并规范化无螺旋时的各项参数。 */ + public RingShape { + if (strands < 0 || strands > RingRenderer.RIBBON_SEGMENTS) throw new IllegalArgumentException("螺旋股数超出范围"); + if (strands == 0) { + height = turns = taper = fadeIn = fadeOut = 0; + } else if (!Float.isFinite(height) || !Float.isFinite(turns) || height == 0 && turns == 0 || + !(taper >= 0 && taper <= 0.95f && fadeIn >= 0 && fadeIn <= 1 && fadeOut >= 0 && fadeOut <= 1)) { + throw new IllegalArgumentException("螺旋轮廓参数无效"); + } + } + + /** 创建螺旋轮廓,渐密比例取 0~0.95,其余参数遵循 {@link RingShape} 的约定。 */ + public static RingShape helix(int strands, float height, float turns, float taper, float fadeIn, float fadeOut) { + return new RingShape(strands, height, turns, Math.max(0, Math.min(taper, 0.95F)), fadeIn, fadeOut); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java new file mode 100644 index 0000000..7363af2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java @@ -0,0 +1,354 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.model.player.PlayerModel; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.entity.RenderLayerParent; +import net.minecraft.client.renderer.entity.layers.RenderLayer; +import net.minecraft.client.renderer.entity.state.AvatarRenderState; +import net.minecraft.util.ARGB; +import net.minecraft.util.Mth; +import net.minecraft.world.phys.Vec3; +import net.neoforged.neoforge.client.event.EntityRenderersEvent; + +import com.mojang.blaze3d.vertex.PoseStack; +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; +import org.joml.Matrix4f; +import org.joml.Vector3d; +import org.joml.Vector3f; +import org.joml.Vector4f; +import org.jspecify.annotations.Nullable; + +/** + * 采集附着在玩家身体部件上的效果,在半透明粒子之后用场景深度绘制像素片。 + * 回调可以通过当帧模型姿态定位身体部件,并将局部位置转换为世界坐标。 + * 绘制、回调登记和 GPU 资源释放都在客户端渲染线程执行。 + */ +public final class PlayerAttachmentRenderer { + + private static final ObjectArrayList LISTENERS = new ObjectArrayList<>(); + private static final ObjectArrayList PENDING = new ObjectArrayList<>(); + private static final ReferenceOpenHashSet UPLOADED_SHEETS = new ReferenceOpenHashSet<>(); + private static final Vector3f TRANSFORMED_POSITION = new Vector3f(); + private static @Nullable Vec3 cameraOrigin; + private static int count; + + private PlayerAttachmentRenderer() {} + + /** + * 登记一个对所有玩家实体生效的附着回调。相同回调只登记一次。 + * + * @param attachment 模型姿态采集回调 + */ + public static void add(Attachment attachment) { + if (!LISTENERS.contains(attachment)) LISTENERS.add(attachment); + } + + /** + * 移除附着回调。请在附着回调执行之外调用。 + * + * @param attachment 先前登记的回调 + */ + public static void remove(Attachment attachment) { + LISTENERS.remove(attachment); + } + + static void initLayers(EntityRenderersEvent.AddLayers event) { + for (var skin : event.getSkins()) { + var renderer = event.getPlayerRenderer(skin); + if (renderer != null) renderer.addLayer(new Layer(renderer)); + } + } + + static void beginFrame(Vec3 origin) { + clearFrame(); + cameraOrigin = origin; + } + + static void clearFrame() { + for (int i = 0; i < count; i++) PENDING.get(i).sheet = null; + count = 0; + cameraOrigin = null; + } + + static void releaseBuffers() { + for (PixelSheet sheet : UPLOADED_SHEETS) sheet.releaseBuffers(); + UPLOADED_SHEETS.clear(); + } + + static void drawPending() { + try { + for (int i = 0; i < count; i++) { + var draw = PENDING.get(i); + draw.sheet.draw(draw.transform, draw.tint); + } + } finally { + clearFrame(); + } + } + + /** + * 查询当前能否提交玩家附着效果。 + * + * @return 世界帧已开始采集且尚未提交附着绘制时为 {@code true} + */ + public static boolean inLevel() { + return cameraOrigin != null; + } + + /** + * 按像素片自身颜色提交绘制。 + * + * @param sheet 可复用的像素片 + * @param poses 已定位到相应身体部件的姿态栈 + */ + public static void draw(PixelSheet sheet, PoseStack poses) { + draw(sheet, poses, 1, 1, 1); + } + + /** + * 将当前姿态复制到本帧命令中,并在提交时对像素颜色乘以指定染色分量。 + * 应在 {@link Attachment#collect} 中调用。世界帧之外调用时直接返回。 + * + * @param sheet 可复用的像素片 + * @param poses 已定位到相应身体部件的姿态栈 + * @param red 红色倍率 + * @param green 绿色倍率 + * @param blue 蓝色倍率 + */ + public static void draw(PixelSheet sheet, PoseStack poses, float red, float green, float blue) { + if (!inLevel()) return; + if (count == PENDING.size()) PENDING.add(new Draw()); + Draw entry = PENDING.get(count++); + entry.sheet = sheet; + entry.transform.set(poses.last().pose()); + entry.tint.set(red, green, blue, 1); + } + + /** + * 用模型姿态和当帧相机原点,将身体部件上的局部点转换到世界空间。 + * 应在 {@link Attachment#collect} 中用已定位到部件的姿态调用。 + * + * @param poses 含相机相对平移的实体姿态栈 + * @param x 局部 X 坐标,单位为方块 + * @param y 局部 Y 坐标,单位为方块 + * @param z 局部 Z 坐标,单位为方块 + * @param out 接收世界坐标的向量。世界帧之外调用时保留原值 + * @return 是否写入了世界坐标 + */ + public static boolean toWorld(PoseStack poses, float x, float y, float z, Vector3d out) { + Vec3 origin = cameraOrigin; + if (origin == null) return false; + var relative = poses.last().pose().transformPosition(x, y, z, TRANSFORMED_POSITION); + out.set(origin.x + relative.x, origin.y + relative.y, origin.z + relative.z); + return true; + } + + /** + * 在渲染线程上采集玩家附着效果,复用已完成动画的模型姿态。 + * 可以暂时变换姿态栈来定位身体部件,返回前须恢复原有姿态。 + * 模型和姿态栈由原版复用,只能在当次调用中使用。 + */ + @FunctionalInterface + public interface Attachment { + + /** + * 采集单个玩家的附着效果。 + * + * @param state 原版提取的玩家渲染状态 + * @param model 已应用动画的玩家模型 + * @param pose 实体相对相机的姿态栈 + */ + void collect(AvatarRenderState state, PlayerModel model, PoseStack pose); + } + + private static final class Layer extends RenderLayer { + + private Layer(RenderLayerParent parent) { + super(parent); + } + + @Override + public void submit(PoseStack pose, SubmitNodeCollector collector, int light, AvatarRenderState state, + float yaw, float pitch) { + if (!inLevel()) return; + for (int i = 0; i < LISTENERS.size(); i++) LISTENERS.get(i).collect(state, getParentModel(), pose); + } + } + + private static final class Draw { + + private PixelSheet sheet; + private final Matrix4f transform = new Matrix4f(); + private final Vector4f tint = new Vector4f(1); + } + + /** + * 位于局部 XY 平面的不可变发光像素片。位置与边长均以方块为单位。 + * 首次绘制时上传静态几何,可在不同玩家和姿态上复用。 + * 重载资源、退出世界或显式关闭时释放 GPU 缓冲,下次绘制会重新上传。 + */ + public static final class PixelSheet implements AutoCloseable { + + private static final int STRIDE = 4; + private final float[] pixels; + private final float pixel; + private final float halo; + private final float core; + private final EffectQuadBuffer glow = new EffectQuadBuffer(); + private final EffectQuadBuffer center = new EffectQuadBuffer(); + private boolean uploaded; + + private PixelSheet(float[] pixels, float pixel, float halo, float core) { + this.pixels = pixels; + this.pixel = pixel; + this.halo = halo; + this.core = core; + } + + /** + * 创建像素片构建器。光晕边长为 {@code pixel * halo},亮芯边长为 {@code pixel * halo * core}。 + * + * @param pixel 基础像素边长,单位为方块 + * @param halo 光晕相对基础像素的边长倍率 + * @param core 亮芯相对光晕的边长倍率 + * @return 独立的构建器 + */ + public static Builder builder(float pixel, float halo, float core) { + return new Builder(pixel, halo, core); + } + + /** 返回像素数量。 */ + public int count() { + return pixels.length / STRIDE; + } + + /** + * 读取像素中心的局部 X 坐标。 + * + * @param index 像素索引,范围为 0 到 {@link #count()} 减一 + * @return 以方块为单位的 X 坐标 + */ + public float x(int index) { + return pixels[index * STRIDE]; + } + + /** + * 读取像素中心的局部 Y 坐标。 + * + * @param index 像素索引,范围为 0 到 {@link #count()} 减一 + * @return 以方块为单位的 Y 坐标 + */ + public float y(int index) { + return pixels[index * STRIDE + 1]; + } + + /** + * 读取构建时传入的颜色。 + * + * @param index 像素索引,范围为 0 到 {@link #count()} 减一 + * @return 打包在低 24 位的 RGB + */ + public int rgb(int index) { + return Float.floatToRawIntBits(pixels[index * STRIDE + 2]); + } + + /** 返回基础像素边长,单位为方块。 */ + public float pixel() { + return pixel; + } + + private void draw(Matrix4f transform, Vector4f tint) { + if (!uploaded) upload(); + Matrix4f matrix = new Matrix4f(EffectRenderer.modelView()).mul(transform); + glow.draw(EffectRenderPipelines.GLOW, EffectRenderPipelines.MOTE_TEXTURE, matrix, tint); + center.draw(EffectRenderPipelines.GLOW, EffectRenderPipelines.WHITE_TEXTURE, matrix, tint); + } + + private void upload() { + var vertices = new EffectVertices(); + try { + float haloSize = pixel * halo; + upload(vertices, glow, haloSize, 0); + upload(vertices, center, haloSize * core, 0.55f); + UPLOADED_SHEETS.add(this); + uploaded = true; + } catch (RuntimeException | Error exception) { + releaseBuffers(); + throw exception; + } finally { + vertices.release(); + } + } + + private void upload(EffectVertices vertices, EffectQuadBuffer output, float size, float whiten) { + vertices.begin(count()); + float half = size * 0.5f; + for (int i = 0; i < pixels.length; i += STRIDE) { + float x = pixels[i], y = pixels[i + 1]; + int color = Float.floatToRawIntBits(pixels[i + 2]); + float alpha = pixels[i + 3]; + // 加法混合直接累加 RGB,由顶点颜色携带像素亮度。 + float r = Mth.lerp(whiten, ARGB.redFloat(color), 1) * alpha; + float g = Mth.lerp(whiten, ARGB.greenFloat(color), 1) * alpha; + float b = Mth.lerp(whiten, ARGB.blueFloat(color), 1) * alpha; + vertices.writeVertex(x - half, y - half, 0, r, g, b, alpha, 0, 0); + vertices.writeVertex(x - half, y + half, 0, r, g, b, alpha, 0, 1); + vertices.writeVertex(x + half, y + half, 0, r, g, b, alpha, 1, 1); + vertices.writeVertex(x + half, y - half, 0, r, g, b, alpha, 1, 0); + } + vertices.upload(output); + } + + /** 在渲染线程释放已上传的缓冲。CPU 侧像素仍可再次绘制。 */ + @Override + public void close() { + UPLOADED_SHEETS.remove(this); + releaseBuffers(); + } + + private void releaseBuffers() { + glow.close(); + center.close(); + uploaded = false; + } + + /** 按插入顺序累积像素。每次构建均取得独立的像素数据。 */ + public static final class Builder { + + private final FloatArrayList pixels = new FloatArrayList(); + private final float pixel; + private final float halo; + private final float core; + + private Builder(float pixel, float halo, float core) { + this.pixel = pixel; + this.halo = halo; + this.core = core; + } + + /** + * 追加一个像素。 + * + * @param x 局部 X 坐标,单位为方块 + * @param y 局部 Y 坐标,单位为方块 + * @param rgb 低 24 位的 RGB + * @param alpha 介于 0 和 1 之间的像素亮度 + * @return 当前构建器 + */ + public Builder pixel(float x, float y, int rgb, float alpha) { + pixels.add(x); + pixels.add(y); + pixels.add(Float.intBitsToFloat(rgb & 0xFFFFFF)); + pixels.add(alpha); + return this; + } + + /** 复制当前像素数据并构造一张可独立使用的像素片。 */ + public PixelSheet build() { + return new PixelSheet(pixels.toFloatArray(), pixel, halo, core); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/PulseAnimation.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/PulseAnimation.java new file mode 100644 index 0000000..0968831 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/PulseAnimation.java @@ -0,0 +1,73 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.world.phys.Vec3; + +import lombok.Getter; +import lombok.experimental.Accessors; +import org.jspecify.annotations.Nullable; + +/** 从固定起点向外推进的周期脉冲。由同一线程更新和读取,所有时间参数使用同一种单位。 */ +public final class PulseAnimation { + + private final double period; + private final double speed; + private final double maxRadius; + /** 本轮脉冲起点,清空后或首次更新前为空值。 */ + @Getter + @Accessors(fluent = true) + private @Nullable Vec3 origin; + private double startedAt; + private double lastTime; + /** 当前半径,单位为方块。 */ + @Getter + @Accessors(fluent = true) + private double radius; + + /** + * 创建周期脉冲,届期后在下一次更新的位置开始新一轮。 + * + * @param period 两次发射之间的时间 + * @param speed 每单位时间扩张的方块数 + * @param maxRadius 最大半径,单位为方块 + * @throws IllegalArgumentException 有参数为非正数或非有限值 + */ + public PulseAnimation(double period, double speed, double maxRadius) { + if (!(Double.isFinite(period) && period > 0 && Double.isFinite(speed) && speed > 0 && Double.isFinite(maxRadius) && maxRadius > 0)) { + throw new IllegalArgumentException("脉冲周期、速度和半径必须为有限正数"); + } + this.period = period; + this.speed = speed; + this.maxRadius = maxRadius; + } + + /** + * 在当前时间更新脉冲。首次调用、周期届满或时间倒退时重新发射。 + * + * @param time 当前时间,须为有限值 + * @param center 重新发射时采样的世界坐标 + * @return 是否开始新的一轮 + * @throws IllegalArgumentException 时间为非有限值 + */ + public boolean update(double time, Vec3 center) { + if (!Double.isFinite(time)) throw new IllegalArgumentException("脉冲时间须为有限值"); + boolean restarted = origin == null || time < lastTime || time - startedAt >= period; + if (restarted) { + startedAt = time; + origin = center; + } + lastTime = time; + radius = Math.min((time - startedAt) * speed, maxRadius); + return restarted; + } + + /** 返回当前半径的平方,供距离平方比较。 */ + public double radiusSquared() { + return radius * radius; + } + + /** 清空起点与半径,使下一次更新重新发射。 */ + public void clear() { + origin = null; + radius = 0; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java new file mode 100644 index 0000000..57b2784 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java @@ -0,0 +1,185 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.Camera; +import net.minecraft.core.Direction; +import net.minecraft.util.ARGB; +import net.minecraft.util.Mth; + +import org.joml.Matrix3f; +import org.joml.Vector3f; + +import java.util.List; + +/** 在普通顶点路径上按环着色器的规则构造实体、精灵和光带。 */ +final class RingGeometry { + + private static final int[] CORNER_X = { -1, 1, 1, -1 }; + private static final int[] CORNER_Y = { -1, -1, 1, 1 }; + private static final Vector3f LEFT = new Vector3f(); + private static final Vector3f UP = new Vector3f(); + private static final Vector3f CENTER = new Vector3f(); + private static final Matrix3f ROTATION = new Matrix3f(); + private static final Vector3f NORMAL = new Vector3f(); + private static final Vector3f TANGENT = new Vector3f(); + private static final Vector3f BITANGENT = new Vector3f(); + private static final Vector3f A = new Vector3f(); + private static final Vector3f B = new Vector3f(); + private static final Vector3f SIDE_A = new Vector3f(); + private static final Vector3f SIDE_B = new Vector3f(); + private static final EffectVertices VOXELS = new EffectVertices(); + private static final EffectVertices GLOWS = new EffectVertices(); + + private RingGeometry() {} + + static void draw(List commands, int count, Camera camera, EffectQuadBuffer voxels, EffectQuadBuffer glows) { + LEFT.set(-1, 0, 0).rotate(camera.rotation()); + UP.set(0, 1, 0).rotate(camera.rotation()); + int particles = 0; + for (int i = 0; i < count; i++) particles = Math.addExact(particles, commands.get(i).ring.count()); + VOXELS.begin(Math.multiplyExact(particles, 3)); + GLOWS.begin(Math.addExact(particles, Math.multiplyExact(count, 2 * RingRenderer.RIBBON_SEGMENTS))); + for (int i = 0; i < count; i++) { + var command = commands.get(i); + particles(command); + float strength = command.intensity * EffectRenderer.breathe(command); + ribbon(command, command.style.hazeWidth(), (int) (command.style.hazeStrength() * strength)); + ribbon(command, command.style.coreWidth(), (int) (command.style.coreStrength() * strength)); + } + VOXELS.upload(voxels); + GLOWS.upload(glows); + voxels.draw(EffectRenderPipelines.VOXEL, EffectRenderPipelines.WHITE_TEXTURE); + glows.draw(EffectRenderPipelines.GLOW, EffectRenderPipelines.GLOW_TEXTURE); + } + + private static void particles(EffectRenderer.RingCommand command) { + ParticleRing ring = command.ring; + ParticleRing.RingShape shape = command.shape; + int strands = shape.strands(); + float radius = ring.majorRadius(); + float length = (float) Math.hypot(shape.turns() * Mth.TWO_PI * radius, shape.height()); + float time = (float) command.time; + float half = ring.half() * command.scale; + for (int i = 0; i < ring.count(); i++) { + float phase = ring.phase(i); + float orbit = ring.orbit(i); + float radial = ring.radial(i, time); + float height = ring.vertical(i, time); + float angle = phase + orbit * time; + float fade = 1; + if (strands != 0) { + float slot = phase / Mth.TWO_PI * strands; + int strand = Math.min(Mth.floor(slot), strands - 1); + float sweep = Mth.frac(slot - strand + orbit * radius / length * time); + float along = helixAlong(shape, sweep); + angle = Mth.TWO_PI * (strand / (float) strands + shape.turns() * sweep); + height += along * shape.height(); + fade = helixFade(shape, along); + } + if (fade == 0) continue; + point(command, angle, radial, height, CENTER); + int rgb = command.palette[ring.tone(i)]; + float red = ARGB.redFloat(rgb), green = ARGB.greenFloat(rgb), blue = ARGB.blueFloat(rgb); + if (half > 0) { + ring.spin(i, time, ROTATION); + voxel(half * fade, red, green, blue); + } + float brightness = command.spriteStrength * fade / 255; + if (brightness > 0) { + GLOWS.facing(CENTER.x, CENTER.y, CENTER.z, LEFT, UP, 2 * command.spriteSize * fade, 0, + red * brightness, green * brightness, blue * brightness, 1, 0, 0, 1, 1); + } + } + } + + private static void voxel(float half, float red, float green, float blue) { + for (int face = 0; face < 3; face++) { + ROTATION.getColumn(face, NORMAL); + if (NORMAL.dot(CENTER) > 0) NORMAL.negate(); + ROTATION.getColumn((face + 1) % 3, TANGENT); + NORMAL.cross(TANGENT, BITANGENT); + float shade = 0.75f + 0.25f * NORMAL.y + 0.05f * (Math.abs(NORMAL.z) - Math.abs(NORMAL.x)); + for (int corner = 0; corner < 4; corner++) { + float x = CORNER_X[corner], y = CORNER_Y[corner]; + VOXELS.writeVertex( + CENTER.x + (NORMAL.x + x * TANGENT.x + y * BITANGENT.x) * half, + CENTER.y + (NORMAL.y + x * TANGENT.y + y * BITANGENT.y) * half, + CENTER.z + (NORMAL.z + x * TANGENT.z + y * BITANGENT.z) * half, + red * shade, green * shade, blue * shade, 1, 0.5f, 0.5f); + } + } + } + + private static void ribbon(EffectRenderer.RingCommand command, float width, int strength) { + if (width <= 0 || strength <= 0) return; + float red = ARGB.red(command.baseColor) * strength / 65025f; + float green = ARGB.green(command.baseColor) * strength / 65025f; + float blue = ARGB.blue(command.baseColor) * strength / 65025f; + int strands = Math.max(1, command.shape.strands()); + for (int strand = 0; strand < strands; strand++) { + int pieces = RingRenderer.RIBBON_SEGMENTS / strands + (strand < RingRenderer.RIBBON_SEGMENTS % strands ? 1 : 0); + ribbonSample(command, strand, 0, width, A, SIDE_A); + for (int piece = 1; piece <= pieces; piece++) { + ribbonSample(command, strand, piece / (float) pieces, width, B, SIDE_B); + ribbonVertex(A, SIDE_A, 1, red, green, blue, 0); + ribbonVertex(A, SIDE_A, -1, red, green, blue, 1); + ribbonVertex(B, SIDE_B, -1, red, green, blue, 1); + ribbonVertex(B, SIDE_B, 1, red, green, blue, 0); + A.set(B); + SIDE_A.set(SIDE_B); + } + } + } + + private static void ribbonSample(EffectRenderer.RingCommand command, int strand, float sweep, float width, Vector3f point, Vector3f side) { + ParticleRing.RingShape shape = command.shape; + float radius = command.ring.majorRadius(); + if (shape.strands() == 0) { + float angle = Mth.TWO_PI * sweep; + point(command, angle, radius, 0, point); + orient(command.axis, -(float) Math.sin(angle), 0, (float) Math.cos(angle), side); + } else { + float along = helixAlong(shape, sweep); + float offset = strand / (float) shape.strands(); + point(command, Mth.TWO_PI * (offset + shape.turns() * sweep), radius, along * shape.height(), point); + float ahead = sweep + 0.001f; + point(command, Mth.TWO_PI * (offset + shape.turns() * ahead), radius, helixAlong(shape, ahead) * shape.height(), side); + side.sub(point); + width *= helixFade(shape, along); + } + side.cross(point).mul(width / Math.max(side.length(), 0.0001f)); + } + + private static void ribbonVertex(Vector3f point, Vector3f side, float sign, float red, float green, float blue, float u) { + GLOWS.writeVertex(point.x + sign * side.x, point.y + sign * side.y, point.z + sign * side.z, red, green, blue, 1, u, 0.5f); + } + + private static void point(EffectRenderer.RingCommand command, float angle, float radius, float height, Vector3f output) { + orient(command.axis, (float) Math.cos(angle) * radius, height, (float) Math.sin(angle) * radius, output); + output.add(command.x, command.y, command.z); + } + + private static void orient(Direction.Axis axis, float x, float y, float z, Vector3f output) { + switch (axis) { + case X -> output.set(y, x, z); + case Y -> output.set(x, y, z); + case Z -> output.set(x, z, y); + } + } + + private static float helixAlong(ParticleRing.RingShape shape, float sweep) { + float taper = shape.taper(); + float lead = 1 + taper; + return 2 * sweep / (lead + Mth.sqrt(Math.max(0, lead * lead - 4 * taper * sweep))); + } + + private static float helixFade(ParticleRing.RingShape shape, float along) { + double start = Mth.clamp(along / Math.max(shape.fadeIn(), 0.0001f), 0, 1); + double end = Mth.clamp((1 - along) / Math.max(shape.fadeOut(), 0.0001f), 0, 1); + return (float) (Mth.smoothstep(start) * Mth.smoothstep(end)); + } + + static void release() { + VOXELS.release(); + GLOWS.release(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java new file mode 100644 index 0000000..6a6a1b0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java @@ -0,0 +1,334 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.client.Camera; + +import com.mojang.blaze3d.opengl.GlStateManager; +import it.unimi.dsi.fastutil.objects.Reference2IntLinkedOpenHashMap; +import org.joml.Vector3f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL31; +import org.lwjgl.opengl.GL33; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; + +final class RingRenderer { + + static final int RIBBON_SEGMENTS = 192; + private static final int RECORD_BYTES = 112; + private static final int VOXEL_VERTICES = 12; + private static final int QUAD_VERTICES = 4; + private static final int PALETTE_ROWS = 64; + private static final int MAX_GROUPS = 16; + private static final int DATA_TEXTURE_LIMIT = 64; + private static final Reference2IntLinkedOpenHashMap DATA_TEXTURES = new Reference2IntLinkedOpenHashMap<>(); + private static final ParticleRing[] GROUP_RING = new ParticleRing[MAX_GROUPS]; + private static final int[] GROUP_FIRST = new int[MAX_GROUPS]; + private static final int[] GROUP_SIZE = new int[MAX_GROUPS]; + private static final int[] GROUP_TEXTURE = new int[MAX_GROUPS]; + private static final int[][] PALETTES = new int[PALETTE_ROWS][]; + private static final ByteBuffer PALETTE_PIXELS = MemoryUtil.memAlloc(EffectPalette.SIZE * PALETTE_ROWS * 4); + private static int state = -1; + private static TransformFeedbackProgram voxelProgram; + private static TransformFeedbackProgram glowProgram; + private static TransformFeedbackProgram ribbonProgram; + private static int groups; + private static int paletteRows; + private static int records; + private static int[] commandGroup = new int[64]; + private static int[] commandRow = new int[64]; + private static ByteBuffer table = MemoryUtil.memAlloc(64 * RECORD_BYTES); + private static int tableBuffer = -1; + private static int paletteTexture = -1; + private static int simulateVao = -1; + private static final EffectQuadBuffer VOXELS = new EffectQuadBuffer(); + private static final EffectQuadBuffer GLOWS = new EffectQuadBuffer(); + + private RingRenderer() {} + + static boolean available() { + if (state < 0) { + boolean supported = TransformFeedbackProgram.supported(); + if (supported) { + voxelProgram = TransformFeedbackProgram.load("ring_voxel.vsh"); + glowProgram = TransformFeedbackProgram.load("ring_glow.vsh"); + ribbonProgram = TransformFeedbackProgram.load("ring_ribbon.vsh"); + } + state = supported && voxelProgram != null && glowProgram != null && ribbonProgram != null ? 1 : 0; + if (state == 0) ModularMCLibUtils.LOGGER.info("环效果采用普通顶点绘制"); + } + return state == 1; + } + + private static void resetUnpack() { + GlStateManager._pixelStore(GL11.GL_UNPACK_ROW_LENGTH, 0); + GlStateManager._pixelStore(GL11.GL_UNPACK_SKIP_ROWS, 0); + GlStateManager._pixelStore(GL11.GL_UNPACK_SKIP_PIXELS, 0); + GlStateManager._pixelStore(GL11.GL_UNPACK_ALIGNMENT, 4); + } + + private static int texture(int internalFormat, int width, int height, int type, ByteBuffer pixels) { + int id = GlStateManager._genTexture(); + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(id); + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL13.GL_CLAMP_TO_EDGE); + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL13.GL_CLAMP_TO_EDGE); + resetUnpack(); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, internalFormat, width, height, 0, GL11.GL_RGBA, type, pixels); + return id; + } + + private static int dataTexture(ParticleRing ring) { + int cached = DATA_TEXTURES.getAndMoveToLast(ring); + if (cached != 0) return cached; + var data = ring.createData(); + try { + int id = texture(GL30.GL_RGBA32F, ParticleRing.DATA_WIDTH, ring.dataRows(), GL11.GL_FLOAT, data); + DATA_TEXTURES.putAndMoveToLast(ring, id); + if (DATA_TEXTURES.size() > DATA_TEXTURE_LIMIT) GlStateManager._deleteTexture(DATA_TEXTURES.removeFirstInt()); + return id; + } finally { + MemoryUtil.memFree(data); + } + } + + private static int paletteRow(int[] palette) { + for (int i = 0; i < paletteRows; i++) { + if (PALETTES[i] == palette) return i; + } + if (paletteRows == PALETTE_ROWS) return PALETTE_ROWS - 1; + int row = paletteRows++; + PALETTES[row] = palette; + int base = row * EffectPalette.SIZE * 4; + for (int i = 0; i < EffectPalette.SIZE; i++) { + int rgb = palette[i]; + PALETTE_PIXELS.put(base + i * 4, (byte) (rgb >> 16)); + PALETTE_PIXELS.put(base + i * 4 + 1, (byte) (rgb >> 8)); + PALETTE_PIXELS.put(base + i * 4 + 2, (byte) rgb); + PALETTE_PIXELS.put(base + i * 4 + 3, (byte) 0xFF); + } + return row; + } + + private static void putColor(long address, int rgb, int strength) { + MemoryUtil.memPutFloat(address, (rgb >> 16 & 0xFF) * strength / 65025F); + MemoryUtil.memPutFloat(address + 4, (rgb >> 8 & 0xFF) * strength / 65025F); + MemoryUtil.memPutFloat(address + 8, (rgb & 0xFF) * strength / 65025F); + MemoryUtil.memPutFloat(address + 12, 0); + } + + private static void buildTable(List commands, int count) { + groups = 0; + paletteRows = 0; + if (commandGroup.length < count) { + commandGroup = new int[count * 2]; + commandRow = new int[count * 2]; + } + for (int c = 0; c < count; c++) { + var command = commands.get(c); + int group = -1; + for (int g = 0; g < groups; g++) { + if (GROUP_RING[g] == command.ring) { + group = g; + break; + } + } + if (group < 0) { + group = groups < MAX_GROUPS ? groups++ : MAX_GROUPS - 1; + GROUP_RING[group] = command.ring; + GROUP_SIZE[group] = 0; + } + GROUP_SIZE[group]++; + commandGroup[c] = group; + commandRow[c] = paletteRow(command.palette); + } + int first = 0; + for (int g = 0; g < groups; g++) { + GROUP_FIRST[g] = first; + first += GROUP_SIZE[g]; + GROUP_SIZE[g] = 0; + var ring = GROUP_RING[g]; + GROUP_TEXTURE[g] = ring.count() == 0 ? 0 : dataTexture(ring); + } + records = count; + if (table.capacity() < count * RECORD_BYTES) table = MemoryUtil.memRealloc(table, count * 2 * RECORD_BYTES); + long base = MemoryUtil.memAddress(table); + for (int c = 0; c < count; c++) { + var command = commands.get(c); + int g = commandGroup[c]; + int slot = GROUP_FIRST[g] + GROUP_SIZE[g]++; + long address = base + (long) slot * RECORD_BYTES; + var style = command.style; + float breathe = EffectRenderer.breathe(command); + MemoryUtil.memPutFloat(address, command.x); + MemoryUtil.memPutFloat(address + 4, command.y); + MemoryUtil.memPutFloat(address + 8, command.z); + MemoryUtil.memPutFloat(address + 12, (float) command.time); + MemoryUtil.memPutFloat(address + 16, command.ring.half() * command.scale); + MemoryUtil.memPutFloat(address + 20, command.spriteSize); + MemoryUtil.memPutFloat(address + 24, command.spriteStrength / 255F); + MemoryUtil.memPutFloat(address + 28, commandRow[c]); + MemoryUtil.memPutFloat(address + 32, command.axis.ordinal()); + MemoryUtil.memPutFloat(address + 36, command.ring.majorRadius()); + MemoryUtil.memPutFloat(address + 40, style.hazeWidth()); + MemoryUtil.memPutFloat(address + 44, style.coreWidth()); + putColor(address + 48, command.baseColor, (int) (style.hazeStrength() * command.intensity * breathe)); + putColor(address + 64, command.baseColor, (int) (style.coreStrength() * command.intensity * breathe)); + var shape = command.shape; + MemoryUtil.memPutFloat(address + 80, shape.strands()); + MemoryUtil.memPutFloat(address + 84, shape.height()); + MemoryUtil.memPutFloat(address + 88, shape.turns()); + MemoryUtil.memPutFloat(address + 92, shape.taper()); + MemoryUtil.memPutFloat(address + 96, shape.fadeIn()); + MemoryUtil.memPutFloat(address + 100, shape.fadeOut()); + MemoryUtil.memPutFloat(address + 104, 0); + MemoryUtil.memPutFloat(address + 108, 0); + } + if (tableBuffer == -1) tableBuffer = GlStateManager._glGenBuffers(); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, tableBuffer); + table.position(0); + table.limit(count * RECORD_BYTES); + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, table, GL15.GL_STREAM_DRAW); + table.clear(); + if (paletteTexture == -1) { + PALETTE_PIXELS.clear(); + paletteTexture = texture(GL11.GL_RGBA8, EffectPalette.SIZE, PALETTE_ROWS, GL11.GL_UNSIGNED_BYTE, PALETTE_PIXELS); + } else { + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(paletteTexture); + resetUnpack(); + PALETTE_PIXELS.position(0); + PALETTE_PIXELS.limit(EffectPalette.SIZE * paletteRows * 4); + GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, EffectPalette.SIZE, paletteRows, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, PALETTE_PIXELS); + PALETTE_PIXELS.clear(); + } + } + + private static void pointRing(TransformFeedbackProgram program, int firstRecord, int divisor) { + for (int i = 0; i < program.ring.length; i++) { + int location = program.ring[i]; + if (location < 0) continue; + GL20.glEnableVertexAttribArray(location); + GL20.glVertexAttribPointer(location, 4, GL11.GL_FLOAT, false, RECORD_BYTES, (long) firstRecord * RECORD_BYTES + i * 16L); + GL33.glVertexAttribDivisor(location, divisor); + } + } + + private static void useParticles(TransformFeedbackProgram program) { + GlStateManager._glUseProgram(program.id); + GL20.glUniform1i(program.uniform("ParticleData"), 0); + GL20.glUniform1i(program.uniform("PaletteAtlas"), 1); + GlStateManager._activeTexture(GL13.GL_TEXTURE1); + GlStateManager._bindTexture(paletteTexture); + } + + private static int capture(EffectQuadBuffer output, int offsetVertices, int vertices, int instances) { + int count = vertices * instances; + GL30.glBindBufferRange(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, output.buffer, (long) offsetVertices * EffectQuadBuffer.VERTEX_BYTES, (long) count * EffectQuadBuffer.VERTEX_BYTES); + GL30.glBeginTransformFeedback(GL11.GL_POINTS); + GL31.glDrawArraysInstanced(GL11.GL_POINTS, 0, vertices, instances); + GL30.glEndTransformFeedback(); + return count; + } + + private static void simulate(Camera camera) { + int voxelVertices = 0, spriteVertices = 0; + for (int g = 0; g < groups; g++) { + int instances = GROUP_SIZE[g] * GROUP_RING[g].count(); + voxelVertices += instances * VOXEL_VERTICES; + spriteVertices += instances * QUAD_VERTICES; + } + int ribbonVertices = records * RIBBON_SEGMENTS * 2 * QUAD_VERTICES; + VOXELS.reserve(voxelVertices); + GLOWS.reserve(spriteVertices + ribbonVertices); + if (simulateVao == -1) simulateVao = GlStateManager._glGenVertexArrays(); + GlStateManager._glBindVertexArray(simulateVao); + GlStateManager._glBindBuffer(GL15.GL_ARRAY_BUFFER, tableBuffer); + GL11.glEnable(GL30.GL_RASTERIZER_DISCARD); + int voxelOffset = 0, glowOffset = 0; + useParticles(voxelProgram); + int voxelCount = voxelProgram.uniform("ParticleCount"); + for (int g = 0; g < groups; g++) { + var ring = GROUP_RING[g]; + if (ring.count() == 0) continue; + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(GROUP_TEXTURE[g]); + GL20.glUniform1i(voxelCount, ring.count()); + pointRing(voxelProgram, GROUP_FIRST[g], ring.count()); + voxelOffset += capture(VOXELS, voxelOffset, VOXEL_VERTICES, GROUP_SIZE[g] * ring.count()); + } + useParticles(glowProgram); + var left = new Vector3f(-1, 0, 0).rotate(camera.rotation()); + var up = new Vector3f(0, 1, 0).rotate(camera.rotation()); + GL20.glUniform3f(glowProgram.uniform("CameraLeft"), left.x(), left.y(), left.z()); + GL20.glUniform3f(glowProgram.uniform("CameraUp"), up.x(), up.y(), up.z()); + int glowCount = glowProgram.uniform("ParticleCount"); + for (int g = 0; g < groups; g++) { + var ring = GROUP_RING[g]; + if (ring.count() == 0) continue; + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(GROUP_TEXTURE[g]); + GL20.glUniform1i(glowCount, ring.count()); + pointRing(glowProgram, GROUP_FIRST[g], ring.count()); + glowOffset += capture(GLOWS, glowOffset, QUAD_VERTICES, GROUP_SIZE[g] * ring.count()); + } + GlStateManager._glUseProgram(ribbonProgram.id); + GL20.glUniform1i(ribbonProgram.uniform("Segments"), RIBBON_SEGMENTS); + pointRing(ribbonProgram, 0, RIBBON_SEGMENTS * 2); + glowOffset += capture(GLOWS, glowOffset, QUAD_VERTICES, records * RIBBON_SEGMENTS * 2); + GL11.glDisable(GL30.GL_RASTERIZER_DISCARD); + GL30.glBindBufferBase(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0); + GlStateManager._glUseProgram(0); + GlStateManager._glBindVertexArray(0); + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + VOXELS.vertices = voxelOffset; + GLOWS.vertices = glowOffset; + } + + static void draw(List commands, int count, Camera camera) { + if (count == 0) return; + if (!available()) { + RingGeometry.draw(commands, count, camera, VOXELS, GLOWS); + return; + } + if (count > MAX_GROUPS) { + for (int first = 0; first < count; first += MAX_GROUPS) { + int size = Math.min(MAX_GROUPS, count - first); + draw(commands.subList(first, first + size), size, camera); + } + return; + } + buildTable(commands, count); + simulate(camera); + VOXELS.draw(EffectRenderPipelines.VOXEL, EffectRenderPipelines.WHITE_TEXTURE); + GLOWS.draw(EffectRenderPipelines.GLOW, EffectRenderPipelines.GLOW_TEXTURE); + } + + static void reload() { + if (voxelProgram != null) GL20.glDeleteProgram(voxelProgram.id); + if (glowProgram != null) GL20.glDeleteProgram(glowProgram.id); + if (ribbonProgram != null) GL20.glDeleteProgram(ribbonProgram.id); + if (simulateVao != -1) GL30.glDeleteVertexArrays(simulateVao); + if (tableBuffer != -1) GlStateManager._glDeleteBuffers(tableBuffer); + if (paletteTexture != -1) GlStateManager._deleteTexture(paletteTexture); + DATA_TEXTURES.values().forEach(GlStateManager::_deleteTexture); + DATA_TEXTURES.clear(); + Arrays.fill(GROUP_RING, null); + Arrays.fill(PALETTES, null); + voxelProgram = glowProgram = ribbonProgram = null; + state = simulateVao = tableBuffer = paletteTexture = -1; + VOXELS.close(); + GLOWS.close(); + RingGeometry.release(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/SphereHighlight.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/SphereHighlight.java new file mode 100644 index 0000000..58848fb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/SphereHighlight.java @@ -0,0 +1,77 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.client.ModularMCLibUtilsClient; +import com.modularmc.mmclutils.client.render.geometry.MeshPrimitives; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.Vec3; + +import org.joml.Matrix4f; +import org.joml.Matrix4fc; + +/** 在当前客户端世界中绘制持续 200 个游戏 Tick 的球形高亮。 */ +public final class SphereHighlight { + + /** 高亮寿命,单位为未暂停的客户端游戏 Tick。 */ + public static final int DURATION = 200; + private static final int LATITUDES = 40; + private static final int LONGITUDES = 50; + private static final EffectQuadBuffer BUFFER = new EffectQuadBuffer(); + private static final Matrix4f TRANSFORM = new Matrix4f(); + + private static long position; + private static int radius; + private static int remaining; + + private SphereHighlight() {} + + /** 在客户端线程切换高亮。已有高亮时清除它,否则从指定方块坐标开始。 */ + public static void toggle(BlockPos center, int radius) { + toggle(center.asLong(), radius); + } + + /** 与方块坐标重载相同,直接使用 {@link BlockPos#asLong()} 的编码。 */ + public static void toggle(long center, int radius) { + if (remaining != 0) { + clear(); + } else if (ModularMCLibUtilsClient.getLevel() != null) { + if (radius < 1) throw new IllegalArgumentException("高亮半径至少为一"); + position = center; + SphereHighlight.radius = radius; + remaining = DURATION; + } + } + + static void tick() { + if (remaining > 0) remaining--; + } + + /** 在客户端线程立即取消当前高亮。 */ + public static void clear() { + remaining = 0; + } + + static void draw(Vec3 camera, Matrix4fc modelView) { + if (remaining == 0) return; + if (BUFFER.vertices == 0) { + var vertices = new EffectVertices(); + vertices.begin(LATITUDES * LONGITUDES); + try { + MeshPrimitives.sphere(1, LATITUDES, LONGITUDES, + (x, y, z) -> vertices.writeVertex(x, y, z, 0x3333FF, 0.25f, 0, 0)); + vertices.upload(BUFFER); + } finally { + vertices.release(); + } + } + TRANSFORM.set(modelView).translate( + (float) (BlockPos.getX(position) - camera.x), + (float) (BlockPos.getY(position) - camera.y), + (float) (BlockPos.getZ(position) - camera.z)).scale(radius); + BUFFER.draw(EffectRenderPipelines.HIGHLIGHT, EffectRenderPipelines.WHITE_TEXTURE, TRANSFORM); + } + + static void release() { + BUFFER.close(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java new file mode 100644 index 0000000..57b6db9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java @@ -0,0 +1,79 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.client.Minecraft; + +import com.mojang.blaze3d.systems.RenderSystem; +import org.jspecify.annotations.Nullable; +import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +final class TransformFeedbackProgram { + + private static final String[] VARYINGS = { "tfPosition", "tfColor", "tfUV" }; + private static final String FRAGMENT = "#version 150\nout vec4 fragColor;\nvoid main() {\n fragColor = vec4(1.0);\n}\n"; + private static final String[] RING_ATTRIBUTES = { "Ring0", "Ring1", "Ring2", "Ring3", "Ring4", "Ring5", "Ring6", "Ring7" }; + + final int id; + final int[] ring = new int[RING_ATTRIBUTES.length]; + + private TransformFeedbackProgram(int id) { + this.id = id; + for (int i = 0; i < RING_ATTRIBUTES.length; i++) ring[i] = GL20.glGetAttribLocation(id, RING_ATTRIBUTES[i]); + } + + int uniform(String name) { + return GL20.glGetUniformLocation(id, name); + } + + static boolean supported() { + return RenderSystem.getDevice().getBackendName().equalsIgnoreCase("OpenGL") && GL.getCapabilities().OpenGL33; + } + + private static String source(String name) throws IOException { + var manager = Minecraft.getInstance().getResourceManager(); + try (var stream = manager.getResourceOrThrow(ModularMCLibUtils.id("shaders/effect/" + name)).open()) { + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @Nullable + static TransformFeedbackProgram load(String vertex) { + try { + String code = source(vertex).replace("//COMMON", source("ring_common.glsl")); + int vertexShader = compile(GL20.GL_VERTEX_SHADER, code, vertex); + int fragmentShader = compile(GL20.GL_FRAGMENT_SHADER, FRAGMENT, "feedback.fsh"); + int program = GL20.glCreateProgram(); + GL20.glAttachShader(program, vertexShader); + GL20.glAttachShader(program, fragmentShader); + GL30.glTransformFeedbackVaryings(program, VARYINGS, GL30.GL_INTERLEAVED_ATTRIBS); + GL20.glLinkProgram(program); + GL20.glDeleteShader(vertexShader); + GL20.glDeleteShader(fragmentShader); + if (GL20.glGetProgrami(program, GL20.GL_LINK_STATUS) == 0) { + ModularMCLibUtils.LOGGER.error("反馈程序 {} 链接失败,驱动信息为 {}", vertex, GL20.glGetProgramInfoLog(program, 32768)); + GL20.glDeleteProgram(program); + return null; + } + return new TransformFeedbackProgram(program); + } catch (IOException e) { + ModularMCLibUtils.LOGGER.error("反馈程序 {} 加载失败", vertex, e); + return null; + } + } + + private static int compile(int type, String code, String name) { + int shader = GL20.glCreateShader(type); + GL20.glShaderSource(shader, code); + GL20.glCompileShader(shader); + if (GL20.glGetShaderi(shader, GL20.GL_COMPILE_STATUS) == 0) { + ModularMCLibUtils.LOGGER.error("着色器 {} 编译失败,驱动信息为 {}", name, GL20.glGetShaderInfoLog(shader, 32768)); + } + return shader; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/MeshPrimitives.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/MeshPrimitives.java new file mode 100644 index 0000000..cdd0e84 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/MeshPrimitives.java @@ -0,0 +1,82 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import net.minecraft.core.Direction.Axis; + +/** 面向顶点流的基础几何生成。顶点按四边形或线段的顺序输出。 */ +public final class MeshPrimitives { + + private static final int[] BOX_CORNERS = { + 0, 1, 5, 4, 2, 6, 7, 3, 0, 2, 3, 1, + 4, 5, 7, 6, 0, 4, 6, 2, 1, 3, 7, 5 + }; + + private MeshPrimitives() {} + + /** 依次写出下、上、北、南、西、东六个朝外的面,每面四个顶点。 */ + public static void box(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, VertexSink sink) { + for (int corner : BOX_CORNERS) { + sink.vertex((corner & 1) == 0 ? minX : maxX, (corner & 2) == 0 ? minY : maxY, (corner & 4) == 0 ? minZ : maxZ); + } + } + + /** 以原点为球心写出四边形球面。纬度分段至少为二,经度分段至少为三。 */ + public static void sphere(float radius, int latitudes, int longitudes, VertexSink sink) { + if (latitudes < 2 || longitudes < 3) { + throw new IllegalArgumentException("球面分段数不足"); + } + float[] cosines = new float[longitudes]; + float[] sines = new float[longitudes]; + for (int longitude = 0; longitude < longitudes; longitude++) { + double angle = longitude * (Math.TAU / longitudes); + cosines[longitude] = (float) Math.cos(angle); + sines[longitude] = (float) Math.sin(angle); + } + float ring = 0; + float y = -radius; + for (int latitude = 1; latitude <= latitudes; latitude++) { + double angle = latitude * (Math.PI / latitudes) - Math.PI / 2; + float nextRing = latitude == latitudes ? 0 : radius * (float) Math.cos(angle); + float nextY = radius * (float) Math.sin(angle); + for (int longitude = 0; longitude < longitudes; longitude++) { + int next = longitude + 1 == longitudes ? 0 : longitude + 1; + sink.vertex(ring * cosines[longitude], y, ring * sines[longitude]); + sink.vertex(nextRing * cosines[longitude], nextY, nextRing * sines[longitude]); + sink.vertex(nextRing * cosines[next], nextY, nextRing * sines[next]); + sink.vertex(ring * cosines[next], y, ring * sines[next]); + } + ring = nextRing; + y = nextY; + } + } + + /** 写出垂直于给定轴的闭合圆,每条线段写入两个顶点。 */ + public static void circle(Axis axis, float radius, int segments, VertexSink sink) { + if (segments < 3) throw new IllegalArgumentException("圆的分段数至少为三"); + float x = radius, y = 0; + for (int segment = 1; segment <= segments; segment++) { + double angle = segment * (Math.TAU / segments); + float nextX = segment == segments ? radius : radius * (float) Math.cos(angle); + float nextY = segment == segments ? 0 : radius * (float) Math.sin(angle); + planarVertex(axis, x, y, sink); + planarVertex(axis, nextX, nextY, sink); + x = nextX; + y = nextY; + } + } + + private static void planarVertex(Axis axis, float x, float y, VertexSink sink) { + switch (axis) { + case X -> sink.vertex(0, x, y); + case Y -> sink.vertex(x, 0, y); + case Z -> sink.vertex(x, y, 0); + } + } + + /** 在生成几何的调用线程上接收连续顶点,可直接写入调用者的缓冲。 */ + @FunctionalInterface + public interface VertexSink { + + /** 写入一个顶点。生成方法决定每组顶点的图元类型和顺序。 */ + void vertex(float x, float y, float z); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCache.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCache.java new file mode 100644 index 0000000..86fc0f0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCache.java @@ -0,0 +1,102 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.modularmc.mmclutils.api.shape.VoxelShapeCache; +import com.modularmc.mmclutils.client.render.geometry.SectionGeometryCapture.Geometry; + +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; + +import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; +import org.jspecify.annotations.Nullable; + +import java.util.function.LongConsumer; + +/** 在客户端世界线程维护有界的区段采集缓存。采集模式变化时会替换同一区段的旧数据。 */ +public final class SectionGeometryCache { + + private final ClientLevel level; + private final int capacity; + private final VoxelShapeCache shapes = new VoxelShapeCache(); + private final Long2ObjectLinkedOpenHashMap sections = new Long2ObjectLinkedOpenHashMap<>(); + + /** 为指定客户端世界创建一个有界缓存,容量按区段计且须为正数。 */ + public SectionGeometryCache(ClientLevel level, int capacity) { + if (capacity < 1) throw new IllegalArgumentException("区段缓存容量必须为正数"); + this.level = level; + this.capacity = capacity; + } + + /** 取得匹配模式且采集完成的数据,并更新该区段的访问顺序。未命中时返回空值。 */ + public @Nullable Geometry get(long section, int modes) { + Entry entry = sections.getAndMoveToLast(section); + return entry != null && entry.modes == modes ? entry.geometry : null; + } + + /** 推进采集至指定时限。采集完成时转交可在后台读取的数据。 */ + public @Nullable Geometry advance(long section, int modes, long deadline) { + Entry entry = sections.getAndMoveToLast(section); + if (entry == null || entry.modes != modes) { + if (System.nanoTime() >= deadline) return null; + entry = new Entry(section, modes); + sections.putAndMoveToLast(section, entry); + if (sections.size() > capacity) sections.removeFirst(); + } + SectionGeometryCapture capture = entry.capture; + if (capture != null) { + entry.geometry = capture.advance(level, shapes, deadline); + if (entry.geometry != null) entry.capture = null; + } + return entry.geometry; + } + + /** 移除指定区段的缓存和未完成采集。已交付的后台任务由调用方取消。 */ + public void invalidate(long section) { + sections.remove(section); + } + + /** 方块变化后作废所有读取过该位置的区段。调用方可以同时取消相同键的后台任务。 */ + public void invalidateBlock(long position) { + shapes.clear(); + forAffectedSections(position, this::invalidate); + } + + /** 遍历采集边缘可能包含该方块的区段。入参为方块打包坐标,回调接收原版区段打包坐标。 */ + public static void forAffectedSections(long position, LongConsumer action) { + int x = BlockPos.getX(position), y = BlockPos.getY(position), z = BlockPos.getZ(position); + for (int sx = (x - 1) >> 4; sx <= ((x + 1) >> 4); sx++) { + for (int sy = (y - 1) >> 4; sy <= ((y + 1) >> 4); sy++) { + for (int sz = (z - 1) >> 4; sz <= ((z + 1) >> 4); sz++) { + action.accept(SectionPos.asLong(sx, sy, sz)); + } + } + } + } + + /** 区块加载、替换或移除时,作废本列及采集边界与其相交的区段。 */ + public void invalidateChunk(int x, int z) { + var iterator = sections.keySet().iterator(); + while (iterator.hasNext()) { + long section = iterator.nextLong(); + if (Math.abs(SectionPos.x(section) - x) <= 1 && Math.abs(SectionPos.z(section) - z) <= 1) iterator.remove(); + } + } + + /** 世界或资源版本结束时释放全部采集状态。 */ + public void clear() { + sections.clear(); + shapes.clear(); + } + + private static final class Entry { + + private final int modes; + private @Nullable SectionGeometryCapture capture; + private @Nullable Geometry geometry; + + private Entry(long section, int modes) { + this.modes = modes; + capture = new SectionGeometryCapture(section, modes); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCapture.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCapture.java new file mode 100644 index 0000000..b8320e3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryCapture.java @@ -0,0 +1,156 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.modularmc.mmclutils.api.shape.VoxelShapeCache; +import com.modularmc.mmclutils.api.shape.VoxelShapeGeometry; +import com.modularmc.mmclutils.utils.DirectionUtils; +import com.modularmc.mmclutils.utils.TemperatureUtils; + +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.SectionPos; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.phys.shapes.VoxelShape; + +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; + +/** 在客户端线程分步读取已加载区段。单个复杂形状的读取同样受本轮时限约束。 */ +public final class SectionGeometryCapture { + + private static final Direction[] DIRECTIONS = Direction.values(); + private final long origin; + private final int modes; + private final int baseChunkX; + private final int baseChunkZ; + private final VoxelShapeGeometry[] shapes = new VoxelShapeGeometry[18 * 18 * 18]; + private final int[] temperatures = new int[4096]; + private final int[] visible = new int[4096]; + private final BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + private final BlockPos.MutableBlockPos neighbor = new BlockPos.MutableBlockPos(); + private final LevelChunk[] chunks = new LevelChunk[9]; + private @Nullable ClientLevel world; + private @Nullable Geometry result; + private @Nullable PendingBlock pending; + private int queriedChunks; + private int cursor; + + /** 为一个原版打包区段创建分步采集。模式位定义在 {@link Geometry}。 */ + public SectionGeometryCapture(long section, int modes) { + origin = BlockPos.asLong(SectionPos.sectionToBlockCoord(SectionPos.x(section)), SectionPos.sectionToBlockCoord(SectionPos.y(section)), SectionPos.sectionToBlockCoord(SectionPos.z(section))); + baseChunkX = BlockPos.getX(origin) >> 4; + baseChunkZ = BlockPos.getZ(origin) >> 4; + this.modes = modes; + } + + /** 在同一客户端世界线程恢复采集,时限使用 System.nanoTime 计时。 */ + public @Nullable Geometry advance(ClientLevel level, VoxelShapeCache cache, long deadline) { + if (world == null) world = level; + else if (world != level) throw new IllegalArgumentException("区段采集已经绑定到另一世界"); + if (result != null) return result; + if (System.nanoTime() >= deadline) return null; + refreshChunks(level); + + while (cursor < shapes.length && System.nanoTime() < deadline) { + int x = cursor % 18 - 1, z = cursor / 18 % 18 - 1, y = cursor / (18 * 18) - 1; + position.set(BlockPos.getX(origin) + x, BlockPos.getY(origin) + y, BlockPos.getZ(origin) + z); + if (pending == null) { + LevelChunk chunk = loadedChunk(level, position.getX() >> 4, position.getZ() >> 4); + if (chunk == null) { + shapes[cursor++] = VoxelShapeGeometry.EMPTY; + continue; + } + BlockState state = chunk.getBlockState(position); + if (state.isAir()) { + shapes[cursor++] = VoxelShapeGeometry.EMPTY; + continue; + } + pending = new PendingBlock(state, state.getShape(level, position)); + } + BlockState state = pending.state(); + VoxelShapeGeometry shape = cache.capture(pending.shape(), deadline); + if (shape == null) return null; + pending = null; + if (shape == VoxelShapeGeometry.UNSUPPORTED) { + shapes[cursor++] = shape; + continue; + } + var fluid = state.getFluidState(); + if (shape.empty() && !fluid.isEmpty()) shape = VoxelShapeGeometry.box(fluid.getHeight(level, position)); + shapes[cursor++] = shape; + if (x < 0 || y < 0 || z < 0 || x > 15 || y > 15 || z > 15) continue; + int index = (y * 16 + z) * 16 + x; + visible[index] = exposedFaces(level, position, state); + if ((modes & Geometry.INCLUDE_TEMPERATURE) != 0 && (visible[index] != 0 || shape != VoxelShapeGeometry.BLOCK)) temperatures[index] = TemperatureUtils.temperature(state, level, position); + } + if (cursor != shapes.length) return null; + Arrays.fill(chunks, null); + result = new Geometry(origin, modes, shapes, temperatures, visible); + return result; + } + + private int exposedFaces(ClientLevel level, BlockPos position, BlockState state) { + int faces = 0; + var fluid = state.getFluidState(); + for (Direction direction : DIRECTIONS) { + neighbor.setWithOffset(position, direction); + LevelChunk chunk = loadedChunk(level, neighbor.getX() >> 4, neighbor.getZ() >> 4); + if (chunk == null) faces |= DirectionUtils.mask(direction); + else { + BlockState adjacent = chunk.getBlockState(neighbor); + if ((fluid.isEmpty() || !fluid.getType().isSame(adjacent.getFluidState().getType())) && Block.shouldRenderFace(level, position, state, adjacent, direction)) faces |= DirectionUtils.mask(direction); + } + } + return faces; + } + + private @Nullable LevelChunk loadedChunk(ClientLevel level, int chunkX, int chunkZ) { + int chunkIndex = (chunkX - baseChunkX + 1) * 3 + chunkZ - baseChunkZ + 1; + int bit = 1 << chunkIndex; + if ((queriedChunks & bit) == 0) { + chunks[chunkIndex] = level.getChunkSource().getChunk(chunkX, chunkZ, false); + queriedChunks |= bit; + } + return chunks[chunkIndex]; + } + + private void refreshChunks(ClientLevel level) { + for (int mask = queriedChunks; mask != 0; mask &= mask - 1) { + int index = Integer.numberOfTrailingZeros(mask); + int x = baseChunkX + index / 3 - 1; + int z = baseChunkZ + index % 3 - 1; + if (chunks[index] == level.getChunkSource().getChunk(x, z, false)) continue; + + // 区块缺失或被替换后,已经采集的可见面也可能发生变化。 + cursor = 0; + pending = null; + queriedChunks = 0; + Arrays.fill(chunks, null); + Arrays.fill(temperatures, 0); + Arrays.fill(visible, 0); + return; + } + } + + private record PendingBlock(BlockState state, VoxelShape shape) {} + + /** 区段和一格邻接范围的几何数据。构造时接管各数组,交付后调用方和后台线程均只读。 */ + public record Geometry(long origin, int modes, VoxelShapeGeometry[] shapes, int[] temperatures, int[] visibleFaces) { + + /** 采集几何的同时填充区段内的温度数组。 */ + public static final int INCLUDE_TEMPERATURE = 1; + + /** 查找原点相对坐标处的几何。坐标范围为 -1~16,越界时返回空几何。 */ + public VoxelShapeGeometry shape(int x, int y, int z) { + return x < -1 || y < -1 || z < -1 || x > 16 || y > 16 || z > 16 ? VoxelShapeGeometry.EMPTY : shapes[index(x, y, z)]; + } + + /** 将 -1~16 范围内的局部坐标转换为带边界的形状数组索引。 */ + public static int index(int x, int y, int z) { + return ((y + 1) * 18 + z + 1) * 18 + x + 1; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryRenderer.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryRenderer.java new file mode 100644 index 0000000..44988bb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryRenderer.java @@ -0,0 +1,187 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.modularmc.mmclutils.api.schedule.BoundedVirtualTaskQueue; +import com.modularmc.mmclutils.api.shape.VoxelShapeGeometry; +import com.modularmc.mmclutils.client.render.geometry.SectionGeometryCapture.Geometry; + +import net.minecraft.core.Direction; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.ByteBufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.MeshData; +import com.mojang.blaze3d.vertex.VertexFormat; +import org.jspecify.annotations.Nullable; + +import java.util.concurrent.CancellationException; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.IntUnaryOperator; + +/** 从已采集的区段生成局部坐标的面与轮廓。计算期间不持有世界或 GPU 对象。 */ +public final class SectionGeometryRenderer { + + private static final int MAX_VERTICES = 32768; + + private SectionGeometryRenderer() {} + + /** + * 创建带并发与结果限制的网格生成队列。调用方负责关闭队列和已领走的批次。 + * + * @param parallelism 并行生成任务数上限 + * @param resultCapacity 暂存批次数量上限 + * @return 由所属线程驱动的任务队列 + */ + public static BoundedVirtualTaskQueue queue(int parallelism, int resultCapacity) { + return new BoundedVirtualTaskQueue<>("mmclutils-section-", parallelism, resultCapacity, Batch::close); + } + + /** 在队列所属线程提交。键可用原版区段坐标;同一个键的旧任务由调用方作废。 */ + public static void submit(BoundedVirtualTaskQueue queue, long key, Geometry data, Style style) { + queue.submit(key, work -> build(data, style, work::cancelled, work::emit)); + } + + /** 每个已交付批次的关闭责任转交给回调。色值的透明分量为零时跳过对应图元。 */ + public static void build(Geometry data, Style style, BooleanSupplier cancelled, Consumer output) { + VoxelContours contours = (style.outlineColor() >>> 24) == 0 ? null : new VoxelContours(data, cancelled); + try (var surfaces = new Buffer(data.origin(), VertexFormat.Mode.QUADS, output)) { + for (int cell = 0; cell < 4096; cell++) { + checkCancelled(cancelled); + int x = cell & 15, y = cell >>> 8, z = cell >>> 4 & 15; + var shape = data.shape(x, y, z); + if (shape.empty()) continue; + int color = style.surfaceColor().applyAsInt(data.temperatures()[cell]); + if ((color >>> 24) == 0 && contours == null) continue; + emitBlock(surfaces, contours, shape, x, y, z, data.visibleFaces()[cell], color, cancelled); + } + surfaces.flush(); + } + if (contours == null) return; + try (var outline = new Buffer(data.origin(), VertexFormat.Mode.DEBUG_LINES, output)) { + contours.write(edge -> { + checkCancelled(cancelled); + outline.vertex(edge.x1(), edge.y1(), edge.z1(), style.outlineColor()); + outline.vertex(edge.x2(), edge.y2(), edge.z2(), style.outlineColor()); + outline.flushIfFull(); + }); + outline.flush(); + } + } + + private static void emitBlock(Buffer surfaces, @Nullable VoxelContours contours, VoxelShapeGeometry shape, + int x, int y, int z, int visible, int color, BooleanSupplier cancelled) { + double[] xs = shape.x(), ys = shape.y(), zs = shape.z(); + for (int i = 0; i < xs.length - 1; i++) { + for (int j = 0; j < ys.length - 1; j++) { + for (int k = 0; k < zs.length - 1; k++) { + if ((k & 63) == 0) checkCancelled(cancelled); + if (!shape.filled(i, j, k)) continue; + float a = (float) (x + xs[i]), b = (float) (y + ys[j]), c = (float) (z + zs[k]); + float d = (float) (x + xs[i + 1]), e = (float) (y + ys[j + 1]), f = (float) (z + zs[k + 1]); + if (!shape.filled(i - 1, j, k) && visible(visible, Direction.WEST, xs[i], 0)) face(surfaces, contours, x, y, z, color, a, b, c, a, b, f, a, e, f, a, e, c); + if (!shape.filled(i + 1, j, k) && visible(visible, Direction.EAST, xs[i + 1], 1)) face(surfaces, contours, x, y, z, color, d, b, f, d, b, c, d, e, c, d, e, f); + if (!shape.filled(i, j - 1, k) && visible(visible, Direction.DOWN, ys[j], 0)) face(surfaces, contours, x, y, z, color, a, b, c, d, b, c, d, b, f, a, b, f); + if (!shape.filled(i, j + 1, k) && visible(visible, Direction.UP, ys[j + 1], 1)) face(surfaces, contours, x, y, z, color, a, e, f, d, e, f, d, e, c, a, e, c); + if (!shape.filled(i, j, k - 1) && visible(visible, Direction.NORTH, zs[k], 0)) face(surfaces, contours, x, y, z, color, d, b, c, a, b, c, a, e, c, d, e, c); + if (!shape.filled(i, j, k + 1) && visible(visible, Direction.SOUTH, zs[k + 1], 1)) face(surfaces, contours, x, y, z, color, a, b, f, d, b, f, d, e, f, a, e, f); + } + } + } + } + + private static boolean visible(int mask, Direction direction, double position, int boundary) { + return position != boundary || (mask & 1 << direction.ordinal()) != 0; + } + + private static void face(Buffer buffer, @Nullable VoxelContours contours, int x, int y, int z, int color, + float x1, float y1, float z1, float x2, float y2, float z2, + float x3, float y3, float z3, float x4, float y4, float z4) { + if ((color >>> 24) != 0) { + buffer.vertex(x1, y1, z1, color); + buffer.vertex(x2, y2, z2, color); + buffer.vertex(x3, y3, z3, color); + buffer.vertex(x4, y4, z4, color); + buffer.flushIfFull(); + } + if (contours != null) { + contours.add(x, y, z, x1, y1, z1, x2, y2, z2); + contours.add(x, y, z, x2, y2, z2, x3, y3, z3); + contours.add(x, y, z, x3, y3, z3, x4, y4, z4); + contours.add(x, y, z, x4, y4, z4, x1, y1, z1); + } + } + + private static void checkCancelled(BooleanSupplier cancelled) { + if (cancelled.getAsBoolean() || Thread.currentThread().isInterrupted()) throw new CancellationException(); + } + + /** 面着色函数接收采集的温度值,在计算线程调用。边框使用固定 ARGB。 */ + public record Style(IntUnaryOperator surfaceColor, int outlineColor) { + + /** 使用统一的表面色和轮廓色创建样式。颜色采用 ARGB 打包。 */ + public Style(int surfaceColor, int outlineColor) { + this(ignored -> surfaceColor, outlineColor); + } + } + + /** 一批顶点和区段原点的打包坐标。可在任意线程关闭,在渲染线程上传。 */ + public record Batch(long origin, MeshData mesh, ByteBufferBuilder memory) implements AutoCloseable { + + /** 在渲染线程复制当前批次到独立的 GPU 网格。上传后仍须关闭批次。 */ + public StaticMesh upload(String label) { + return StaticMesh.upload(label, mesh); + } + + @Override + public void close() { + try { + mesh.close(); + } finally { + memory.close(); + } + } + } + + private static final class Buffer implements AutoCloseable { + + private final long origin; + private final VertexFormat.Mode mode; + private final Consumer output; + private @Nullable ByteBufferBuilder memory; + private @Nullable BufferBuilder builder; + private int vertices; + + private Buffer(long origin, VertexFormat.Mode mode, Consumer output) { + this.origin = origin; + this.mode = mode; + this.output = output; + } + + private void vertex(float x, float y, float z, int color) { + if (builder == null) { + memory = new ByteBufferBuilder(4096); + builder = new BufferBuilder(memory, mode, DefaultVertexFormat.POSITION_COLOR); + } + builder.addVertex(x, y, z).setColor(color); + vertices++; + } + + private void flushIfFull() { + if (vertices >= MAX_VERTICES) flush(); + } + + private void flush() { + if (builder == null) return; + var batch = new Batch(origin, builder.buildOrThrow(), memory); + builder = null; + memory = null; + vertices = 0; + output.accept(batch); + } + + @Override + public void close() { + if (memory != null) memory.close(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/SpriteQuads.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SpriteQuads.java new file mode 100644 index 0000000..ccb522d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SpriteQuads.java @@ -0,0 +1,152 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import org.joml.Matrix4f; + +/** + * 按每格十六像素生成轴对齐的纹理面,使流体或面板可以跨方块连续平铺。 + * 顶点包含位置、颜色、UV、覆盖层、亮度和法线。 + */ +public final class SpriteQuads { + + /** 单个面的掩码,位编号使用原版方向编号。 */ + public static final int DOWN = 1, UP = 2, NORTH = 4, SOUTH = 8, WEST = 16, EAST = 32; + /** 水平方向的四个侧面掩码。 */ + public static final int SIDES = NORTH | SOUTH | WEST | EAST; + /** 六个方向的合并掩码。 */ + public static final int ALL = SIDES | UP | DOWN; + + private static final float P = 1F / 16F; + + private SpriteQuads() {} + + /** + * 将方向转为可与其他面掩码按位组合的标记。 + * + * @param face 选中的方块面 + * @return 原版方向编号对应的单个位 + */ + public static int bit(Direction face) { + return 1 << face.get3DDataValue(); + } + + /** + * 写入盒体选定的外侧面。每 16 个局部像素平铺一格纹理,边缘只取对应的 UV 子范围。 + * + * @param buffer 接收四边形顶点的缓冲区,须支持位置、颜色、UV、覆盖层、光照和法线 + * @param pose 将局部方块坐标变换到目标空间的矩阵 + * @param sprite 用于平铺的图集精灵 + * @param x0 盒体西侧的局部像素坐标 + * @param y0 盒体底部的局部像素坐标 + * @param z0 盒体北侧的局部像素坐标 + * @param x1 盒体东侧的局部像素坐标 + * @param y1 盒体顶部的局部像素坐标 + * @param z1 盒体南侧的局部像素坐标 + * @param faces 用 {@link #bit(Direction)} 组合的面掩码 + * @param argb 应用于各顶点的 ARGB 颜色 + * @param light 原版打包光照 + */ + public static void box(VertexConsumer buffer, Matrix4f pose, TextureAtlasSprite sprite, float x0, float y0, float z0, float x1, float y1, float z1, + int faces, int argb, int light) { + for (var face : Direction.values()) { + if ((faces & bit(face)) != 0) face(buffer, pose, sprite, face, x0, y0, z0, x1, y1, z1, argb, light); + } + } + + /** + * 写入盒体的一个外侧面。顶点顺序和法线朝外,纹理按每 16 像素平铺。 + * + * @param buffer 接收四边形顶点的缓冲区 + * @param pose 将局部方块坐标变换到目标空间的矩阵 + * @param sprite 用于平铺的图集精灵 + * @param face 要写入的面的朝向 + * @param x0 盒体西侧的局部像素坐标 + * @param y0 盒体底部的局部像素坐标 + * @param z0 盒体北侧的局部像素坐标 + * @param x1 盒体东侧的局部像素坐标 + * @param y1 盒体顶部的局部像素坐标 + * @param z1 盒体南侧的局部像素坐标 + * @param argb 应用于各顶点的 ARGB 颜色 + * @param light 原版打包光照 + */ + public static void face(VertexConsumer buffer, Matrix4f pose, TextureAtlasSprite sprite, Direction face, float x0, float y0, float z0, float x1, + float y1, float z1, int argb, int light) { + switch (face) { + case UP -> horizontal(buffer, pose, sprite, x0, z0, x1, z1, y1, true, argb, light); + case DOWN -> horizontal(buffer, pose, sprite, x0, z0, x1, z1, y0, false, argb, light); + case NORTH -> vertical(buffer, pose, sprite, face, x0, x1, y0, y1, z0, argb, light); + case SOUTH -> vertical(buffer, pose, sprite, face, x0, x1, y0, y1, z1, argb, light); + case WEST -> vertical(buffer, pose, sprite, face, z0, z1, y0, y1, x0, argb, light); + case EAST -> vertical(buffer, pose, sprite, face, z0, z1, y0, y1, x1, argb, light); + } + } + + private static void horizontal(VertexConsumer buffer, Matrix4f pose, TextureAtlasSprite sprite, float x0, float z0, float x1, float z1, float y, + boolean up, int argb, int light) { + for (float a = x0; a < x1;) { + float ta = tile(a), a1 = Math.min(x1, ta + 16); + for (float b = z0; b < z1;) { + float tb = tile(b), b1 = Math.min(z1, tb + 16); + float u0 = sprite.getU((a - ta) * P), u1 = sprite.getU((a1 - ta) * P); + float v0 = sprite.getV((b - tb) * P), v1 = sprite.getV((b1 - tb) * P); + if (up) { + vertex(buffer, pose, a, y, b, u0, v0, argb, light, 0, 1, 0); + vertex(buffer, pose, a, y, b1, u0, v1, argb, light, 0, 1, 0); + vertex(buffer, pose, a1, y, b1, u1, v1, argb, light, 0, 1, 0); + vertex(buffer, pose, a1, y, b, u1, v0, argb, light, 0, 1, 0); + } else { + vertex(buffer, pose, a, y, b, u0, v0, argb, light, 0, -1, 0); + vertex(buffer, pose, a1, y, b, u1, v0, argb, light, 0, -1, 0); + vertex(buffer, pose, a1, y, b1, u1, v1, argb, light, 0, -1, 0); + vertex(buffer, pose, a, y, b1, u0, v1, argb, light, 0, -1, 0); + } + b = b1; + } + a = a1; + } + } + + private static void vertical(VertexConsumer buffer, Matrix4f pose, TextureAtlasSprite sprite, Direction face, float h0, float h1, float y0, + float y1, float plane, int argb, int light) { + float nx = face.getStepX(), nz = face.getStepZ(); + for (float a = h0; a < h1;) { + float ta = tile(a), a1 = Math.min(h1, ta + 16); + for (float y = y0; y < y1;) { + float ty = tile(y), yb = Math.min(y1, ty + 16); + float u0 = sprite.getU((a - ta) * P), u1 = sprite.getU((a1 - ta) * P); + float v0 = sprite.getV(1 - (yb - ty) * P), v1 = sprite.getV(1 - (y - ty) * P); + switch (face) { + case NORTH -> quad(buffer, pose, argb, light, nx, nz, a, y, plane, a, yb, plane, a1, yb, plane, a1, y, plane, u0, v1, u0, v0, u1, v0, u1, v1); + case SOUTH -> quad(buffer, pose, argb, light, nx, nz, a1, y, plane, a1, yb, plane, a, yb, plane, a, y, plane, u1, v1, u1, v0, u0, v0, u0, v1); + case WEST -> quad(buffer, pose, argb, light, nx, nz, plane, y, a1, plane, yb, a1, plane, yb, a, plane, y, a, u1, v1, u1, v0, u0, v0, u0, v1); + default -> quad(buffer, pose, argb, light, nx, nz, plane, y, a, plane, yb, a, plane, yb, a1, plane, y, a1, u0, v1, u0, v0, u1, v0, u1, v1); + } + y = yb; + } + a = a1; + } + } + + private static float tile(float v) { + return (float) Math.floor(v / 16F + 1e-4F) * 16F; + } + + private static void quad(VertexConsumer buffer, Matrix4f pose, int argb, int light, float nx, float nz, float xa, float ya, float za, float xb, + float yb, float zb, float xc, float yc, float zc, float xd, float yd, float zd, float ua, float va, float ub, float vb, + float uc, float vc, float ud, float vd) { + vertex(buffer, pose, xa, ya, za, ua, va, argb, light, nx, 0, nz); + vertex(buffer, pose, xb, yb, zb, ub, vb, argb, light, nx, 0, nz); + vertex(buffer, pose, xc, yc, zc, uc, vc, argb, light, nx, 0, nz); + vertex(buffer, pose, xd, yd, zd, ud, vd, argb, light, nx, 0, nz); + } + + private static void vertex(VertexConsumer buffer, Matrix4f pose, float x, float y, float z, float u, float v, int argb, int light, float nx, + float ny, float nz) { + buffer.addVertex(pose, x * P, y * P, z * P).setColor(argb).setUv(u, v) + .setOverlay(OverlayTexture.NO_OVERLAY).setLight(light).setNormal(nx, ny, nz); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java new file mode 100644 index 0000000..33766a5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java @@ -0,0 +1,70 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.MeshData; +import com.mojang.blaze3d.vertex.VertexFormat; +import org.jspecify.annotations.Nullable; + +/** 保存能跨帧使用的 GPU 顶点和索引。上传、提交及释放都在渲染线程完成。 */ +public final class StaticMesh implements AutoCloseable { + + private final GpuBuffer vertices; + private final @Nullable GpuBuffer indices; + private final MeshData.DrawState state; + + private StaticMesh(GpuBuffer vertices, @Nullable GpuBuffer indices, MeshData.DrawState state) { + this.vertices = vertices; + this.indices = indices; + this.state = state; + } + + /** 复制网格数据。调用方仍负责关闭传入的网格。 */ + public static StaticMesh upload(String label, MeshData mesh) { + RenderSystem.assertOnRenderThread(); + var device = RenderSystem.getDevice(); + GpuBuffer vertices = device.createBuffer(() -> label + " vertices", GpuBuffer.USAGE_VERTEX, mesh.vertexBuffer()); + try { + var bytes = mesh.indexBuffer(); + GpuBuffer indices = bytes == null ? null : device.createBuffer(() -> label + " indices", GpuBuffer.USAGE_INDEX, bytes); + return new StaticMesh(vertices, indices, mesh.drawState()); + } catch (RuntimeException | Error failure) { + vertices.close(); + throw failure; + } + } + + /** 返回网格在上传时使用的顶点格式。 */ + public VertexFormat format() { + return state.format(); + } + + /** 返回网格的图元模式,供调用方选择绘制管线。 */ + public VertexFormat.Mode mode() { + return state.mode(); + } + + /** 在已设置管线、变换及贴图的 pass 中提交。管线的顶点格式和图元须与网格一致。 */ + public void draw(RenderPass pass) { + pass.setVertexBuffer(0, vertices); + if (indices == null) { + var sequential = RenderSystem.getSequentialBuffer(state.mode()); + pass.setIndexBuffer(sequential.getBuffer(state.indexCount()), sequential.type()); + } else { + pass.setIndexBuffer(indices, state.indexType()); + } + pass.drawIndexed(0, 0, state.indexCount(), 1); + } + + /** 在渲染线程释放网格的顶点缓冲和独立索引缓冲。 */ + @Override + public void close() { + RenderSystem.assertOnRenderThread(); + try { + if (indices != null) indices.close(); + } finally { + vertices.close(); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java new file mode 100644 index 0000000..e641ab3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java @@ -0,0 +1,37 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.modularmc.mmclutils.client.model.QuadUtils; +import com.modularmc.mmclutils.client.model.QuadView; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +import java.util.function.IntUnaryOperator; + +/** 按原版实体顶点格式提交位置、调制色、图集 UV、光照和法线。 */ +public final class VertexWriters { + + private VertexWriters() {} + + /** 按指定姿态写出位置和法线,其余属性使用传入的图集 UV、ARGB、覆盖层与打包光照。 */ + public static void vertex(VertexConsumer vertices, PoseStack.Pose pose, Vector3fc position, int color, + float u, float v, int overlay, int light, Vector3fc normal) { + vertices.addVertex(pose, position).setColor(color).setUv(u, v).setOverlay(overlay).setLight(light).setNormal(pose, normal); + } + + /** 按四边形顶点顺序写入,同一打包光照应用于四点。 */ + public static void quad(VertexConsumer vertices, PoseStack.Pose pose, QuadView quad, int overlay, int light) { + quad(vertices, pose, quad, overlay, ignored -> light); + } + + /** 按四边形顶点顺序写入。回调按顶点索引分别提供打包光照。 */ + public static void quad(VertexConsumer vertices, PoseStack.Pose pose, QuadView quad, int overlay, IntUnaryOperator light) { + var normal = new Vector3f(); + for (int index = 0; index < QuadView.VERTEX_COUNT; index++) { + vertex(vertices, pose, quad.position(index), quad.color(index), quad.u(index), quad.v(index), overlay, + light.applyAsInt(index), QuadUtils.vertexNormal(quad, index, normal)); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/VoxelContours.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/VoxelContours.java new file mode 100644 index 0000000..9701157 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/VoxelContours.java @@ -0,0 +1,117 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.modularmc.mmclutils.api.shape.VoxelShapeGeometry; +import com.modularmc.mmclutils.client.render.geometry.SectionGeometryCapture.Geometry; + +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; + +import it.unimi.dsi.fastutil.doubles.DoubleArrayList; +import it.unimi.dsi.fastutil.doubles.DoubleComparators; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import lombok.RequiredArgsConstructor; + +import java.util.concurrent.CancellationException; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; + +/** 从区段几何数据计算并集轮廓,可在后台线程中执行。 */ +@RequiredArgsConstructor +public final class VoxelContours { + + private static final double EPSILON = 1.0e-5; + private final Geometry geometry; + private final BooleanSupplier cancelled; + private final ObjectOpenHashSet edges = new ObjectOpenHashSet<>(); + private final DoubleArrayList cuts = new DoubleArrayList(); + + /** + * 按沿线的体素占用变化分段,将并集边界上的部分纳入轮廓。 + * + * @param bx 来源方块的区段局部 X 坐标 + * @param by 来源方块的区段局部 Y 坐标 + * @param bz 来源方块的区段局部 Z 坐标 + * @param x1 候选线段起点 X + * @param y1 候选线段起点 Y + * @param z1 候选线段起点 Z + * @param x2 候选线段终点 X + * @param y2 候选线段终点 Y + * @param z2 候选线段终点 Z + * @throws CancellationException 计算已被取消或中断 + */ + public void add(int bx, int by, int bz, float x1, float y1, float z1, float x2, float y2, float z2) { + checkCancelled(); + Direction.Axis axis = x1 != x2 ? Direction.Axis.X : y1 != y2 ? Direction.Axis.Y : Direction.Axis.Z; + double a = axis.choose(x1, y1, z1), b = axis.choose(x2, y2, z2); + double start = Math.min(a, b), end = Math.max(a, b); + double u = axis == Direction.Axis.X ? y1 : x1; + double v = axis == Direction.Axis.Z ? y1 : z1; + cuts.clear(); + cuts.add(start); + cuts.add(end); + for (int cell = Mth.floor(start); cell <= Mth.floor(end - EPSILON); cell++) { + checkCancelled(); + if (cell > start) cuts.add(cell); + double along = (Math.max(start, cell) + Math.min(end, cell + 1)) * 0.5; + for (int side = 0; side < 4; side++) { + double across = u + ((side & 1) == 0 ? -EPSILON : EPSILON), vertical = v + ((side & 2) == 0 ? -EPSILON : EPSILON); + int nx = Mth.floor(axis == Direction.Axis.X ? along : across); + int ny = Mth.floor(axis == Direction.Axis.Y ? along : axis == Direction.Axis.X ? across : vertical); + int nz = Mth.floor(axis == Direction.Axis.Z ? along : vertical); + for (double coordinate : geometry.shape(nx, ny, nz).coordinates(axis)) { + checkCancelled(); + double cut = axis.choose(nx, ny, nz) + coordinate; + if (cut > start && cut < end) cuts.add(cut); + } + } + } + cuts.sort(DoubleComparators.NATURAL_COMPARATOR); + for (int index = 1; index < cuts.size(); index++) { + checkCancelled(); + double from = cuts.getDouble(index - 1), to = cuts.getDouble(index); + if (to - from < EPSILON) continue; + int filled = 0; + for (int side = 0; side < 4; side++) { + double across = u + ((side & 1) == 0 ? -EPSILON : EPSILON), vertical = v + ((side & 2) == 0 ? -EPSILON : EPSILON); + if (occupied(bx, by, bz, axis, (from + to) * 0.5, across, vertical)) filled |= 1 << side; + } + if (filled == 0 || filled == 15 || filled == 3 || filled == 5 || filled == 10 || filled == 12) continue; + edges.add(switch (axis) { + case X -> new Edge((float) from, (float) u, (float) v, (float) to, (float) u, (float) v); + case Y -> new Edge((float) u, (float) from, (float) v, (float) u, (float) to, (float) v); + case Z -> new Edge((float) u, (float) v, (float) from, (float) u, (float) v, (float) to); + }); + } + } + + private boolean occupied(int bx, int by, int bz, Direction.Axis axis, double along, double u, double v) { + double x = axis == Direction.Axis.X ? along : u; + double y = axis == Direction.Axis.Y ? along : axis == Direction.Axis.X ? u : v; + double z = axis == Direction.Axis.Z ? along : v; + VoxelShapeGeometry source = geometry.shape(bx, by, bz); + if (source.contains(x - bx, y - by, z - bz)) return true; + int nx = Mth.floor(x), ny = Mth.floor(y), nz = Mth.floor(z); + return geometry.shape(nx, ny, nz).contains(x - nx, y - ny, z - nz); + } + + private void checkCancelled() { + if (cancelled.getAsBoolean() || Thread.currentThread().isInterrupted()) throw new CancellationException(); + } + + /** 将已采集的轮廓边交给调用方,端点使用区段局部坐标。 */ + public void write(Consumer output) { + edges.forEach(output); + } + + /** + * 区段局部空间中的轴对齐轮廓线段。两个端点均以方块为单位。 + * + * @param x1 起点 X + * @param y1 起点 Y + * @param z1 起点 Z + * @param x2 终点 X + * @param y2 终点 Y + * @param z2 终点 Z + */ + public record Edge(float x1, float y1, float z1, float x2, float y2, float z2) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/client/texture/ImageTextures.java b/src/main/java/com/modularmc/mmclutils/client/texture/ImageTextures.java new file mode 100644 index 0000000..65743c1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/texture/ImageTextures.java @@ -0,0 +1,258 @@ +package com.modularmc.mmclutils.client.texture; + +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.resources.Identifier; + +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.RenderSystem; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import lombok.RequiredArgsConstructor; +import org.jspecify.annotations.Nullable; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; + +/** 以最近访问顺序缓存动态贴图。每个缓存须独占其注册标识,清理时释放对应 GPU 资源。 */ +public final class ImageTextures implements AutoCloseable { + + private final TextureManager textures; + private final int capacity; + private final Object2ObjectLinkedOpenHashMap entries = new Object2ObjectLinkedOpenHashMap<>(); + + /** 创建渲染线程使用的动态贴图缓存。容量为同时保留的贴图数,须为正数。缓存占有登记的标识。 */ + public ImageTextures(TextureManager textures, int capacity) { + if (capacity < 1) throw new IllegalArgumentException("贴图缓存容量必须为正数"); + this.textures = textures; + this.capacity = capacity; + } + + /** 查询缓存并更新最近使用顺序。缺失时返回空值,返回的贴图由缓存持有。 */ + public @Nullable DynamicTexture get(Identifier id) { + RenderSystem.assertOnRenderThread(); + return entries.getAndMoveToLast(id); + } + + /** 在渲染线程从文件解码并登记 PNG,方法返回或抛出异常时关闭文件流。 */ + public DynamicTexture load(Identifier id, Path path, Limits limits) throws IOException { + try (InputStream input = Files.newInputStream(path)) { + return load(id, input, limits); + } + } + + /** 在渲染线程读取和上传。输入流由调用方关闭。 */ + public DynamicTexture load(Identifier id, InputStream input, Limits limits) throws IOException { + RenderSystem.assertOnRenderThread(); + return load(id, input.readNBytes(limits.bytes() + 1), limits); + } + + /** 读取 PNG 数据。解码前限制文件大小和像素数。 */ + public DynamicTexture load(Identifier id, byte[] bytes, Limits limits) throws IOException { + RenderSystem.assertOnRenderThread(); + if (bytes.length > limits.bytes()) throw new IOException("贴图数据超出字节上限 " + id); + checkHeader(id, bytes, limits); + NativeImage image = NativeImage.read(bytes); + DynamicTexture texture; + try { + texture = new DynamicTexture(id::toString, image); + } catch (RuntimeException | Error failure) { + image.close(); + throw failure; + } + try { + textures.register(id, texture); + } catch (RuntimeException | Error failure) { + texture.close(); + throw failure; + } + entries.putAndMoveToLast(id, texture); + if (entries.size() > capacity) invalidate(entries.firstKey()); + return texture; + } + + /** 释放匹配标识的 GPU 贴图,并将其从缓存移除。 */ + public void invalidate(Identifier id) { + RenderSystem.assertOnRenderThread(); + if (entries.remove(id) != null) textures.release(id); + } + + /** 在渲染线程释放缓存中的全部贴图,可在世界或资源切换时调用。 */ + public void clear() { + RenderSystem.assertOnRenderThread(); + while (!entries.isEmpty()) invalidate(entries.firstKey()); + } + + /** 释放当前贴图缓存,调用线程须为渲染线程。 */ + @Override + public void close() { + clear(); + } + + private static void checkHeader(Identifier id, byte[] bytes, Limits limits) throws IOException { + if (bytes.length < 33 || readInt(bytes, 0) != 0x89504e47 || readInt(bytes, 4) != 0x0d0a1a0a || readInt(bytes, 8) != 13 || readInt(bytes, 12) != 0x49484452) { + throw new IOException("贴图缺少有效的 PNG 标头 " + id); + } + int width = readInt(bytes, 16), height = readInt(bytes, 20); + if (width < 1 || height < 1 || width > limits.dimension() || height > limits.dimension() || (long) width * height > limits.pixels()) { + throw new IOException("贴图尺寸超出上限 " + id + " " + width + "×" + height); + } + } + + private static int readInt(byte[] data, int offset) { + return (data[offset] & 255) << 24 | (data[offset + 1] & 255) << 16 | (data[offset + 2] & 255) << 8 | data[offset + 3] & 255; + } + + /** 分别限制压缩数据、单边像素和总像素数。 */ + public record Limits(int bytes, int dimension, long pixels) { + + /** 创建图片解码限制。容量须为正数,字节上限还需保留一字节用于检测溢出输入。 */ + public Limits { + if (bytes < 1 || bytes == Integer.MAX_VALUE || dimension < 1 || pixels < 1) { + throw new IllegalArgumentException("贴图读取上限超出范围"); + } + } + } + + /** 限制等待中的请求数、单张图片的分块数、单块大小与组装总大小。 */ + public record RequestLimits(int requests, int parts, int partBytes, int imageBytes, Duration timeout) { + + /** 创建分块请求限制。各容量和超时长度均须为正。 */ + public RequestLimits { + if (requests < 1 || parts < 1 || partBytes < 1 || imageBytes < 1 || timeout.toNanos() <= 0) { + throw new IllegalArgumentException("图片请求的容量与超时必须为正数"); + } + } + } + + /** + * 按调用方的键组装乱序图片分块。各入口可由不同线程调用,完成后由调用方负责上传。 + * 同一个键重新发起时分配新的编号,迟到的旧数据随即失效。 + */ + public static final class Requests { + + private final RequestLimits limits; + private final long timeout; + private final Object2ObjectOpenHashMap pending = new Object2ObjectOpenHashMap<>(); + private long nextId; + + /** 创建带超时和并发限制的分块接收器。 */ + public Requests(RequestLimits limits) { + this.limits = limits; + timeout = limits.timeout().toNanos(); + } + + /** 新请求返回正编号。相同的键正在接收或已经达到并发上限时返回零。 */ + public synchronized long start(K key) { + return start(key, false); + } + + /** 替换同一个键的旧请求。达到并发上限且没有可替换的请求时返回零。 */ + public synchronized long restart(K key) { + return start(key, true); + } + + private long start(K key, boolean replace) { + long now = System.nanoTime(); + expire(now); + if (pending.containsKey(key) ? !replace : pending.size() >= limits.requests()) return 0; + nextId = Math.incrementExact(nextId); + pending.put(key, new PendingRequest(nextId, now + timeout)); + return nextId; + } + + /** 接收零基编号的数据。接收器复制获准的分块,调用方可在方法返回后复用原数组。 */ + public synchronized ReceiveResult receive(K key, long id, int index, int total, byte[] data) { + PendingRequest request = find(key, id); + if (request == null) return new ReceiveResult(ReceiveStatus.IGNORED, null); + if (index < 0 || index >= total || total > limits.parts() || data.length > limits.partBytes() || + (request.parts != null && request.parts.length != total)) { + pending.remove(key); + return new ReceiveResult(ReceiveStatus.REJECTED, null); + } + if (request.parts == null) request.parts = new byte[total][]; + if (request.parts[index] != null) return new ReceiveResult(ReceiveStatus.DUPLICATE, null); + if (data.length > limits.imageBytes() - request.bytes) { + pending.remove(key); + return new ReceiveResult(ReceiveStatus.REJECTED, null); + } + request.parts[index] = data.clone(); + request.bytes += data.length; + if (++request.received != total) return new ReceiveResult(ReceiveStatus.WAITING, null); + + pending.remove(key); + byte[] image = new byte[request.bytes]; + int offset = 0; + for (byte[] part : request.parts) { + System.arraycopy(part, 0, image, offset, part.length); + offset += part.length; + } + return new ReceiveResult(ReceiveStatus.COMPLETE, image); + } + + /** 完成一项已匹配的失败响应。过期请求和旧编号按迟到数据处理。 */ + public synchronized ReceiveResult fail(K key, long id) { + if (!cancel(key, id)) return new ReceiveResult(ReceiveStatus.IGNORED, null); + return new ReceiveResult(ReceiveStatus.FAILED, null); + } + + /** 取消相同键和编号的在途请求。存在有效请求时返回真。 */ + public synchronized boolean cancel(K key, long id) { + return find(key, id) != null && pending.remove(key) != null; + } + + /** 依据单调时钟移除过期请求及其已接收的数据。 */ + public synchronized void expire() { + expire(System.nanoTime()); + } + + /** 取消所有请求并丢弃暂存的分块,后续请求继续使用新的编号。 */ + public synchronized void clear() { + pending.clear(); + } + + private void expire(long now) { + pending.values().removeIf(request -> now - request.deadline >= 0); + } + + private @Nullable PendingRequest find(K key, long id) { + PendingRequest request = pending.get(key); + if (request == null || request.id != id) return null; + if (System.nanoTime() - request.deadline < 0) return request; + pending.remove(key); + return null; + } + + @RequiredArgsConstructor + private static final class PendingRequest { + + private final long id; + private final long deadline; + private byte @Nullable [][] parts; + private int bytes; + private int received; + } + } + + /** 接收或结束图片请求的结果。 */ + public enum ReceiveStatus { + /** 接收了一块数据,仍在等待后续分块。 */ + WAITING, + /** 此前已接收相同编号的分块,继续等待其他分块。 */ + DUPLICATE, + /** 全部分块已组装,返回完整图片。 */ + COMPLETE, + /** 匹配的请求以失败结束。 */ + FAILED, + /** 分块编号、数量或数据大小超出约定,请求已取消。 */ + REJECTED, + /** 响应对应的请求已经失效。 */ + IGNORED + } + + /** COMPLETE 时交付完整的字节数组,其余状态的图片数据为空。 */ + public record ReceiveResult(ReceiveStatus status, byte @Nullable [] image) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/client/texture/SpriteLookup.java b/src/main/java/com/modularmc/mmclutils/client/texture/SpriteLookup.java new file mode 100644 index 0000000..648069f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/texture/SpriteLookup.java @@ -0,0 +1,84 @@ +package com.modularmc.mmclutils.client.texture; + +import com.modularmc.mmclutils.client.model.QuadView; + +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jspecify.annotations.Nullable; + +import java.util.Collection; + +/** 用图集归一化 UV 反查贴图。图集重载后须用新贴图重建索引。 */ +public final class SpriteLookup { + + private static final int MAX_DEPTH = 12; + private final Node root = new Node(0, 0, 1, 0); + private final TextureAtlasSprite missing; + + /** 在当前图集上建立查询索引。资源重载后,须使用新图集重新创建。 */ + public SpriteLookup(TextureAtlas atlas) { + this(atlas.getTextures().values(), atlas.missingSprite()); + } + + /** 以给定的精灵集合建立索引,未命中时返回指定的缺失纹理。 */ + public SpriteLookup(Collection sprites, TextureAtlasSprite missing) { + this.missing = missing; + sprites.forEach(root::add); + } + + /** 用四个顶点的 UV 重心定位贴图。 */ + public TextureAtlasSprite find(QuadView quad) { + return find((quad.u(0) + quad.u(1) + quad.u(2) + quad.u(3)) * 0.25f, + (quad.v(0) + quad.v(1) + quad.v(2) + quad.v(3)) * 0.25f); + } + + /** 使用图集 UV 查找精灵。坐标越界或落在图集空白处时返回缺失纹理。 */ + public TextureAtlasSprite find(float u, float v) { + if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return missing; + TextureAtlasSprite sprite = root.find(u, v); + return sprite == null ? missing : sprite; + } + + private static final class Node { + + private final float x; + private final float y; + private final float size; + private final int depth; + private final ObjectArrayList sprites = new ObjectArrayList<>(); + private final Node[] children = new Node[4]; + + private Node(float x, float y, float size, int depth) { + this.x = x; + this.y = y; + this.size = size; + this.depth = depth; + } + + private void add(TextureAtlasSprite sprite) { + float half = size * 0.5f, midU = x + half, midV = y + half; + boolean crossesU = sprite.getU0() < midU && sprite.getU1() > midU; + boolean crossesV = sprite.getV0() < midV && sprite.getV1() > midV; + if (depth == MAX_DEPTH || crossesU || crossesV) { + sprites.add(sprite); + return; + } + int u = sprite.getU0() >= midU ? 1 : 0, v = sprite.getV0() >= midV ? 1 : 0; + int index = u | (v << 1); + if (children[index] == null) children[index] = new Node(x + u * half, y + v * half, half, depth + 1); + children[index].add(sprite); + } + + private @Nullable TextureAtlasSprite find(float u, float v) { + for (TextureAtlasSprite sprite : sprites) { + if (u >= sprite.getU0() && u < sprite.getU1() && v >= sprite.getV0() && v < sprite.getV1()) return sprite; + } + float half = size * 0.5f; + int index = (u >= x + half ? 1 : 0) | (v >= y + half ? 2 : 0); + Node child = children[index]; + return child == null ? null : child.find(u, v); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/texture/TextureMetadata.java b/src/main/java/com/modularmc/mmclutils/client/texture/TextureMetadata.java new file mode 100644 index 0000000..010bf5d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/texture/TextureMetadata.java @@ -0,0 +1,32 @@ +package com.modularmc.mmclutils.client.texture; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.metadata.MetadataSectionType; +import net.minecraft.server.packs.resources.ResourceManager; + +import java.io.IOException; +import java.util.Optional; + +/** 通过资源提供器读取指定的原版贴图元数据段。 */ +public final class TextureMetadata { + + private TextureMetadata() {} + + /** 将精灵标识映射为资源包内的 PNG 文件标识。 */ + public static Identifier textureFile(Identifier id) { + return id.withPath(path -> "textures/" + path + ".png"); + } + + /** 按精灵的源贴图查找指定元数据,资源或元数据段缺失时返回空结果。 */ + public static Optional readSprite(ResourceManager resources, TextureAtlasSprite sprite, MetadataSectionType type) + throws IOException { + return read(resources, textureFile(sprite.contents().name()), type); + } + + /** 读取当前资源优先级下的贴图元数据。资源缺失时返回空结果,读取失败时传播 I/O 异常。 */ + public static Optional read(ResourceManager resources, Identifier file, MetadataSectionType type) throws IOException { + var resource = resources.getResource(file); + return resource.isPresent() ? resource.get().metadata().getSection(type) : Optional.empty(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/VoxelShapeAccessor.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/VoxelShapeAccessor.java new file mode 100644 index 0000000..8917b8f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/VoxelShapeAccessor.java @@ -0,0 +1,20 @@ +package com.modularmc.mmclutils.mixin.mc; + +import net.minecraft.world.phys.shapes.DiscreteVoxelShape; +import net.minecraft.world.phys.shapes.VoxelShape; + +import org.jspecify.annotations.NullMarked; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +/** 供采集线程复制体素占用数据。 */ +@NullMarked +@Mixin(VoxelShape.class) +public interface VoxelShapeAccessor { + + /** + * 返回原版体素网格。调用方在拥有该形状的线程上读取网格。 + */ + @Accessor("shape") + DiscreteVoxelShape mmclutils$voxelGrid(); +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/GlBufferAccessor.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/GlBufferAccessor.java new file mode 100644 index 0000000..11f044f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/GlBufferAccessor.java @@ -0,0 +1,15 @@ +package com.modularmc.mmclutils.mixin.mc.client; + +import com.mojang.blaze3d.opengl.GlBuffer; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +/** 为渲染后端读取原版 GL 缓冲对象的驱动句柄。 */ +@Mixin(GlBuffer.class) +public interface GlBufferAccessor { + + /** 返回原版缓冲包装所持有的 OpenGL 缓冲标识。 */ + @Accessor("handle") + int mmclutils$handle(); +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/KeyBindsScreenMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/KeyBindsScreenMixin.java new file mode 100644 index 0000000..882985f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/KeyBindsScreenMixin.java @@ -0,0 +1,64 @@ +package com.modularmc.mmclutils.mixin.mc.client; + +import com.modularmc.mmclutils.client.input.ClientInput; +import com.modularmc.mmclutils.client.input.KeyChordMapping; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.gui.screens.options.controls.KeyBindsList; +import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.util.Util; + +import com.mojang.blaze3d.platform.InputConstants; +import org.jspecify.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** 将自定义组合键的录入交给客户端绑定模型解析与保存。 */ +@Mixin(KeyBindsScreen.class) +public abstract class KeyBindsScreenMixin { + + @Shadow + public @Nullable KeyMapping selectedKey; + @Shadow + public long lastKeySelection; + @Shadow + private KeyBindsList keyBindsList; + + @Inject(method = "keyPressed", at = @At("HEAD"), cancellable = true) + private void mmclutils$captureKey(KeyEvent event, CallbackInfoReturnable callback) { + if (!(selectedKey instanceof KeyChordMapping chord)) return; + InputConstants.Key key = InputConstants.getKey(event); + if (event.isEscape()) mmclutils$finish(chord, InputConstants.UNKNOWN, 0); + else if (ClientInput.keyModifierBit(key) == 0) mmclutils$finish(chord, key, ClientInput.modifiers()); + callback.setReturnValue(true); + } + + @Inject(method = "keyReleased", at = @At("HEAD"), cancellable = true) + private void mmclutils$releaseKey(KeyEvent event, CallbackInfoReturnable callback) { + if (!(selectedKey instanceof KeyChordMapping chord)) return; + InputConstants.Key key = InputConstants.getKey(event); + if (ClientInput.keyModifierBit(key) != 0) mmclutils$finish(chord, key, ClientInput.modifiers()); + callback.setReturnValue(true); + } + + @Inject(method = "mouseClicked", at = @At("HEAD"), cancellable = true) + private void mmclutils$captureMouse(MouseButtonEvent event, boolean doubleClick, CallbackInfoReturnable callback) { + if (!(selectedKey instanceof KeyChordMapping chord)) return; + mmclutils$finish(chord, InputConstants.Type.MOUSE.getOrCreate(event.button()), ClientInput.modifiers()); + callback.setReturnValue(true); + } + + @Unique + private void mmclutils$finish(KeyChordMapping chord, InputConstants.Key key, int modifiers) { + chord.setChord(key, modifiers); + selectedKey = null; + lastKeySelection = Util.getMillis(); + keyBindsList.resetMappingAndUpdateButtons(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/client/OptionsMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/OptionsMixin.java new file mode 100644 index 0000000..05778de --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/client/OptionsMixin.java @@ -0,0 +1,37 @@ +package com.modularmc.mmclutils.mixin.mc.client; + +import com.modularmc.mmclutils.client.input.KeyChordMapping; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Options; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** 在选项序列化流程中读写组合键的主键与修饰键。 */ +@Mixin(Options.class) +public abstract class OptionsMixin { + + @Shadow + public KeyMapping[] keyMappings; + + @Inject(method = "processOptions", at = @At("TAIL")) + private void mmclutils$processChords(Options.FieldAccess access, CallbackInfo callback) { + for (KeyMapping mapping : keyMappings) { + if (mapping instanceof KeyChordMapping chord) chord.processOptions(access); + } + } + + @WrapOperation(method = "load", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;processOptions(Lnet/minecraft/client/Options$FieldAccess;)V")) + private void mmclutils$readLegacyChords(Options options, Options.FieldAccess access, Operation original) { + original.call(options, access); + for (KeyMapping mapping : keyMappings) { + if (mapping instanceof KeyChordMapping chord) chord.readLegacyOptions(access); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/BlockEntityMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/BlockEntityMixin.java new file mode 100644 index 0000000..2706b0c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/BlockEntityMixin.java @@ -0,0 +1,26 @@ +package com.modularmc.mmclutils.mixin.mc.world; + +import com.modularmc.mmclutils.api.blockentity.BlockEntityTracking.TrackedBlockEntity; + +import net.minecraft.world.level.block.entity.BlockEntity; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +/** 在原版方块实体中保存由方块实体索引管理的探测位掩码。 */ +@Mixin(BlockEntity.class) +public abstract class BlockEntityMixin implements TrackedBlockEntity { + + @Unique + private int mmclutils$probed; + + @Override + public int mmclutils$probedMask() { + return mmclutils$probed; + } + + @Override + public void mmclutils$setProbedMask(int mask) { + mmclutils$probed = mask; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ClientChunkCacheMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ClientChunkCacheMixin.java new file mode 100644 index 0000000..c8cf286 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ClientChunkCacheMixin.java @@ -0,0 +1,41 @@ +package com.modularmc.mmclutils.mixin.mc.world; + +import com.modularmc.mmclutils.client.level.ClientChunkVisibility; +import com.modularmc.mmclutils.client.level.ClientChunkVisibility.View; + +import net.minecraft.client.multiplayer.ClientChunkCache; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** 在原版客户端视野中心和半径变化后更新方块实体索引可见范围。 */ +@Mixin(ClientChunkCache.class) +public abstract class ClientChunkCacheMixin { + + @Shadow + private volatile ClientChunkCache.Storage storage; + + @Unique + private ClientChunkCache.Storage mmclutils$previousStorage; + + @Inject(method = "updateViewCenter", at = @At("TAIL")) + private void mmclutils$afterCenter(int x, int z, CallbackInfo ci) { + ClientChunkVisibility.sync((View) (Object) storage); + } + + @Inject(method = "updateViewRadius", at = @At("HEAD")) + private void mmclutils$beforeRadius(int viewDistance, CallbackInfo ci) { + mmclutils$previousStorage = storage; + } + + @Inject(method = "updateViewRadius", at = @At("TAIL")) + private void mmclutils$afterRadius(int viewDistance, CallbackInfo ci) { + ClientChunkCache.Storage previous = mmclutils$previousStorage; + mmclutils$previousStorage = null; + ClientChunkVisibility.afterResize((View) (Object) storage, (View) (Object) previous); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ClientChunkStorageMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ClientChunkStorageMixin.java new file mode 100644 index 0000000..25351e7 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ClientChunkStorageMixin.java @@ -0,0 +1,34 @@ +package com.modularmc.mmclutils.mixin.mc.world; + +import com.modularmc.mmclutils.client.level.ClientChunkVisibility; + +import net.minecraft.world.level.chunk.LevelChunk; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.gen.Invoker; + +import java.util.concurrent.atomic.AtomicReferenceArray; + +/** 将原版客户端区块槽位与可见范围暴露给索引可见性同步逻辑。 */ +@Mixin(targets = "net.minecraft.client.multiplayer.ClientChunkCache$Storage") +public abstract class ClientChunkStorageMixin implements ClientChunkVisibility.View { + + @Shadow + @Final + private AtomicReferenceArray chunks; + + @Invoker("inRange") + protected abstract boolean mmclutils$contains(int x, int z); + + @Override + public AtomicReferenceArray mmclutils$chunks() { + return chunks; + } + + @Override + public boolean mmclutils$inRange(int x, int z) { + return mmclutils$contains(x, z); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/LevelChunkMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/LevelChunkMixin.java new file mode 100644 index 0000000..b1ed055 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/LevelChunkMixin.java @@ -0,0 +1,78 @@ +package com.modularmc.mmclutils.mixin.mc.world; + +import com.modularmc.mmclutils.api.blockentity.BlockEntityTracking; +import com.modularmc.mmclutils.api.blockentity.BlockEntityTracking.TrackedChunk; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.chunk.LevelChunk; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Slice; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.Map; + +/** 在区块的方块实体增删、替换和清理时维护空间索引登记。 */ +@Mixin(LevelChunk.class) +public abstract class LevelChunkMixin implements TrackedChunk { + + @Unique + private boolean mmclutils$hiddenFromIndex; + + @Shadow + public abstract Map getBlockEntities(); + + @Override + public boolean mmclutils$hidden() { + return mmclutils$hiddenFromIndex; + } + + @Override + public void mmclutils$setHidden(boolean hidden) { + mmclutils$hiddenFromIndex = hidden; + } + + @Inject(method = "setBlockEntity", + at = @At(value = "INVOKE", target = "Ljava/util/Map;put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;")) + private void mmclutils$beforeSet(BlockEntity be, CallbackInfo ci) { + if (mmclutils$hiddenFromIndex) return; + BlockEntity old = getBlockEntities().get(be.getBlockPos()); + if (old == be) return; + if (old != null) BlockEntityTracking.removed(old); + BlockEntityTracking.added(be); + } + + @Inject(method = "removeBlockEntity", + at = @At(value = "INVOKE", target = "Ljava/util/Map;remove(Ljava/lang/Object;)Ljava/lang/Object;")) + private void mmclutils$beforeRemove(BlockPos pos, CallbackInfo ci) { + if (mmclutils$hiddenFromIndex) return; + BlockEntity old = getBlockEntities().get(pos); + if (old != null) BlockEntityTracking.removed(old); + } + + @Inject(method = "getBlockEntity(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/chunk/LevelChunk$EntityCreationType;)Lnet/minecraft/world/level/block/entity/BlockEntity;", + slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/BlockEntity;isRemoved()Z")), + at = @At(value = "INVOKE", target = "Ljava/util/Map;remove(Ljava/lang/Object;)Ljava/lang/Object;")) + private void mmclutils$beforeDropRemoved(BlockPos pos, LevelChunk.EntityCreationType type, CallbackInfoReturnable cir) { + if (mmclutils$hiddenFromIndex) return; + BlockEntity old = getBlockEntities().get(pos); + if (old != null) BlockEntityTracking.removed(old); + } + + @Inject(method = "clearAllBlockEntities", at = @At("HEAD")) + private void mmclutils$beforeClear(CallbackInfo ci) { + if (mmclutils$hiddenFromIndex) { + mmclutils$hiddenFromIndex = false; + return; + } + Map map = getBlockEntities(); + if (map.isEmpty()) return; + for (BlockEntity be : map.values()) BlockEntityTracking.removed(be); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/LevelMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/LevelMixin.java new file mode 100644 index 0000000..89f7eed --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/LevelMixin.java @@ -0,0 +1,40 @@ +package com.modularmc.mmclutils.mixin.mc.world; + +import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder; + +import net.minecraft.world.level.Level; + +import org.jspecify.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +/** 让每个维度实例持有其 LevelStore 槽位与卸载状态。 */ +@Mixin(Level.class) +public abstract class LevelMixin implements SlotHolder { + + @Unique + private volatile @Nullable Object[] mmclutils$levelSlots; + + @Unique + private volatile boolean mmclutils$levelReleased; + + @Override + public @Nullable Object[] mmclutils$slots() { + return mmclutils$levelSlots; + } + + @Override + public void mmclutils$setSlots(@Nullable Object[] slots) { + mmclutils$levelSlots = slots; + } + + @Override + public boolean mmclutils$released() { + return mmclutils$levelReleased; + } + + @Override + public void mmclutils$setReleased(boolean released) { + mmclutils$levelReleased = released; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerChunkCacheMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerChunkCacheMixin.java new file mode 100644 index 0000000..1efbda3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerChunkCacheMixin.java @@ -0,0 +1,59 @@ +package com.modularmc.mmclutils.mixin.mc.world; + +import com.modularmc.mmclutils.api.level.LoadedChunks.RecentChunks; +import com.modularmc.mmclutils.api.level.LoadedChunks.Source; + +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.ChunkResult; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.LevelChunk; + +import org.jspecify.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.gen.Invoker; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** 为异步区块查询提供仅查已加载数据的服务端来源。 */ +@Mixin(ServerChunkCache.class) +public abstract class ServerChunkCacheMixin implements Source { + + @Shadow + @Final + private Thread mainThread; + + @Unique + private final RecentChunks mmclutils$recent = new RecentChunks<>(); + + @Shadow + public abstract @Nullable LevelChunk getChunkNow(int chunkX, int chunkZ); + + @Invoker("getVisibleChunkIfPresent") + protected abstract @Nullable ChunkHolder mmclutils$visibleChunk(long chunkPos); + + @Override + public @Nullable LevelChunk mmclutils$loadedChunk(int chunkX, int chunkZ) { + if (Thread.currentThread() == mainThread) return getChunkNow(chunkX, chunkZ); + long key = ChunkPos.pack(chunkX, chunkZ); + LevelChunk cached = mmclutils$recent.get(key); + if (cached != null) return cached; + ChunkHolder holder = mmclutils$visibleChunk(key); + if (holder == null) return null; + ChunkResult result = holder.getFullChunkFuture().getNow(null); + if (result == null) return null; + LevelChunk chunk = result.orElse(null); + if (chunk == null) return null; + mmclutils$recent.put(key, chunk); + return chunk; + } + + @Inject(method = "clearCache", at = @At("TAIL")) + private void mmclutils$clearRecent(CallbackInfo ci) { + mmclutils$recent.clear(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerLevelMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerLevelMixin.java new file mode 100644 index 0000000..f29e6f4 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/mc/world/ServerLevelMixin.java @@ -0,0 +1,22 @@ +package com.modularmc.mmclutils.mixin.mc.world; + +import com.modularmc.mmclutils.api.data.FastSavedData; + +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.ProgressListener; + +import org.jspecify.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** 在原版强制世界保存完成后等待紧凑二进制存档队列。 */ +@Mixin(ServerLevel.class) +public abstract class ServerLevelMixin { + + @Inject(method = "save", at = @At("RETURN")) + private void mmclutils$finishSave(@Nullable ProgressListener progress, boolean flush, boolean noSave, CallbackInfo callback) { + if (flush && !noSave) FastSavedData.flush((ServerLevel) (Object) this); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/utils/ArrayUtils.java b/src/main/java/com/modularmc/mmclutils/utils/ArrayUtils.java new file mode 100644 index 0000000..6c0eb5b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/utils/ArrayUtils.java @@ -0,0 +1,237 @@ +package com.modularmc.mmclutils.utils; + +import org.jetbrains.annotations.Contract; +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; +import java.util.Objects; + +import static org.apache.commons.lang3.ArrayUtils.isEmpty; + +/** 数组复制、等值检查和有序查找。 */ +public class ArrayUtils { + + /** + * 复制数组,并递归复制多维数组的各级子数组。 + * 输入为空时返回空值。 + * + *

+ * 非数组的引用元素沿用原引用。 + * + * @param array 待复制数组 + * @param 数组类型 + * @return 复制后的数组,输入为空时返回空值 + */ + @Contract(value = "!null -> !null; _ -> null", pure = true) + public static T @Nullable [] deepCopy(T @Nullable [] array) { + if (array == null) { + return null; + } + + T[] copy = array.clone(); + if (array.getClass().getComponentType().isArray()) { + for (int i = 0; i < array.length; ++i) { + copy[i] = copySubarray(array[i]); + } + } + + return copy; + } + + private static @Nullable T copySubarray(@Nullable T value) { + // clone 保留每个子数组的实际类型,与传入引用的类型一致。 + @SuppressWarnings("unchecked") + T copy = (T) switch (value) { + case null -> null; + case Object[] array -> deepCopy(array); + case boolean[] array -> array.clone(); + case byte[] array -> array.clone(); + case char[] array -> array.clone(); + case short[] array -> array.clone(); + case int[] array -> array.clone(); + case long[] array -> array.clone(); + case float[] array -> array.clone(); + case double[] array -> array.clone(); + default -> throw new IllegalArgumentException("需要数组类型的元素"); + }; + return copy; + } + + /** 检查全部元素是否相等。空值、空数组和单元素数组均视为匹配。 */ + public static boolean allMatch(boolean @Nullable [] array) { + if (isEmpty(array)) return true; + boolean firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement) return false; + } + return true; + } + + /** 检查全部元素是否相等。空值、空数组和单元素数组均视为匹配。 */ + public static boolean allMatch(byte @Nullable [] array) { + if (isEmpty(array)) return true; + byte firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement) return false; + } + return true; + } + + /** 检查全部元素是否相等。空值、空数组和单元素数组均视为匹配。 */ + public static boolean allMatch(char @Nullable [] array) { + if (isEmpty(array)) return true; + char firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement) return false; + } + return true; + } + + /** + * 比较浮点元素。正负零视为相等,NaN 只与 NaN 匹配。 + * + * @param array 待比较数组。空值、空数组和单元素数组均视为匹配 + * @return 全部元素是否与首元素匹配 + */ + public static boolean allMatch(double @Nullable [] array) { + if (isEmpty(array)) return true; + double firstElement = array[0]; + boolean firstIsNaN = Double.isNaN(firstElement); + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement && !(firstIsNaN && Double.isNaN(array[i]))) return false; + } + return true; + } + + /** + * 以首元素为基准比较绝对误差。同号无穷视为相等。多元素数组包含 NaN 时返回 {@code false}。 + * + * @param array 待比较数组。空值、空数组和单元素数组均视为匹配 + * @param tolerance 最大允许误差,须为有限非负数 + * @return 每个元素是否与首元素相同或误差在上限以内 + * @throws IllegalArgumentException 误差上限为负数或非有限值 + */ + public static boolean allMatch(double @Nullable [] array, double tolerance) { + if (!(tolerance >= 0) || !Double.isFinite(tolerance)) throw new IllegalArgumentException("容差须为有限非负数"); + if (isEmpty(array)) return true; + double firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + double element = array[i]; + if (element != firstElement && !(Math.abs(element - firstElement) <= tolerance)) return false; + } + return true; + } + + /** + * 比较浮点元素。正负零视为相等,NaN 只与 NaN 匹配。 + * + * @param array 待比较数组。空值、空数组和单元素数组均视为匹配 + * @return 全部元素是否与首元素匹配 + */ + public static boolean allMatch(float @Nullable [] array) { + if (isEmpty(array)) return true; + float firstElement = array[0]; + boolean firstIsNaN = Float.isNaN(firstElement); + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement && !(firstIsNaN && Float.isNaN(array[i]))) return false; + } + return true; + } + + /** + * 以首元素为基准比较绝对误差。同号无穷视为相等。多元素数组包含 NaN 时返回 {@code false}。 + * + * @param array 待比较数组。空值、空数组和单元素数组均视为匹配 + * @param tolerance 最大允许误差,须为有限非负数 + * @return 每个元素是否与首元素相同或误差在上限以内 + * @throws IllegalArgumentException 误差上限为负数或非有限值 + */ + public static boolean allMatch(float @Nullable [] array, float tolerance) { + if (!(tolerance >= 0) || !Float.isFinite(tolerance)) throw new IllegalArgumentException("容差须为有限非负数"); + if (isEmpty(array)) return true; + float firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + float element = array[i]; + if (element != firstElement && !(Math.abs(element - firstElement) <= tolerance)) return false; + } + return true; + } + + /** 检查全部元素是否相等。空值、空数组和单元素数组均视为匹配。 */ + public static boolean allMatch(int @Nullable [] array) { + if (isEmpty(array)) return true; + int firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement) return false; + } + return true; + } + + /** 检查全部元素是否相等。空值、空数组和单元素数组均视为匹配。 */ + public static boolean allMatch(long @Nullable [] array) { + if (isEmpty(array)) return true; + long firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement) return false; + } + return true; + } + + /** 使用 {@link Objects#equals} 比较元素。空值、空数组和单元素数组均视为匹配。 */ + public static boolean allMatch(Object @Nullable [] array) { + if (isEmpty(array)) return true; + Object firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + if (!Objects.equals(array[i], firstElement)) return false; + } + return true; + } + + /** 检查全部元素是否相等。空值、空数组和单元素数组均视为匹配。 */ + public static boolean allMatch(short @Nullable [] array) { + if (isEmpty(array)) return true; + short firstElement = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] != firstElement) return false; + } + return true; + } + + /** + * 二分查找严格小于给定值的最后一个元素。 + * + * @param array 按有符号长整数升序排列的数组,允许重复 + * @param value 查找上界,结果严格小于该值 + * @return 最后一个满足条件的下标,无匹配时返回 -1 + */ + public static int nearestLesser(long[] array, long value) { + return value == Long.MIN_VALUE ? -1 : nearestLesserOrEqual(array, value - 1); + } + + /** + * 二分查找小于或等于给定值的最后一个元素。 + * + * @param array 按有符号长整数升序排列的数组,允许重复 + * @param value 查找上界,结果可以等于该值 + * @return 最后一个满足条件的下标,无匹配时返回 -1 + */ + public static int nearestLesserOrEqual(long[] array, long value) { + int low = 0, high = array.length; + while (low < high) { + int mid = (low + high) >>> 1; + if (array[mid] <= value) low = mid + 1; + else high = mid; + } + return low - 1; + } + + /** 按元素顺序计算整型数组的哈希值。数组为空值时返回 0。 */ + public static int hashInts(int @Nullable... vals) { + return Arrays.hashCode(vals); + } + + /** 按元素顺序计算长整型数组的哈希值。数组为空值时返回 0。 */ + public static int hashLongs(long @Nullable... vals) { + return Arrays.hashCode(vals); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/utils/BlockPatternUtils.java b/src/main/java/com/modularmc/mmclutils/utils/BlockPatternUtils.java new file mode 100644 index 0000000..9940090 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/utils/BlockPatternUtils.java @@ -0,0 +1,91 @@ +package com.modularmc.mmclutils.utils; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; +import java.util.regex.Pattern; + +/** 解析并匹配可复用的正则表达式配置规则。 */ +public final class BlockPatternUtils { + + private BlockPatternUtils() {} + + /** 一条方块标识的正则规则及其倍率。 */ + public record MultiplierEntry(Pattern pattern, double value) {} + + /** 编译非空的方块标识正则,返回可反复匹配的不可变列表。无效正则会抛出异常。 */ + public static List precompilePatterns(List textPatterns) { + List patterns = new ObjectArrayList<>(textPatterns.size()); + for (String entry : textPatterns) { + if (entry.isBlank()) { + throw new IllegalArgumentException("方块黑名单的正则表达式不能为空"); + } + patterns.add(Pattern.compile(entry)); + } + return List.copyOf(patterns); + } + + /** 把格式为 {@code 表达式=倍率} 的配置解析为不可变规则列表。倍率接受表达式,结果须为有限正数。 */ + public static List precompileMultipliers(List textMultipliers) { + List entries = new ObjectArrayList<>(textMultipliers.size()); + for (String entry : textMultipliers) { + int separator = entry.lastIndexOf('='); + if (separator <= 0 || separator >= entry.length() - 1) { + throw new IllegalArgumentException("方块倍率须使用“表达式=倍率”格式,实际值为 " + entry); + } + String patternText = entry.substring(0, separator).trim(); + String valueText = entry.substring(separator + 1).trim(); + if (patternText.isEmpty()) { + throw new IllegalArgumentException("方块倍率的正则表达式不能为空,实际值为 " + entry); + } + double value = NumberUtils.parseDouble(valueText) + .orElseThrow(() -> new IllegalArgumentException("无法解析方块倍率 " + entry)); + if (value <= 0.0D) { + throw new IllegalArgumentException("方块倍率须为有限正数,实际值为 " + entry); + } + entries.add(new MultiplierEntry(Pattern.compile(patternText), value)); + } + return List.copyOf(entries); + } + + /** 逐项配对正则和倍率。两个数组长度须相同,倍率须为有限正数。 */ + public static List precompileMultipliers(String[] patterns, double[] values) { + if (patterns.length != values.length) { + throw new IllegalArgumentException("方块倍率的表达式和数值须一一对应"); + } + List entries = new ObjectArrayList<>(patterns.length); + for (int index = 0; index < patterns.length; index++) { + String patternText = patterns[index]; + if (patternText == null || patternText.isBlank()) { + throw new IllegalArgumentException("方块倍率的正则表达式不能为空"); + } + double value = values[index]; + if (!Double.isFinite(value) || value <= 0.0D) { + throw new IllegalArgumentException("方块倍率须为有限正数"); + } + entries.add(new MultiplierEntry(Pattern.compile(patternText), value)); + } + return List.copyOf(entries); + } + + /** 判断完整方块标识是否被任一正则完整匹配。 */ + public static boolean isBlockBlacklisted(String blockId, List blacklist) { + for (Pattern pattern : blacklist) { + if (pattern.matcher(blockId).matches()) { + return true; + } + } + return false; + } + + /** 返回匹配规则中的最大倍率,基础倍率为一。 */ + public static double getMultiplierForBlock(String blockId, List multipliers) { + double maxMultiplier = 1.0D; + for (MultiplierEntry entry : multipliers) { + if (entry.pattern().matcher(blockId).matches()) { + maxMultiplier = Math.max(maxMultiplier, entry.value()); + } + } + return maxMultiplier; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/utils/BlockPosUtils.java b/src/main/java/com/modularmc/mmclutils/utils/BlockPosUtils.java new file mode 100644 index 0000000..afa577a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/utils/BlockPosUtils.java @@ -0,0 +1,157 @@ +package com.modularmc.mmclutils.utils; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.GlobalPos; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.RandomAccess; +import java.util.function.Function; + +/** + * 把带坐标的对象排成原版逐格遍历的顺序,用索引替代逐格扫描时保持"先找到谁"的结果不变。功能: + *

    + *
  • {@link #betweenClosed}/{@link #sortBetweenClosed}:{@code BlockPos.betweenClosed} 的顺序,x 最快、其次 y、z 最慢,都从小到大
  • + *
  • {@link #withinManhattan}/{@link #sortWithinManhattan}:{@code BlockPos.withinManhattan} 的顺序,先按到中心的曼哈顿距离, + * 再按 x、y 从小到大,z 偏移为正的排在为负的前面
  • + *
  • {@link #sortWithinManhattan} 在条目不超过 2^20 个且坐标都在中心 ±63 格内时用打包长整数排序,不比较对象; + * {@link #sortBetweenClosed} 在条目不超过 2^20 个且三轴跨度合计不超过 43 位时同样打包排序;其余情况退回比较器
  • + *
  • 排序稳定性:坐标相同的条目保持原有相对顺序
  • + *
+ */ +public final class BlockPosUtils { + + private BlockPosUtils() {} + + /** 按原版闭合区间的遍历顺序比较元素坐标。 */ + public static Comparator betweenClosed(Function pos) { + return (a, b) -> { + BlockPos pa = pos.apply(a), pb = pos.apply(b); + int c = Integer.compare(pa.getZ(), pb.getZ()); + if (c != 0) return c; + c = Integer.compare(pa.getY(), pb.getY()); + if (c != 0) return c; + return Integer.compare(pa.getX(), pb.getX()); + }; + } + + /** 原地稳定排序。排序期间坐标提取函数应对同一个元素返回相同坐标。 */ + public static void sortBetweenClosed(List list, Function pos) { + int n = list.size(); + if (n < 2) return; + if (!(list instanceof RandomAccess) || n > (1 << 20) || !sortClosedPacked(list, pos)) list.sort(betweenClosed(pos)); + } + + @SuppressWarnings("unchecked") + private static boolean sortClosedPacked(List list, Function pos) { + int n = list.size(); + int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE, maxZ = Integer.MIN_VALUE; + for (T t : list) { + BlockPos p = pos.apply(t); + minX = Math.min(minX, p.getX()); + minY = Math.min(minY, p.getY()); + minZ = Math.min(minZ, p.getZ()); + maxX = Math.max(maxX, p.getX()); + maxY = Math.max(maxY, p.getY()); + maxZ = Math.max(maxZ, p.getZ()); + } + int bx = bits((long) maxX - minX), by = bits((long) maxY - minY), bz = bits((long) maxZ - minZ); + if (bx + by + bz > 43) return false; + long[] keys = new long[n]; + for (int i = 0; i < n; i++) { + BlockPos p = pos.apply(list.get(i)); + long k = (((long) p.getZ() - minZ) << (by + bx)) | (((long) p.getY() - minY) << bx) | ((long) p.getX() - minX); + keys[i] = k << 20 | i; + } + Arrays.sort(keys); + Object[] items = list.toArray(); + for (int i = 0; i < n; i++) { + list.set(i, (T) items[(int) (keys[i] & 0xFFFFF)]); + } + return true; + } + + private static int bits(long span) { + return 64 - Long.numberOfLeadingZeros(span); + } + + /** 按相对中心坐标的曼哈顿距离及原版遍历顺序比较元素。 */ + public static Comparator withinManhattan(BlockPos center, Function pos) { + long cx = center.getX(), cy = center.getY(), cz = center.getZ(); + return (a, b) -> { + BlockPos pa = pos.apply(a), pb = pos.apply(b); + long ax = pa.getX() - cx, ay = pa.getY() - cy, az = pa.getZ() - cz; + long bx = pb.getX() - cx, by = pb.getY() - cy, bz = pb.getZ() - cz; + int c = Long.compare(Math.abs(ax) + Math.abs(ay) + Math.abs(az), Math.abs(bx) + Math.abs(by) + Math.abs(bz)); + if (c != 0) return c; + c = Long.compare(ax, bx); + if (c != 0) return c; + c = Long.compare(ay, by); + if (c != 0) return c; + return Long.compare(bz, az); + }; + } + + /** 以指定坐标为中心原地稳定排序,使元素顺序与原版曼哈顿遍历一致。 */ + public static void sortWithinManhattan(List list, BlockPos center, Function pos) { + int n = list.size(); + if (n < 2) return; + if (list instanceof RandomAccess && n <= (1 << 20) && withinPackedRange(list, center, pos)) { + sortPacked(list, center, pos); + } else { + list.sort(withinManhattan(center, pos)); + } + } + + private static boolean withinPackedRange(List list, BlockPos center, Function pos) { + int cx = center.getX(), cy = center.getY(), cz = center.getZ(); + for (T t : list) { + BlockPos p = pos.apply(t); + if (Math.abs((long) p.getX() - cx) > 63 || Math.abs((long) p.getY() - cy) > 63 || Math.abs((long) p.getZ() - cz) > 63) { + return false; + } + } + return true; + } + + @SuppressWarnings("unchecked") + private static void sortPacked(List list, BlockPos center, Function pos) { + int n = list.size(); + int cx = center.getX(), cy = center.getY(), cz = center.getZ(); + long[] keys = new long[n]; + for (int i = 0; i < n; i++) { + BlockPos p = pos.apply(list.get(i)); + int dx = p.getX() - cx, dy = p.getY() - cy, dz = p.getZ() - cz; + long d = Math.abs(dx) + Math.abs(dy) + Math.abs(dz); + keys[i] = d << 41 | (long) (dx + 64) << 34 | (long) (dy + 64) << 27 | (long) (64 - dz) << 20 | i; + } + Arrays.sort(keys); + Object[] items = list.toArray(); + for (int i = 0; i < n; i++) { + list.set(i, (T) items[(int) (keys[i] & 0xFFFFF)]); + } + } + + /** 计算两个打包坐标的平方距离,中间乘积使用 long。 */ + public static long distanceSquared(long first, long second) { + long dx = BlockPos.getX(first) - BlockPos.getX(second); + long dy = BlockPos.getY(first) - BlockPos.getY(second); + long dz = BlockPos.getZ(first) - BlockPos.getZ(second); + return dx * dx + dy * dy + dz * dz; + } + + /** 返回两个打包方块坐标之间的欧氏距离,单位为方块。 */ + public static double distance(long first, long second) { + return Math.sqrt(distanceSquared(first, second)); + } + + /** 用维度标识和原版打包坐标构建全局位置。坐标为零时表示该维度的原点。 */ + public static GlobalPos globalPos(Identifier dimension, long packedPos) { + return GlobalPos.of(ResourceKey.create(Registries.DIMENSION, dimension), BlockPos.of(packedPos)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/utils/CollectionUtils.java b/src/main/java/com/modularmc/mmclutils/utils/CollectionUtils.java new file mode 100644 index 0000000..df42f88 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/utils/CollectionUtils.java @@ -0,0 +1,46 @@ +package com.modularmc.mmclutils.utils; + +import it.unimi.dsi.fastutil.objects.ObjectImmutableList; +import it.unimi.dsi.fastutil.objects.ObjectList; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import it.unimi.dsi.fastutil.objects.ObjectSet; +import it.unimi.dsi.fastutil.objects.ObjectSets; + +import java.util.Collection; + +/** 将列表和集合复制为不可变容器,可复用本库已持有的不可变副本。 */ +public final class CollectionUtils { + + private CollectionUtils() {} + + /** 以迭代顺序复制元素并返回不可变列表。已有不可变副本可以直接复用。 */ + public static ObjectList immutableList(Collection source) { + if (source.isEmpty()) return ObjectList.of(); + if (source instanceof ObjectImmutableList) { + // 不可变列表可以按更宽的元素类型读取。 + @SuppressWarnings("unchecked") + ObjectList immutable = (ObjectList) source; + return immutable; + } + return new ObjectImmutableList<>(source); + } + + /** 按相等性去重并返回不可变集合。元素引用沿用源集合,迭代顺序由散列表决定。 */ + public static ObjectSet immutableSet(Collection source) { + if (source.isEmpty()) return ObjectSets.emptySet(); + if (source instanceof ImmutableSetCopy) { + // 后备集合为该副本独有,可直接复用。 + @SuppressWarnings("unchecked") + ObjectSet immutable = (ObjectSet) source; + return immutable; + } + return new ImmutableSetCopy<>(new ObjectOpenHashSet<>(source)); + } + + private static final class ImmutableSetCopy extends ObjectSets.UnmodifiableSet { + + private ImmutableSetCopy(ObjectSet owned) { + super(owned); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/utils/ColorUtils.java b/src/main/java/com/modularmc/mmclutils/utils/ColorUtils.java new file mode 100644 index 0000000..b7b1bd9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/utils/ColorUtils.java @@ -0,0 +1,172 @@ +package com.modularmc.mmclutils.utils; + +import net.minecraft.util.ARGB; +import net.minecraft.util.Mth; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.level.material.MapColor; + +import it.unimi.dsi.fastutil.ints.IntIntPair; + +/** 颜色分量、颜色空间和分段渐变。颜色按 ARGB 打包。 */ +public final class ColorUtils { + + private static final DyeColor[] DYE_COLORS = DyeColor.values(); + + private ColorUtils() {} + + /** 将给定透明度和低 24 位的 RGB 合成为 ARGB。 */ + public static int withAlpha(int rgb, int alpha) { + return ARGB.color(alpha, rgb); + } + + /** 输入只含 RGB 分量时补上透明度,已有非零透明度的颜色直接返回。 */ + public static int withDefaultAlpha(int color, int alpha) { + return ARGB.alpha(color) == 0 ? withAlpha(color, alpha) : color; + } + + /** 以 0~1 的比例逐通道插值 ARGB,并四舍五入到整数分量。 */ + public static int interpolate(int from, int to, float amount) { + return ARGB.color( + Math.round(Mth.lerp(amount, ARGB.alpha(from), ARGB.alpha(to))), + Math.round(Mth.lerp(amount, ARGB.red(from), ARGB.red(to))), + Math.round(Mth.lerp(amount, ARGB.green(from), ARGB.green(to))), + Math.round(Mth.lerp(amount, ARGB.blue(from), ARGB.blue(to)))); + } + + /** 交换红色与蓝色通道,保持透明度和绿色通道。 */ + public static int swapRedBlue(int argb) { + return ARGB.toABGR(argb); + } + + /** 将最高字节的透明度移到最低字节。 */ + public static int argbToRgba(int argb) { + return Integer.rotateLeft(argb, 8); + } + + /** 返回归一化到 0~1 的红、绿、蓝三个分量。 */ + public static float[] rgb(int argb) { + return new float[] { ARGB.redFloat(argb), ARGB.greenFloat(argb), ARGB.blueFloat(argb) }; + } + + /** 两个 RGBA 值中位置相同的分量相乘,结果仍按 RGBA 排列。 */ + public static int multiplyRgba(int first, int second) { + return ARGB.multiply(first, second); + } + + /** 以 RGB 分量的平方距离匹配最接近的染料文字颜色。 */ + public static DyeColor nearestDyeColor(int rgb) { + DyeColor nearest = DYE_COLORS[0]; + int bestDistance = Integer.MAX_VALUE; + for (DyeColor color : DYE_COLORS) { + int distance = rgbDistanceSquared(rgb, color.getTextColor()); + if (distance < bestDistance) { + bestDistance = distance; + nearest = color; + } + } + return nearest; + } + + /** 在原版地图的六位色表中匹配最接近的可见色。 */ + public static MapColor nearestMapColor(int rgb) { + MapColor nearest = MapColor.NONE; + int bestDistance = Integer.MAX_VALUE; + for (int id = 1; id < 64; id++) { + MapColor color = MapColor.byId(id); + if (color == MapColor.NONE) continue; + int distance = rgbDistanceSquared(rgb, color.calculateARGBColor(MapColor.Brightness.NORMAL)); + if (distance < bestDistance) { + bestDistance = distance; + nearest = color; + } + } + return nearest; + } + + private static int rgbDistanceSquared(int first, int second) { + int red = ARGB.red(first) - ARGB.red(second); + int green = ARGB.green(first) - ARGB.green(second); + int blue = ARGB.blue(first) - ARGB.blue(second); + return red * red + green * green + blue * blue; + } + + /** 按相同透明度填充两种 RGB 之间的均匀色阶,色阶数至少为二并包含两端颜色。 */ + public static int[] stepGradient(int from, int to, int alpha, int steps) { + if (steps < 2) throw new IllegalArgumentException("渐变至少需要两个色阶"); + int[] result = new int[steps]; + for (int index = 0; index < steps; index++) { + float amount = (float) index / (steps - 1); + result[index] = ARGB.color(alpha, + Math.round(Mth.lerp(amount, ARGB.red(from), ARGB.red(to))), + Math.round(Mth.lerp(amount, ARGB.green(from), ARGB.green(to))), + Math.round(Mth.lerp(amount, ARGB.blue(from), ARGB.blue(to)))); + } + return result; + } + + /** 从色板按归一化进度选出相邻色阶并插值。色板至少一个颜色。 */ + public static int gradient(int[] stops, float position) { + if (stops.length == 0) throw new IllegalArgumentException("渐变至少需要一种颜色"); + float scaled = Mth.clamp(position, 0f, 1f) * (stops.length - 1); + int first = (int) scaled; + return first == stops.length - 1 ? stops[first] : interpolate(stops[first], stops[first + 1], scaled - first); + } + + /** 将色相、饱和度和亮度转换成 ARGB。色相以一圈为 1。 */ + public static int fromHsl(float hue, float saturation, float lightness, int alpha) { + float turn = hue - (float) Math.floor(hue); + float sat = Mth.clamp(saturation, 0f, 1f); + float light = Mth.clamp(lightness, 0f, 1f); + float chroma = (1 - Math.abs(2 * light - 1)) * sat; + return ARGB.color(alpha, hslChannel(turn, chroma, light, 0), hslChannel(turn, chroma, light, 8), + hslChannel(turn, chroma, light, 4)); + } + + /** 根据归一化 HSL 及指定透明度生成 ARGB。 */ + public static int fromHsl(Hsl hsl, int alpha) { + return fromHsl(hsl.hue(), hsl.saturation(), hsl.lightness(), alpha); + } + + /** 取得归一化的 HSL 分量。灰阶的色相与饱和度均为零。 */ + public static Hsl toHsl(int argb) { + int red = ARGB.red(argb); + int green = ARGB.green(argb); + int blue = ARGB.blue(argb); + int maximum = Math.max(red, Math.max(green, blue)); + int minimum = Math.min(red, Math.min(green, blue)); + int chroma = maximum - minimum; + float lightness = (maximum + minimum) / 510f; + if (chroma == 0) return new Hsl(0, 0, lightness); + + float hue; + if (maximum == red) { + hue = (green - blue) / (float) chroma; + } else if (maximum == green) { + hue = 2 + (blue - red) / (float) chroma; + } else { + hue = 4 + (red - green) / (float) chroma; + } + if (hue < 0) hue += 6; + float saturation = chroma / (255f - Math.abs(maximum + minimum - 255)); + return new Hsl(hue / 6, saturation, lightness); + } + + /** 从原色的亮度减去和加上同一偏移量,依次返回暗色和亮色并保留透明度。 */ + public static IntIntPair lightnessGradient(int argb, float difference) { + if (!(difference >= 0)) throw new IllegalArgumentException("亮度偏移量须为非负数"); + Hsl hsl = toHsl(argb); + int alpha = ARGB.alpha(argb); + int dark = fromHsl(hsl.hue(), hsl.saturation(), hsl.lightness() - difference, alpha); + int light = fromHsl(hsl.hue(), hsl.saturation(), hsl.lightness() + difference, alpha); + return IntIntPair.of(dark, light); + } + + private static int hslChannel(float hue, float chroma, float lightness, int offset) { + float phase = (offset + 12 * hue) % 12; + float weight = Math.max(-1, Math.min(Math.min(phase - 3, 9 - phase), 1)); + return Math.round(255 * (lightness - chroma * weight / 2)); + } + + /** 色相以圈为单位,饱和度与亮度使用 0~1。 */ + public record Hsl(float hue, float saturation, float lightness) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/utils/ComponentUtils.java b/src/main/java/com/modularmc/mmclutils/utils/ComponentUtils.java new file mode 100644 index 0000000..2028e39 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/utils/ComponentUtils.java @@ -0,0 +1,198 @@ +package com.modularmc.mmclutils.utils; + +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 org.jspecify.annotations.NullMarked; + +import java.util.Iterator; +import java.util.List; +import java.util.StringJoiner; +import java.util.function.UnaryOperator; +import java.util.stream.Collector; + +/** 组合原版文本组件,保留子组件的样式和翻译信息。 */ +@NullMarked +public final class ComponentUtils { + + private ComponentUtils() {} + + /** + * 将方块状态属性及其原版序列化值组成一个可显示的组件。布尔值使用绿色和红色区分。 + * + * @param property 要显示的属性 + * @param value 属于该属性的值 + * @return 属性名称和带样式的值 + */ + public static MutableComponent propertyText(Property property, Comparable value) { + MutableComponent text = Component.literal(Util.getPropertyName(property, value)); + if (value instanceof Boolean flag) text.withStyle(flag ? ChatFormatting.GREEN : ChatFormatting.RED); + return Component.literal(property.getName()).append(": ").append(text); + } + + /** 将长整数按紧凑数值格式封装为字面组件。 */ + public static MutableComponent numberText(long value) { + return Component.literal(NumberUtils.format(value)); + } + + /** 将浮点数按紧凑数值格式封装为字面组件。 */ + public static MutableComponent numberText(double value) { + return Component.literal(NumberUtils.format(value)); + } + + /** 用翻译键显示百分数,数字部分最多两位小数。 */ + public static MutableComponent percentText(String translationKey, double percent) { + return Component.translatable(translationKey, NumberUtils.formatTwoDecimals(percent)); + } + + /** 创建可继续添加行的列表,首行使用字面文本。 */ + public static List literalLine(String text) { + var lines = new ObjectArrayList(1); + lines.add(Component.literal(text)); + return lines; + } + + /** 创建只含一行长整数文本的可修改列表。 */ + public static List literalLine(long value) { + return literalLine(Long.toString(value)); + } + + /** 创建只含一行浮点数文本的可修改列表。 */ + public static List literalLine(double value) { + return literalLine(Double.toString(value)); + } + + /** 将各行解析为纯文本并以换行连接。 */ + public static String plainText(Iterable lines) { + StringJoiner text = new StringJoiner("\n"); + for (Component line : lines) text.add(line.getString()); + return text.toString(); + } + + /** 解析一行整数。空列表视作零,多行或无效数值抛出 NumberFormatException。 */ + public static int parseInt(List lines) { + return lines.isEmpty() ? 0 : Integer.parseInt(singleLineText(lines)); + } + + /** 解析一行浮点数。空列表视作零,多行或无效数值抛出 NumberFormatException。 */ + public static double parseDouble(List lines) { + return lines.isEmpty() ? 0 : Double.parseDouble(singleLineText(lines)); + } + + private static String singleLineText(List lines) { + if (lines.size() != 1) throw new NumberFormatException("数值文本须为单行"); + return lines.getFirst().getString(); + } + + /** 把首行接到目标末行,其余行逐行添加。目标允许为空,待追加的行由独立列表提供。 */ + public static void appendLines(List target, List lines) { + Iterator remaining = lines.iterator(); + if (!remaining.hasNext()) return; + if (target.isEmpty()) target.add(Component.empty()); + target.getLast().append(remaining.next()); + while (remaining.hasNext()) target.add(Component.empty().append(remaining.next())); + } + + /** 两个组件都有内容时插入分隔符。 */ + public static MutableComponent appendSeparated(MutableComponent target, Component addition, Component separator) { + if (!hasContent(addition)) return target; + if (hasContent(target)) target.append(separator); + return target.append(addition); + } + + private static boolean hasContent(Component component) { + return component.getContents() != PlainTextContents.EMPTY || !component.getSiblings().isEmpty(); + } + + /** 以带引号的条目预览列表。超过五项时保留首尾各两项。 */ + public static MutableComponent previewList(List entries, Style entryStyle) { + List preview = new ObjectArrayList<>(Math.min(5, entries.size())); + if (entries.size() <= 5) { + for (String entry : entries) preview.add(quoted(entry, entryStyle)); + } else { + preview.add(quoted(entries.getFirst(), entryStyle)); + preview.add(quoted(entries.get(1), entryStyle)); + preview.add(Component.literal("…")); + preview.add(quoted(entries.get(entries.size() - 2), entryStyle)); + preview.add(quoted(entries.getLast(), entryStyle)); + } + return Component.literal("[").append(join(preview, Component.literal(", "))).append("]"); + } + + private static MutableComponent quoted(String entry, Style style) { + return Component.literal('"' + entry + '"').withStyle(style); + } + + /** 按迭代顺序拼接组件,在相邻项之间插入分隔符。各子组件的翻译和样式得以保留。 */ + public static MutableComponent join(Iterable components, Component separator) { + Iterator iterator = components.iterator(); + MutableComponent result = Component.empty(); + if (iterator.hasNext()) result.append(iterator.next()); + while (iterator.hasNext()) result.append(separator).append(iterator.next()); + return result; + } + + /** 创建与 {@link #join} 一致的流收集器,保留来源的相遇顺序。 */ + public static Collector joining(Component separator) { + return Collector.of( + ObjectArrayList::new, + List::add, + (left, right) -> { + left.addAll(right); + return left; + }, + parts -> join(parts, separator)); + } + + /** 按 Tick 从色板选定颜色。每种颜色须持续至少一个 Tick,色板须包含至少一种颜色。 */ + public static UnaryOperator