From ebfef1a52de00f0a1b9c14cab1bf3672c2c5c0b4 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 00:22:34 +0800 Subject: [PATCH 01/79] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E5=BA=93=E5=B7=A5=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 3 +- build.gradle | 42 +-------- dependencies.gradle | 5 +- gradle.properties | 10 +-- gradle/libs.versions.toml | 22 +++-- gradle/scripts/jars.gradle | 2 +- gradle/scripts/moddevgradle.gradle | 50 ----------- gradle/wrapper/gradle-wrapper.jar | Bin 45633 -> 49154 bytes gradle/wrapper/gradle-wrapper.properties | 4 +- gradlew | 6 +- gradlew.bat | 85 +++++++++++------- settings.gradle | 5 +- .../ModularMCLibUtils.java} | 14 +-- .../mixin/MMCLibUtilsMixinConfig.java | 5 ++ .../template/mixin/TemplateMixinConfig.java | 70 --------------- .../resources/assets/template/lang/en_us.json | 5 -- src/main/resources/mmclutils.mixins.json | 15 ++++ src/main/resources/template.mixins.json | 16 ---- 18 files changed, 116 insertions(+), 243 deletions(-) rename src/main/java/com/modularmc/{template/Template.java => mmclutils/ModularMCLibUtils.java} (60%) create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/MMCLibUtilsMixinConfig.java delete mode 100644 src/main/java/com/modularmc/template/mixin/TemplateMixinConfig.java delete mode 100644 src/main/resources/assets/template/lang/en_us.json create mode 100644 src/main/resources/mmclutils.mixins.json delete mode 100644 src/main/resources/template.mixins.json 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/build.gradle b/build.gradle index 79ecb17..f187d92 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 @@ -88,35 +83,4 @@ tasks.withType(Test).configureEach { 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/**') - })) - } -} +} \ No newline at end of file diff --git a/dependencies.gradle b/dependencies.gradle index 374cb52..84f58d9 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,7 +1,10 @@ dependencies { compileOnly(libs.jetbrains.annotations) + compileOnly(libs.jspecify) - testImplementation(libs.testframework.get()) + 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..1df33c1 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,23 +1,31 @@ [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" +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" } [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" } \ No newline at end of file diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index e09356e..68f1c5d 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -28,7 +28,7 @@ afterEvaluate { tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { destinationDirectory = file('build/libs/') manifest.attributes([ - 'MixinConfigs': "synceddata.mixins.json", + 'MixinConfigs': "mmclutils.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..a2ecc5e 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,12 @@ 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. - gameTestServer { - type = "gameTestServer" - sourceSet = sourceSets.test - 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()) } // 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 f8e1ee3125fe0768e9a76ee977ac089eb657005e..51cbd2a6f8121b2ce12daf979b128058fb9672ee 100644 GIT binary patch delta 40950 zcmX6^^FwF<)2%k!wr#uKxy`n1ySv%8ZEW_|W_z>E&Dz@P+0Xa+<^BP$J9FloGiUk_ zA%eesX|O{EJmSUR2Ut-hpMy5ZV4Q=yE}6BH#PuLsyW-ATpcgnP#lAb)VnMnH+<$z2 zPuBFpCFeX1A$Azi^p}-o;|=+;PHVu`>PE{Q@S-> zA1+vr^!W4QG5kOHveoz!O z&%sX5Oo-O|wu7csfnrs>id<%1O^L~ygeS%Q_Z78$GI=BvkWAAbBJz`jN>Oqi&-+IB zn2n^s=^Bjnn*sRj#iRWL?X@z~_^>OZ2DzWA1@{WHd|v0AC0pawI4btgF+_|qlMGYL z1h#8#AzdZSJ!ea1#B29KD!__IYW05lEL;_9Vj|hQtBEc3Zt`hQTd+oc~jY(HhB5TRita zhJolFBly4i!2WwFrW0QYbZ{^*t^Zz%A>}(GN{T@_7GR;Or-UJf`4OJZ?2sWpDR~pz zVQ5`sp(4tFYXnO#3vLDnc`)hjwT^sQwzgF~BC|hxgY#002A7Rn@J{prXEf9tBLm06 zagzII<~i?=W#Gr3SE8Sc*tpxje+x1En6KVkMT@VRwv$p|unxE5DI5NB#xJ?S1+^q( z0(XVLZx1;4S#yRq9<^hh(w3dWZp}(bEF%q#BFnl`uALs(kho(Ud2~lW@0%nm zCYFvlt59Z48YX70;ZBw%LBq`YkQ?pTv7pX6fNHek+f}-cz96eVWPw%1dOlPcoqsUG zh7UZqxbUG8f7cZc8kwUSWONn^FVgRIm^%U? zWyp|9y&a54)#1RLeunqgeL?(f_JUD=d2s&ucb#kmZz3gvmc3_m3{tWkFVNWXh$9@q z$l2+BaQ=IO#8S{(i{-pasEa%8srne~-x1p5s(jKtZ%zrufsqf0|LRe2Hnh$K;tLp9 zZb}e_5n%9N6$&k4r!$w8k-yY+1V5!@!^)P8K+5{t{){x8h{?KAoLtyiv-HHFl0yGX zK*=nm%zpXuS7l^_nN~a{JkR|2D$i|J$n9k2`_2vkp)C=#xA^ffc@9%DJ{_N!-e{l6 zRAQc)ztKuWyqeG0oliCPJ(Qw@#o8_B&B9F&$RrYR4>0Q-CNfHmb?m;pb6mS}6U6Lk z9fPZ>rn#+~a~W%7NL8vmtYl_n64YfEjt^oxB`~b~db{Zf30hP8EvM%)iH5b<$WW7i z;cBzwKxgQDguvCl03WJ*{q*n$A04r*h-|(I?MBoZ*8-R4Qw%ru6)#wLlV4KJ3^%|O zkQeZtU@ag(o^@g$a{Dul>0at?ohf62I8G^*Xp-sv$51U1A4_7?ICEyn>xKC{uYMZ? zK~R%LclwTL=FK6{Q3u`uo@9lU|6NAHyPDa3XcSapI2r%2J?_?zUye6K>Hw1G(m%IJ zQjz_Bn%S?>C8bpFb63he3%zt>`heIB3_{v7KT(G0+@aGb8@? ztQRG6Sfu3Hf-P)v)Q^W&D|dMcWr`C%B9pO~iEwYdpY4VpoZL9bSSZ=ONURdH$rLyk z!UF?fT(k&?do~sHO5=h4qWo7|lxIv|q#?k-a#9*niBew4s8SdzD1lZD2en0Q%s^&R zy2eV(9WM{NOI>S%>N|2}e{f7pgpL>%wNbni?jH^mHVd+>1qYXyxv&oB)F@Eo3& zk2xG4l^#mT#iB_s78NO_&zmQ?Z<}rfZdaqg&c_#HND;Qby}cjzFW=>o>}m!W=~ALK zHQA#rm(IKT4Yt^qvH=Zr^Y$>Z4hrk02_lUec!wpMUxXG-Q%KV0slJkRw_Vk5Y|IFT z#CxHwqwVjLNQ0z<@+Jb9X^01)63}4DgcBMow9l~ZYIf!#Qa`KZTAKavF%`(13p6{U z+ltR4@3V!8((xNsfQ@1zUBP<8MGJp;xhIr4+^(p1(!)t_5wP2I)X~(xf`{8e+;Y_L zLeIcU_1DfMEUIu<^KxRHLJ1vwCii!v1wr!^-`C)lU zF@l{g<7~|;egSvEJ8{_)%@-r4)Th+kWUXzLKCZT@%L>{uF;*&hLCX-dlnsxX8@jsN zDVq`tA6&=zD|~0KrG{x^?kgikAF_HKDozoKU|r!31m90j$ON6!ynF1}bT3rGE&jNd z!>GeFwBT*c*!>FPk;_Mx!kuYV#c-k$&G383TVSs#?N4jhO5>z{H_*3 z5fw3Jyz-hlN?6{5x`M}_3_{!7#MpEDL4;|t9>Y3_>Qd)GM?zxlMRw`1dE4N|9xk-J z_xth#(2{UV*qgoSZK=sc;lBfW78yV8jfFbI>#{tnFYJ2$DIce+vWns}-;L%AS68RX z_h$B>l8|}|Z8rMalP>$o|MTDXnhKw4PF938o4$0XkSA|#V7^aKF#T*xVMo#T)j2l* z=Ydo7qU4Tkb=1c|@`=kGm#@*m+Z1)`vkWGHEwbx7!GrWSNE@RHA})MkR!y&?X@1DL zC~AIy>s+%!GQgvA73Cb!BRR? zF;hAzsZ#PQsDLz08!rqE+(5@1b_d*~mT&4}Bd~4L3&jx2O)^!5t1Xf-zl^cU#~t|H z*)goBnLPRfh66^SyqrbOWfx0wO9Jmgb{KJHYcfgZZxaeUjvvV-8mb7(h- zCkWu{2WE55ywoG)VOjOLuaEhjm`oEDyt;N8IVlF`(s|_xodzw#C5gd6FF>2G-dpK(@byXzsz({0rYeZ&Z)ih(EDKRs3Z1ta`g!OT$U1S z57QPoDb$$ZQ*k`@88iyX5%gRJDU%7Q#nTq{Ka4zt;Y8E;CO}*!U0@!g-YX z;(V2_6<2v|s80bw%&>tP%env-8c?L+8g^7eETLa+?WNRaM2) za-g!xGSkhjNHbYf{W}nI;U2obRJ))K#MJ8qW|04;UY{ZLG{%9eIClL-jkoV6tKPU# zA%$!dvjwrwA6{L)tV?N0HdVUxN%jCADjcpm%IHyLF`cG2_T;-sYX26p%B;}Wni;=eS)#8Jhj$ivqL6A?ysR;Kb`(Jr4I5IrCJ;8{_@u1487r0qV70T_ zXY(NVa&AyZ8%|(k?*yVK&x%~k++SOg7MDP~pn@d02J`GRx>I??A#9Oj7B>}jvUhSX zP8RHN@l@2+QE#DIMc^V%2hO-~@*Vgk%VhCZa?#3S4I{M4lVgeb=1U`&X=^8*ROTh9 zlq;%B&VS#(_jtrVWcTT4VY&_jV!cJNY_Tv&qb9ceZJq)dF5Rc(3@$K(R8}zLd-eQ; z{eQ|dkDr{rd+ZF(&8Mso#pzDPcC@k2Fa>JfZA)tu^KGgUrTo%UsYZVe-TDyxa|1?< znMzXJQmLPD14|_ka2Yw3af=I$bD%;<1t4W-8u$gGB;G>iV|ps7@Uo`^S+hvi#q->$ zXoZ+WXD0(sc!CUfSA4dQSd-|6u=|qz4riBYls#WRRGPXoAc8()WY5aIp}s@AAbwB6 z$Y*VfJ=hL%N<8F?*`TyFvN>aFOdZ|$b;y{{HA-829Ub^dzD;50L@#6(u+SW6RJ#~} zdRm+y815$N?03IL=J;C!h#0Ea7|fRFe+A>#mAqw_*#yFZSgfkZ{to@j?<>kxUK=QPXyTXGqynvyT0`AACxwIZE9~EgTht|0Sj4 z#f{zkCG!JkoSx;B&SJ+z-DP-Q{1;0hlI<`e!oRbrW^}z^RtDvX$r+g*XoQ=*8l~T?luri zCWTvSZ)3_POKg=Y2QP=o2&wHtS&wgDE91lh=Qdf*q!55moVR{UJNQfci<9lz8c=tzRp(^gRAV+^>%JGdf|9*4x7zD9RS%SX# zfO3o15ibgU%?TaN>tg>};SEj_c^d)wK@nu+PhGvC%oB&KzEZ3*P$`i?SnfiXsfVYP zKf(_utq4jsyE!H4xZw=ud_k}~GZO#s8rnp?8jX$))sufSOHI$QE>DT3PlcQzsISbF`|3vQ#t>Lf^LJKT*dFQ|L)~dV^F{J`9GPB;Ov?)1`P&g zh5SE5;+0GeNHK6)WW@|OYS&w|q_abS8d)K=pSxC^6Kf?y{pzg2EisSU?WWd_AfHPw zOG7q9`GJD-HJIF`A7xjXOtA^mp>jdkblfxdBp|`f|L@!EtPvP~C9D7ThTqoTO0SMa z3Ue)^`M7+;d8AR|OzdX`X-$U;2J0=X^xgczgpJJ_0Dog(^)|e%;`>9#QB<_>sg{Fq zWp>eM^6n34nq`Oh#~(!&^8@wHLat?DmJXesfX-(sq?z)@%pBJc!Xi2%3Sqm^b$5?l zRF_HCBiCqK=VjYhIzyKgjH?0p#rv;oJGhVn{^w5{!p~vBbm0??>mg*Sl(^`Mrvr1= zL^VRNfcKb5+C#!uo7V(9V(b}H*DX3R}m1kJCi=P%j0Y{`gP;sYCpG*1*>~-Kf8XFFKZ2oeF(h8xxK;($m_d0xO zFHo2`KN|?$C^aQq7k|aSGG>eP$v~#qeAoV??}=Bwe5%Ph1&we4>ZaJ_=`n*dKU>A> z%89j9hvLjB?~KMfmwzaykU~+~++zC9kPc_z5KZt^ka4mO zaGdCWL5>ye7RHwAn_1*TGW%~YASC(XD3o0g-fT-@Sh72H=Oo|GpBZ1^^Up29Pfkr- zVGrbFEf|D3noj>E~3$zEFZ5E*KHr-&uB|DTZ<;pJ^zw{ldKRSATA~Vsx7<4ict(_ z{w)$JreH)-*^hw48H1QNQ||~QC~SXobUi7~aF_Q=$1{x38`SGg=t20Iz)ZsL9Mg~C zc@6&XQbdaR4M$jOadgh?uB4|>uuSbc&Y&pok5Lrwg>TDiOJhwr1RK(bB?#L%5(FBrvFis&75Y9hzD8flAiM8r0ud z$pZ!ZCEUyvvS=fdaxQ(Z6u6sHWPccJ=qMez+7aM|?}gu#(nf(MCS5{XXonz^g@@RD z%5ENEF$K+T(nFhVopYLiO9W~B;##;UV|v+v$- zhOt3&D$?)$fH+@=0oiwOwv1=l9%vfq7p#7w{rZ|D8;*!orQ z|I6Cs%J4_;zp`e4`X5Ywp_Kvt=i0Wm)@f|KdOV;Dsy9ltge^oD27A+L)Oz1=D^$36 zG{fa6ph@%>9LnD8qTEPFr9_@8Yz|J%Z1^~B&%BLZ5P)%-Nd8ySkg{y-G2(N^ zew4pYlhDYqv65jl(|`G0x4i5)=|dZYs!SXjb$hB!kKTZRzw?L`kJ*`@e5Ha5St%`4 zb%v<$)$%u|TwMUxmzebEL>%Srez-39*6Vy^r?F;9T3FgkS*G8;-}D3CU6JKj)xybB zq145v_08Vgtx#fFjDhan?KiiF??nbrM7HJB;5H1q4cl)ntPN7OeQ!>~(MnH{2P7J8 z0cl94mZf8N!FSRHPDF?hzol5^942otivIjWW7cf4E|NV=6462lEO6U|3 zdK^H{3H_fp44qikArqw8VpzRFpV4G&nv=NvVvJEx?J)FfHwG^qylqR*GNTta=Y``h zRIlyAf&>QeO+-$pTeRm}*5w+#YLRycHIbq(SbADjqLeF z+w8sde4E>!?nGOj-NDXujQs&({ov0YW~4x@8DRak?wO$1TWMox)ZSTciq++a=N%$cMqIVv}LXSfkw^$60?s4Z7WVNhz}N2vc`{6FK^aw55&F z-INf|g7_k`A}k)z*_=Bnjp2_C!+;Q$yf*R=^e-iT8o21)oZjK~ylp4{2GXJYHr!~A z4b;PWz6;Abg>*381EJYrQu5)EI1xoCnsnMF^l!PyMTn*)&o_v*IJZOF6Iy@j$Ra6j z*-zep&cw;mG0|YbLLDIxvk~FmGEA-iuxlR8vHlGD8j zZ)iEN7&X5<@p$peCP;gPA4tsczJtyCf`j2L0q)aOlrA8 ztx868YjqBZ2|8NeNcMSE0`0tziOZlcZoD4oQVfQ}GL{l;O)zuEI-e7Iem$gt8bcT( zkzq;!fiJekU7$}5=%c|aoBM{g6T5UN%tY8EL1@|mze(a0P0Nss!C*yUX5P9n=hRjrD71lX7U|J!B&?3T%)}kGc2lz+{iq5 zDrJBn|Bbz25x=||gSq7&{)a{wR@)?J*0|q>iWbBl232X^3m=1LccxdIJKR&i9*_^a zL6`Y~@;?Up4K3^z__yeZ{{MDvVpdGq#ef0YFeh{vj})MWFZ%$y;FQ z2)aE$MLoxId~Z4#%Vi2-TYFcXAw%&dF5N-RSV^Wpo326KkWoZmy$|^tTWPhS{P}*T z1w!~}J|~x&>mYWvquzS<3GXHseL91o%NYXS+wzvjkAy2J4s~zB8fZaO*&#gQhft$$ z7gjPaMU%?)50t0D^{hi3oOn|70{%dP9k-W49lp#Y7adn=feGHP`zf@9`C+BR51Mp4 zC?!0JD_~?BG6SPvhw@M7-|}G2`tn2xDKU6Zhzx0sXn)!qfg0<#{<$1unH+NO{&x+V zHo`q*ZJdJOC1=9>&c7BXnRoj1HtXc5@a1f2#qm5PH#+TBIEcW}LY$?q z0vlXfn}lA{-_q7uR?p2YEbX>7da6(T#=pjr{ft-0`^Z;p<}9=_@?;6*ApbZ=gh6Lo(;r8_!u$s>+C;;pl1c>#C=zCZd%k)rCY7m?=YY|T zu+~|;W`lBxN%bm!d`2a8f@1BkQP>RmhYnHTIjmcrQsU-w`nmM4!4}Q&)_PyONQ?V| zsuYIMcU5ff?B);i*ZdXSVG!hRxAr(`oS*!;#fk zNw#U$KbA6);26Sfw>P1?VZZDhzP>4)i8Eyv2#~Lg2ZDbi)~z*0?b%Zo$i^WbjjCc` zfV9{Vi_mcNJvfDIqKY$>;$243(%EEaklk{4E$W}3rjHl9XjvOB5WAxGa&}X2zChS?xv2@Uq>)`!OzhuzxaNK7qs#K$FnOP<4Tq zV)9_%z@@zu#uM9%qRP2Pu)%i@g$vBuVAR3h;07*vOx3vEQKBn#hn1~Iux+s%5*TMz zFcD9g3D5Ah)n99VYH8hcTb1e8JK8!_cRUAq!tSh>JL1$(*X*>9^@R{rrWD^n)pi`K zon=Gdg#CVjgi@SfB-s|Md6Y^9`r#Oj1UZckz}6R!Fxh9KY8zgCj>}2YAd~C!!gC@v z+BBI$>FAu&Y-)dRK;hum54zJbl(j<=PACnbQ z$OsiAwhH`PMk5#vFh}k6XN4N$uEwuNfe!Nb__w6=TavX?efqs+5kcw44Ccr;d>1RN z(m$c4QQ=(tm3qNA*aJ{(plNMV(zxhl1z+v{Uj$Y@3^y9!L|HrkZk({CZ8|W~NLD*P9N_1-4l0 zPFsW7=}J_DI?NWJR&n%*CT^PYWWK8ZWp&OW>$v>^;aWe}PDyc`2Ucyp0S@DZ+XIca zyyD7t0(RU;>Qbt`fUpf^Rp;gIOAB zynN974*HBgl@bBro*%&uque+f`1aL%iO=&Kp&>~)kwTyzeW?%ja+cQPj==>pNvo_;f~2a*2q045js_niIw4=oR%c=_O*SxP80|d=ub}(a z^Iu_lRz&9X1YwHC_;j6mZeCz|9<02JT(+mnkrZZB#!al)v$CGEe2(+pAFoLQAz5Q- z5RHTa_(h(0Tga`rJL*G6Kv_%5oT+TCJ{mxZ!_u4?A85~v)m6BhpO4wa$3vUi$gP&JPj`-!-QH!fxYit(fDn%mA5O>y((Hx_ z7m8!hsT$u37T=OPpUXn>;5N2=RdlKWACu5hia5dXLjU7a~bd% zNuT@aJTQjvYx!^{*rD1teNTPCg>khSyN^lFuG#g29%Q$Dh`sW=Guf|o1EM`FXWVTB zTg$Ms_0C}#!tAYG}uDRbhAFVXDV5O;M$DW4yocXZ%lDD$2;*y(7-ud8+fE!g6WP> z=HifvcC*COHljGTR<!4CuG84?}hR z5rApXs4kbLgN|tR=76o9Qh_KWd9jh8pyEK>LZNFY&C4)`O;JvZkv%e}!FQ5&uYh2J zP{332%|RDd?ZLEA0)hL7pY_@nPKZ2$KA1d~E5oKcqjd>*@~OuWRopVEjf3et-@>(= zt{LTp*dDL!EX(P}EP$z@bf-g^tH?sK`wMM-ar}$BM6dJ-+6??V;n^0J?=0F3f{?`P zaKHl%MFg(-3-pRi=fDm6pfs++Eb;D^P;3f_UelHKgE+pEILhUkn7_McKES`>q331P zE3^nX;cV@T5*pkuH0G#uq7QN90op1_-I4uk`Pb*9d-AkIYG93$IZ$`YniLf0+FDer^SnrdPiF6e^M!Dk=3vpN;7Ydv*byvDy$I z^aupe%d@`JM>?M5gofU~E4lN(;KL@ov_#omnd*_^_fR^`oA{ju1`THk=~E_cf>5G# z!1?l`M;4N_`2j)%fB$bvgq#J@6(vIScFgqs=T?bZUyh^x{M&Pz*fL=a7@;F@^c4#C z_=Vc*mKwzi!dD*k5IB~9u@+Imb(6CPXCN2#sidRzsj%T8!>H2e zRv=;Czbavny)%@Zsu`UgZsIaaP$tUn&Zd<6btKiQ}5@zNHn4{%pQ z{;_kzt}bt!Vu%uxnnYbI&C=!BB6EcXZyj-t+fqu6Xtz_xzpnfNo+V&)j_um_--NMW zdW;qOrv+2~KOUKnfs)cu!v@4@Y`I}*V1904uR3Il>-3flpks<>bCY7q{ZWQ3oNqDy z^2@k&)6p@xEN9EYYf%*qweKcHD?<2oq-Ossy{DAF`!Adw|6h0?@K&7p-8S-c9wQOk z+d?FLZdZJLZg=-0JD*_2B#s=LJ%IrY&$jld1ZD%wL$9V%Z0WIhio*aG6LDtzmWB&_ z@L_%f-Zeujt5zEnl_dg!Fq}E{6g^29Ib6ZbSq-@ z-YPhcLxIWtK;aqtv+KUA#%ee(CEK!D$k3`xJ{{KV9KqjjenEhUIkZK%hdk9+Ln3cY zUk9@9CRqGJoSYnaskN2CxS$*s{j1xbx8`5jze?W{<~#L!UKUn(543iOap{mKRb*6( zVY*xq* z)ksWg{f8VLq+-d}7>ARZT*+4$jsTyCL+F(C++S#D=l z4UYI;ZYdgQ2!Z0$eHhE5w_hjxv@663ceiMnM9dTLSX^9C_(LpCNV-OTl6hI>isu#xMA#mL3B~2ru@d*TS)WbFSQo#b zs(L~bPUq~9)KSXx?9aN<@R!q9TpTD55c|qH^4jT_o-k3?LvOckTBwVMWk_38)=dci z9?NQ<{1)%1;4U>Mmpm)`7fUwh?DI|nsixv)G@!OK#9CZWYp|T|Z~7efN`nWy2vv*2 z-q9X_*k*NYX7wTSc4JWcwWWgJ_VltZVu|Q?Rd+|4H3>3Q-k(EGRj$ivE33Jb>uZ0o z^|?jfSFlmMriVZ5gGBan3%|L-NnCcp6*+z-5_D++skM8TJ=6JoDQ*6Jp1t9JF_9-Y zF97ORo+GRG=bO7H%(ktX&+HdpXqn z!XX~MI!XA^pWqpjmfBAOI4l>k@%HQ6jwoCny?B{EI(MQ-Mq%H4wtzuy>E@ z=GyPS>>&}*Zm8ZJ$o#TlbypQy{${hu#J5-J^ch1DCn*l|QsXNGD{_Z^Yh6F|>Iftu zCt1FUdcyNK)vNsj4ZE>Hc)b0W-h8+BYD5;Wa~@xG=Cfp6m3SyYu{ZW%ahvhXOz};25!Pb_E8Mp4d{B z*rsewNhPB(;haTVYXU`;1l1*amOaK6e7`p~cWt8<_d0Z=?GE&F7}F5SWY{b4skX7` zjt`((aaX8Dnd^_AszY1-Y+pN@Oy))~+vSJk2!yuYx}Gm%^zVb%UZm@q>TVCZ`tf|3 z1PaDBY?pW8w%j`$s-?)KrQrq_s699ecs(UKCa41B=pStGS%5Ufs`BiUHVBl#bvO?> z1zdVEB`fNVV_NOuhVw$l^BJ=65$n-TFn{ge5fCCEJF&d+o4`T(+h&VAff2;P5o@{R zQ%!N=O1zL~&s>U|CI=`x+@5T2Bx5E`o+79^#EX1Bv8%gcnet$d!w7mJ%Tqr~(9rxv zZyM2-jCFcd8sLzVqgZUjg}CB-{-?ng58@FKo|}#Hq|;3btJ;x!MM@w&8;&$|Im!8%1)0?$AGXaFJ-4&nEy`D(A}2#}tclop4O&^1mm%3s2NP@Jpr zMqM?biT-Bpi{puKNq{Jjo?nBEW;ubJk^XAy1pl-w_l8LiMg{d&#mAXbgDg_Lp-wcp z%%|Z)*_C{RQ1xk1{|x2$ysIFBOxjtxB5fsy%tFg6v&NyZh`%VgR=EN5g*UYQ-5Vj| z2P(iM4IuLbzyIMFT+VpP4K_n`XiZJ1v|Og|I5=+Gh{6xLQ6kV%NFkuY6YF~`-lZHo zP9vkkw}b*AB0aUBRQ$z7rMg$^(@4W>Tgq^t3X~hh%f+gu_*ES*L?MH>Zd6G#BWr_r z{lW%on+}%!ezU(tl|@KU!EcGxBOPME&dZ`|1xUe2IvEVT1?vBVkw4DaU2e(wJ{kIp z)^9dJ-oyCIn5f-=%Umk$5(C$_+>U6~u@zM+E~$xf5L9jVzr7)~idxNOXr2BlOticF z!{H=N4XMWmjACo{feVEar@kXXXm?LW3V&7!d>GE2HcsraJ;w35!}2qOIh- z4*~64t!bpOrKd zwPENBn(?O`Af18UTWdY3&$M+l%8w)n-lGQDL-naK{A$9Vq9M=RP+tmsjaQLU?HZ4m z3`1-mg^a%1P>B%EulQB$FU`P}LLL!I4Se-CxBdZg(vxLR-d-ilzMB6sXw_1myb){s zD^lb1gT96833j>>29|wl!0m(B!58*d?Bl}&A9(hBgA9TTU5j)%k8#Q5{0$b{+bJo3 zLYup9Wpgmoy|t2;VfJ7Rmi>2QtA>zt_^#u`!a?{a&X34|=Xt+;q~_8S;n(E@8Gy|D zA>Q}rWU`!$Pi*7)vDEd-&i;@f^uk#wI$=E8$r-%VqO20s$>LzbJh7_yP-3|eL;hxG zf_(E0N?7Wi&Z!H!tcB<8_8cQ~c&fCFyAW6z8}VIeD*TA7bhZ-EXCHyYGG#{2v|mUY z91gp04W)Sl@-2qV(-mDrX!M>A0>ac4Xguk>J&;MdJ9a&^PO$0RXZ9AMUR|$;9ACA} z!>^V=FX2tu1C^;Z*}h~f6f73`{QL6BP?%+m2jQvhHduE8o5P@FuiKCztsBvah!>3s zniqo!k(-QE;DCgVz+46BKbOq?R$Qp?5zm0D%zCOaM#5OEl#2DsG{h873$;uOr)u@_ zB{hZw)tjUTotd|KS8Bbs0(&&sFXpg*#~o{VJm1mJ_g`}KZUOGx^Do2(bvoYKs@>QW zxa|mLSXz4X94*NH|D)lcZ#Uh&{~$gP{(lfpkAjktU5f>PTrJEk9Nle9?A@5n>`mO< zG}NKM{t;&|uz%>UhM|S~NtDtc8;Ktry@IWVU;>I7@OyguI^*nR^L7~K+L$RBDHOP%dgtTlp(i+qq*pS9zKPi1 zJmEuC&oE-$<8;WVT#k(0k;d9Y4Vn&|p1V{G zKOR%PFH26xK&+RUi~_T5TtI=Vfw&ns34!Sc`+KAjX_DrkKzRJbHc7eq1Ua~?7RDl< z+YDI6gwvm+im2;c+Esbx@0wLu_r!VrNmdsFcLbCYP_Pp+-62OY$cG4VpS=sVs7A zCeKNX((-_EaL~eAHE z|Db-m91E(!Y?&pFs{u!o?g*2`PjwA(0S`v-6`JEee#Ip?yY-O}r$2jjdm`W6Etfde zhYb(AFSEwmF<9WPj4Ug)qMtHtY%+3#LZo;W{Z6WVCciYUYI zy7;uBEEkWjjqsc0gS1jojqF=TLR-+Ik;DB#puwTzkzeR<(L|C$@qr|UUp(3}8r&6D zdw$-0HTTI#S2F<5{VChOc7b@20Rk9JB1iHCa)LUywQ=~CG+N=Ec3Vg)Zm2^9Np5## z`r9yikIHl4lOQvQyn_YBghm`O1*iB4; zjvTgZWajl=z`P;}>kGW3$~_?Wof2Kc?}%R*{g?!SIivYSUE5!Zv?jJbl%A zG=`$DdS86;Pzz_Tt=r+4U!gT8&mJ%}rLT+YADPdApqD!nq-9M+1$clKF=1kHb%!2i zBY2R?zALVdO0dBH+i{B^p>3A99o$BU1Jz~hLUHJiXP1ARwwNq0H(Wa39;r2Pf49~> z8G_wksX(j&kFXFC9iOsG2x^0pjFhu}M1V5Dnu+U2VKI{NI8DMr zD#5)a{QrusYlJQ+{6sh3Qo7(j-_?gYB^`&Hi$CRjT9BO$6C4yNk=l(G4wW`eShyC- z{e-iFVqRYo5Eu`@a9m+pspFILcU}=1;PyqJ9fs1cEwwHdj|4CYjyNUdl7WePf>QT& zs^{*Kf5KszslwZ1KZ)V3K^NkZY|TUGCK=v&PGG;J$cxA&pzB%58*kie zD42-KKl7@G?Y@0X^Lkx%fQI}C`#B3;_!^7Rv*QT&wxd6)9*q4(ytq;*q{$;0o}cdwqN4n5X{yX{tl_|{{*AzEkqToJwI#1E0>Q0*Vg&HT2a21xfL&*eaT)!8vZSLHRc`B4B**9WbDSuyCxkhw8@4eG+p)Ca%JS2 zbS7=q06i7Oy8wi;rijvbo`1v!uW5?U&)c#S4kS2*6^7=M^RPjI0{cvJN-h#6yXu@b zoFMT|7uC@}gR)3Ff(c05k;YnP=ZHZ(IITbj#2(!=a{am4(JGBjQm zp9&hnvIEmtBUA6DxQWlOA-mjoY6HvFx=q(Q)w&OUU4U)bIc;yuvgFq?;jos|ckVD8 zKJ_nrHh*~@U3Y0~Xt3?SKe^);#?Wx!)>XO31q#VV+^Uk9hGiu>|x6L+Y zblD0ltYBnjOnp8?TxT-J`ZT!;)5nnWXl9B2PnQEJ6YP8Nz|^T$4RvR=2>$0>wFo_> zS>O|Vbtw7g@9AlkiwO}5pZetZzTcDeJ2w{iR_lq2Ht0h((riv?Dya;_PqZlJO5^wb zs3#wu8DHxG{6K6dHj5x;_GL^Do~YKg$E$1PSd)G6wOq9?$?NQkU~wUPmGU!j0dQLzF{X%pL2~j=RYhvMn{D5cQ(_1ve-i_&uW=+G1t{$+K@R z`Oo)_fZyGF0vLAV#Le&zKZ4fTS|-P9*gms5ZO@hL=F376XCdNFAjs$phDa=sPOu*& zmLWu}d70nfHPAt#%V2O7W;%n6}8Ft|G4_5;6S3S-I~Xwr$%^CblyZCx6a4_vu!3)vB)Qe(CC6d#z8KZuP$Fr^mD&iXOhtoXaZ-7N>Hs z(E=RFE=(E8RNTf9(9wD3v{P2?URp8b84R z^06aNxil7l+F_6Q3orqNJC%T~6nfWn_T%tQ-L<_%gG*+|QXZNw4o5nGJ;D6yj&0Gg zhvhIm<*d9=$U~FA$lo0=^(wSmN_Y*QMu<71*$5k(qNzzBnLXi`(ZNuL{atCvK5X*Y zeFyZqWfC?ywC7f@mMl%rd8X%nnco!wjlJ0XUp%~HtOvcTA>%F?IaHjYqaG$V6tN`O z&T!^|vd=875nMY7FJEh)JWo;tI1-(`1A0y2&X=t_7Qs+B00l}W@+ zFi(Ew0n-q%_-Uu`GVT1q_u+}lSc3hh3x4ude)&S+AJa1>RJ*iAsAmM6m8`rjs+VA8w4eiO;i0>@Fiz` z5nsSxKY#=l{<%W8OZlVbkZBhveK2(fe`b1!9o^B_CyQ(6Z9Nq$L z+Zg?nem>&QO{#FlvZtU4g?EOXhwBcA6YIEAd%<3-EF?;PLj9Fv!JANsTgoe1C;(>l z7h6eKFR-v(LT5L|{*;+Il>IMNp~eKySm4X%2=+f6GmMM~pr!C1eZD=6ELL$?Yt6|| zZaTfq*&h+cdWwQlN+$b3ZL$s+$&B#){$`~B)(;cB-((KXy2HUqMfB6Y_oU=`b=pYkhj9{*y zlvCPLStt4d-=ih!9DenKW(s8QrliUn>v`)ZPCCz9UW&>|+jR_^X1PEyBECE6Kv`>2 zH+xY4?YoKM@m2=wklX}1ER{yeJlPmbvm}F*eid|j_Z2-?^8}2D%e-G5uh#uU|1DkO zYqjcZU+p86!GV>;((U7Gg#ZTZ6_fke`4RsROa8+l4uo?x z`kfP4OsG6e!ap#VT+E`Cf&@S%f(pSg8_lBw_hI>j1`5wRifvdfwpp9oRHSEK6FL)u zgkZ~NodS&vI{s--)x!kpKPEwgD0z4NB$E#yva)q+T6zuT0}D6dbc`p2E-wGxgzqUV z9%mf(bj7VXa7u^*Vu6`Y*Qn$eV=2_6h?5EIZ|itc%l436g-Q-U(m%|e=oRKPSri#2 z<$3T$%N2_XUJ#b+nPWadM5F5FO~2STPaYN~`KIR$gz-&Vrwy{9nT#q^v{=pTUvSqr zl(v33W!&=xJX@)lXXY=!2aLJ)?5pYt5B$0jWi4H|O9;T-emhY_$}@k%%(kRHLCpsm zBJj1ZXXQ$K!ra+%48*Q)C?2{TewSEX=JPGq7PjI%ahwRIxntFsTtndcM;h}QjMQ=0 z{Uv!>Haz&1TS=@gQ7<4TgJ&T?g3`|sb!gFJ!nzILz6hT25m5aRe#)jhr4n`y)xYJ9 zVK8**5#4ES$rm>3z$>JgHw;GLPXdiutXTA&c(au0?Y|vCcYeih@UI0T{l5j`E6)hP z{M5Bj`;cdDc)Yq`eNE%#mRgr@rrNq-VUBiNI0q!qFi`~$_9qCkuhoCE*U5t7#5)xu1OFEO-&r8CIoWsah1K6?Z--Z&n1RL@aI*$>jwCW;HN%;BSQc^Ze(w=8R~PTQ)LXNbsy^R^nZ)DqE^{H|Vb1*fpjR zFjT0BW7gzzRKr&{+v;2fhL1*M!w6?{>A0bMB$&-$)XlQvtC2>qrPuUE@MwV4hU{ve zh7p#sN;cD83QJCFyoPpVb@M`-nfL@F%mpOm?HEAF2=e+Ah31ebb}nCzL6gy+C)r9BS@(a!#nb)QS4iZp7~ zKV2>{iT)xVq{mj(H-j5k z7#%QWIwrWICbEpEw|z z(V3vpEIjVo&q{Z;hS7#j6YcLpv;$M$Sxu@4S$%Z+xD)E(I)x3_(*psQ`ki9K=!Pqj z2#h8}y>Bh~$(vK!%(K%CV}X~NA+&OJzRPRd%sHUkb85ffD=~r%)Rn;PGpkTmzQYc~ zWgMZfIYKmzubwn0pz2B?fY)JpEE}QZ|1cO9W2juorxYh1~)2sr_3NPTeslT5uX^xzG8MUlw$H*1RS zUMnM3EAAT8y@KrZA)!eKR8a#)03VV#?A&#kU=Z1X9aEGf!_{4|_V5#l5PUBXr{-`c zCz21fR|pq6A0N*9+$IpxsBBt);tv)bs&jVKCJF__eY43Pq#F~EKm9KP%(d?Kfk>^| zozZYH@`Q#84w|dJOn+Cqn@%00G=%~=?=e^TGU6i zJ<9VKsA^f8ZS~YY1CBpN1Nv+as*HSQrP`^p`I%a4T8Q1iP(dq&Jco+ZP(WfB>1EWi*6W?Jrd1Qh{-H0`e!>eQG;`t0jY$LCs zXGr8D>UYd2UJP48F{M!F)Ig73oK5=mlK@olV+qgE+J3h8b4Tfsb@oHV~d?c9zrShn_b4p?hiJ1iu9+wmT2(4X1x7}Ns$XBh^ zFuD5r!xJH=5c=2n^wDylR?5R~(`K2-OY|zRKI^D}l5wsb=Thq$Vh+`LnL|xPg27)u zp2U39(y92^lU(nFd{I59&rAZF-kS%c37js3=f)Jfvq3<7pblNuU_)eU$-=~CeR;!( zW56(zdWdfTjQXHgV>J&i*b&baEZ!>UPf#1*kjSgOo7&4&5uXS!awh8GX3c8<=)LJtWr}Cy9$Uh67p-qP7O)sWiD=y!Cp?kP^5RJj7nR08v&6_P)u#Ui6Xf(Mb zLetr#Sz^M!NpmXLSLWrFpSZ?W>&)ujpHeC$K1ERj*DacH$m-NerX%Jy(Ch4b;A3EL z$O81t9F)xiVwq2uXS~djr2#u+R7dfC{|3Z(45(fyz*;^;m5O=w`VYVH$1*5#BU3Nr zTq*m~b+w;HKKX4ukd;q&O<_}CL+&AT6$z9N#xS=fV!6W?0F#3}`4W7o>+-SCdkU;o zoj(PDswAcLIu4b?Zw6)ht14*W0KF!YM#hyfGh5-`BL>h3bi^H(h#uHKVsB_cf&=UW zjyiHs$9D7!`M00o1`8;FOr~gP1NJdfbZ`%fE3NAY8`XP|^2=~mA`EKPGsUNp!bhUN z_m8LYI|6OO63i#|g^@kWJxNNFCSgEOZ;uCI1<@JLH#BcB~ zg8E}IdxF-a*KgYMZfno@5I8Xd|p(CYgz=X(_Hs=S(&e4&=ez5VvgB_*aAo^;FlGoM)%)A~@Eyu2JmYf}M1+6m5#z|_M=MpVV2MYn zd`Y%>b+UY9Y5SCh6$#!k|6GYKKA!pCy2 zKMkY07|SFcu&)ajht7c`p)0mj$(gPJSPsqIf+;NAu5xG&;fzGO2aTj9x!n!EzEi5M zqW0>yv8wv&@Bb?4b#?r#Y7*gLS5~Btvr^8?-o0glYOx%0geX`>>P_4=CZ!3m>fJZM zY*wXf0WK@Zj=S~;SmB$ZGo0~bPh(b|#)a`(kcpaTvj&r)%_f+)${-L5mwyUC%ZZ-X zWyASVjeU!9nSVQE_PzTWW*nTegkQ96eqOq!GHQK8JC7^R0JUdpn$x}UO3Yob=~a>? z%2sN&&O4%y1%+2(DNT_4cv1&oyVCPBkGiX-ag@*cMZ>GcphdV=8CQn6BW-@_hnBrD zIHl%rk`I`j+GXuT?fD@V&5|3?yV0Iqq+9VjIltrbcgOA8f{6y&@4iow%tvNwt&Im^5@cg-QH zQm2#YoRq+cVRP)EN}vv?O#54%>rc6mV>MQa_Ka_xy;ge(d2QM}8~r}!N^ka9ydd_t z0)8DphX66y=l*`9rCUP56I+*MVYO}Cwtr6h>1qa@%l{XjoG+*_7JJRtVpw{kn0Ne6 z-q8D&$zjeJxuCc+=dfe~mERxT3fv#1kFGe&oLIkvafiF#_l+G`=D)N)!LQ^AXS(D6 z4SOCdG#0g`AxmHs?3EUJW!wCl_^6XK@mObLhJq{CvUE4=+8Mn;+%LIfKjBWZ1}uie z;OJ@;gIS_ynU~fg+85$}#BNhZ=E6m8<&mu_>V+IJUDSp5j9`S0tTB6p25c_FamtHv z!S~x1cZY-{(#9TeTk3=#^?~dzK6SrJ)*7W9j%}exz^<#Q5mhT-8yb!L50{hWukY$k zdpp~-!|KZV-1;(iOxJPkH7@wH(I*!#XL!(Uvs32_E_`m#QWB-n0dqCXYi2^0p71;A zu%{<(IuvRS*-GR=_8Y$F6srACC6iiD?A4PG8}?eLC!%%$)|SLLg1bDsr7sg?N5T*3og3wOCazT0Ao(%?q}$M8iX5dWAJwssSg zslt8d;4LQr&E9nc(%yYU$1#&9q9T~kG=flzJaDPrdQ6 zFiO6GxO$w(9e^PaRCpEZRP4_ky0#v~;E%{)S>*)6YlbOqjeVDPW1QaHpbQ*dUXi=8 zs;PE!WuBHfKMsXyZAJYoZVvCBKK^+^F^IiK(>+B=UB0huHElIzPS*BR1rrQkL(;xL z!po2DB`orW;7v@iP5dZ9aMQ`0WLwU=Dl#s#$$dgROUbNI5V%E6X|5(3zv7P^s8C?w zkU<7uaqJ>f!KCL06Ei2TSX6RV!A0s-xu6zAbY_eVBvVpJbrY7z+IH74L&DSwF;j6w zkjo$u6U^mx^uT=iNNu1Li<_O=4u#qBWC$M%(f^%JO61#N)QU$_>OEESG|y?<%wF|# zQ*Xx5e+?xPZ0B~Eu10uh{)oTyG$le}_ly9HWhJ9u1|e>$PeD&Ni$Y#D5`m_PK6+Fhc|=X%V%JaS>9aT6WC z<_lHNi*vC#<{I2q2tdcJUag*3b;csty*Gnyp{)3BIyb=vU)P1}-GrO*AjjPC(!zwD z4Mu`5A|y`3qZ8**u3>;zQ(gDmJ}2=Nsy&grpDhCfN1X=8eyNTcBV@Mfp9rrAETAXH zaB~S4*EhJ`3RGf#ctl=tkGh4#ZB`zuD<0tS%?Z4y*EBoBq6>K~a(+Qv$CHaI-1GyF zv<&{Nq&57y$mdj|Jgm0vr)qU^q-jjk<2PiBA*QM>L0Aa|N(O)pP7ve{tkif%F46L~ zQo^Q~(_V*k0tG}B8I_}9Ohy@;kD?En4%`|`NLRVT2T$IWktD(m$Wy8TnY6dBN)%`N zFgOT<^O{~)IV5@v`587^p-sGcyEqD6eGb?z{`yDL<}IY%BdOh;k$v{h@S0ikouh8? z_v~U@Hp3zvTLWNT*eNU&W~}ahzAfy~b)O!CSLwS6{gWiv=4D__#ZNza&+;GQe)Mml zR;vIy$XrIlY7N)>&{JON8b15J-P_Lir*`~4t%!N22t}yBb$_vi3HLOP+fA`UPI|Xl z->D9;8QS8r;J~-Pyezhu@|x`7!zRP-vQ4gcH~tBxC<6-tiD;;IvgnOVZr@o4-^PO)Z&9UVzoT8Ji#8l^ zVD+1rM>XenE4uQHsG@T($_5^!N1CaTF;Ml`COa5`_Ub-r!ZXT+54CM@s9J&3bMr1M z4UG$vjYtEA{kQ35pY6N~YFP2CRJOyICoa%P%4+A9?Xl2N-v)m~n1`orLoRq*EzgpQ zZPFNIA9g|FEsZBZqPqd`B;8!>B^}sQckyZ1;6Ax*{J(r;O?eRO|(%z#~51{_2w zmV^!jj2Jm|u|$PllJXRF{KptyJ?0u{<8o%fsbLdwyzIbI73qzjQ?Vkjq$&_3Gs9_s z(z7hmGDtXGGs;(DzdW?5#2iN2WqN9@Zp`vO*wv|wL0ZC&@lglc|#7}J`fK#kCDw*oL}#og&eVD;uDgQiKz4b}C8DA} z@NUV@+i|R!ag+sW-Zb$(edAB!v~q$Uc-xu$WD)2w*!jj7lJ|3F>xv0Tm085GhUQ9b zPckXfyNn)MZY8hK6Pg6k>X+=)HJW^g03OKQ-IDH+?F#E2)YJ=RCi(X>YO{!ULf>`_ z+?SbGmBX^e33DgOIar>Vz7ZKd9kl;Goz_HVbk0*&>+MhQhCAT{bL&ZEfcX2fxUF^R z-G>SnhSOjlJ$a~DIr1>WHM76$XVSK$2OR`?s>TegJYh&Ts1CT}vO=7rK;Qv_BHR~4 zWQ2q7e*7h?LHVB|{Y0Asn9}m`RXKeA^0)MYZ4`PhHDEz;#Nb7ONz&sC-U zn2*9Lk)7`8^?anH@woH)p7+|Nr}MaNKbG&iVOdd9?PrD!J6%sbkS_yurEZc3Z6H?L zk>5>RD)!osB!*zazwp3LvC z`r9eA+?7EMlf9caawj`V)YB*yTY*tcUvt~heL%}XL-+C<(g8dj7DBmAKT@({*^m#m z&z>}8KKoTPjh~-2(CJilyKdFpM75g+ij()iY!*9@sbtI-jnhuA64VaL(}#ZO*H5*y z@ow^p=go_IuBFtF%xGfk<|ZmdN;(=`kFU0ax#CLR|HfuR9vyLpohU90N4{^=)#JoF z2~CleMqU8A00mPVn%s+>I}A}}o}Gq_BA@LzxJr-WktaJ0$W9VZro&42Qw1ZFpRWXl zPH8e}1RwR%nXn%rXSMMl%afs=uBXUVq0DMy*?mVJPeV}P*RBYL7G}y_ z>#IgIV=^~Wa%s90C6iCA!z^h~YhP=HS3TC63Qkm%sjWz*SWAXHT>7{**Hdbk3itLj zTg(fvGjm1;ma)O6hNC04C&YP!49!AUf%5y1(eWghFXE_Ai+OrbInZXWJJ@V8p*kI( zs~iIyi6*KG_c-Mb?o(Rk4}0?6&PoobRQG%^8&g&zIwNnuK=)E*Z%vWNmKGKKd4BOpfqaiT z6IR1~O~)xdinx+uu?s>J%8oX>Jr+;XB3ruxY#*n#4)oHKz~~AyF*AXQ4_8g+AJ`H< zN<$E%PbXqU!mgyG8Jj)PlR8aZTCtCCdG&C?ZrT|XwBKVLKHrx1X5#LYOFZ(U>qt{6 z#poQcF!VgBawu35RVD1^{v8DdsWXJvF%X&MxPiafsDrRB$gs@X@z1;yYQ1|#LO;Eb z5D};A)TS#ja`S*6XBgr;KKWYk*p z1p(7mco^qzD5Ztd_2kmCVDsv~b=>Z(y2XP44W1zdwbe*CeXhxJV*dG@ywZ8EcEE5}x%a8vD9+E^vK``x$+bY4>KV z<%7ch?(pK0kRxsKieF*i0@cTi>cmKP*D0%4Y0VtXeY4aQBzuGR{+pVUj0AsL@FDDh zBUi(OzvSr=EgF%|+OLG?GUqIb*IZyQv4FGx4ubTAS2(OlAgSv2pihDl zy1xrR@N020%Ou)&fK(tx0d?QxiIfFs1IgXf1-zIm&)|JCG&1m>U~xF+a%Y!HHPTiC zIyk>PTM6Er^Ct)tt)>1kwfQ1TDEPpT%iJ=1EY$T_t7uP&c5qs|Lij(iMeo=au62fH zb@A6n%J@R<0U{@kTx4aGK2Od95)C4aR*Xj|{hl~FByb41+t&G+({~wSL6ks(ek(8R z>DXDN=JY?Qw`f>Ftw26M90uf}rCNVbWiJ!-d6FnYB<*g+CS%%{xBQGl%M7r%Jr-%E z^7Gv!@l@p;4}c2x)ae&O?^To(4z{Lmsc4cEog!aBoo9wO3j0${4{IXcYr>2_Tx;p_ zhSECylb3#<=&R9n&sQwfEvko_GQ5&>H~UA%E2XK!7qXwRN;51Xt7spZTVlo=;$V7S zWz?ZQy+SM_^+bN$UF*5f)C$B=YY0`PyQ$B#+}J|J>;aH}DU!zD7V>Dg7XW@Adwemd zoui8pI=hZ`1&#=0h&PWLV<`Pzk2b4ttcm9-x#68GPpBOfM}~$T@#GKsWQB-x9ARg+H4CgIPpB$e5R0vW0g|z8rM`wGJVf6={KgDlg#!DmeP^#mS6s8wSj1B5Y zGbZ*Ohm>j`Hw+TGkcIQd3k?ukvw6I$MmeD??l#nr=4P8GRRu${<4SYclW)KlAu7|n36QebQo*>4! zD?gi4N)3LCRegiDL4gr0DkXrdQ6KT{ zSfM!-7P%?%W4u+H(VL9I?!Z5l9Z`XI;chjlbRcUR8JD2o{rE{-1l5DWF0X3nB0O7{ zxxwhT@Ml=tFRRQ^vG5ejTuxgE39O|#vaDp}T^i1AcW2Do{%R;Leu)hF??|Ra$4OT9 z{N71nK)mj7DEwZIOU_vNFPTz`jHnYMc+=RmBUa8*iDG-E4%$h<5LUKbq#*5@dWpZ3 zb^a(xL|&|A8LnxY{h?YT?zcAUSEM%7{ZwUbW^xPYpGVm?9Bgc_I_~zTmTQeJTcOS9 z6hp1ig_KrDMUv|G`>@kF#i~WOmqe1a`NI^S{JZoS%c4? zvK;er!H;h2cGeDd2Ip3n;Z6X?9cUs{c8P&X1^({!*OeoAbQE^Hr|Hp3L1j2l2jvLx z#|GK&`lpfEoJm_E;U7d-K({ZYVV{a*0mRy|iTr_Vfgu}%P1F4H78f}LC{R7&{PLxg zgkneSzlU1!5Zyu`QnW%E$>vH-+eJ+8%LBbEJDuf1U`JhfZc9x#4oOfu??xHxxC=mr zCSP4K{F>9|ydX0)zLlkq422a3lePmLwJ;d@)N@_97rYbKOM4w0zY5C9>)D;MUw`=3 zrCk*;U~xGpyVO{+9lq4dKF(@L*TpmPNv<^c)Jn+8hsy)vNm?OqIBkxFl1fne+raAo z9;g8RKY*+pM7cSn{!L-w5oCayMnAvg?ix%y6Gh%Ce=6D?OKyyVyqN%nH$&t$lbKIM z0xDG=t(l^>FFb7w_iyEwZ?q-UnX%eg$e#U5bUJ(7>`rC`Q3+sd=?nIR*@BVY>afSBZ$fL-k?jd=uYCPSv*h{Nivzo8Bt*< z*G+9At?K)CF2r_Yq~S00yI|JKz{R1%QDTTw)1gHO)cKpH?xPoTF5{cLx18^hrmVmr zxW%TKCi?!du9kS_WEP&&Zo;`7m(Jt_!>I=Id!YZN=%DXQRh*g6henE2tz5;sezC^s z-%fHT7Y3X-nh}CF9Y}zDe-C>>7aKSn9VhNLAf>5$U)qRH|ADo^b($|%E^Lx z!Rex!{gl`2b+;XT=t3gHg8AosZ8O|hn;-N+bupX<4z)jQG=43+j$ ztjnH>73a7MwYNqZC&OIr9!XOp3vaf5J@14?#+twpcO)W(z6anM7q2*RktQX{+0eNsdbDi60kwKj^b<(3v%zwv}3`$fKY^ zM{Xon7tWc7Kdk(z9o=jQzxK5ChtK?Dj}O8g8565R%OuuJQJ`nd+n~&iZWdYyg?|}I zDD>8lj|u;wfDTafboI}uf8e;G6)}>8+@T&7)l&XZ$QxHn6yE=4eIDxg&*;YWh#q}I{=mb)b&y}uYv`PE&7V&98A;> zyCb%@UqW62u`BJDwCes3P1=P)5A#*=r{tv;<$mM1U>HCgbJo}4hd3ci_3EAk0tusN zjaj>pTv(s^!MoZUZ6t$2aU87&Q_ldqrcUZ1|L`Y+2bt~|>dQhab%@Or!6)NC2=@z1 zg?;c1qD|EY&a)riE6!8kGtZY}Q0-lo@cJ*;mUukf1S{RmHLeblXCjh+p5Mcsv>zjO za|T0%-YNpU7C6HL->-#y=|TpqeEFhD20W?%(A>4#S@F7H&LH`^x4biQy1>ugUlHHF z`SmBtu2U4<6nt;rp=;A;i(+=ctYNAae1HBk%B25k2Hk`8GjooV{qWpAT?_fD@z}6!D+X1LpqExCDp#T{^J)t55e=r)801Xc zBi@nR<93>vnys@eax0AE7JMQ*zy5oYnHd`vm;d6_dC5~mL<-k9o;{VA%Qc^Wub%2v z?IkkMpTYxcBO_E#P2T#HhwXtgg9Ymr~TV+3PqJc=j+wI~!&HRPHNJkt+9U?T8{906He8MA${;Q*del4tUjQ1;9c!i;zyyyv=e*OwK0mW zK%s0g%5s3Ohp=D$F`TjvB4{o-J^DWRh^?NwdPab%UV@MrsxT*UuJRE6offZn1FJ4& zpG#3d)}!_l;Fj~iFPy0%DE9ebx4jMov8ENjo^SnYA30(AgA|Wo7b^l?*|O}BG`C{& z>qIJ^k}DqTG|qmYjHDGKA^jsN_Z=BO!BMs!rk6*PJkNf2z8onje38GuY+4C1r4Q7T z>=UnV{f8hh_9NP{nl>j2JpA2!H1RT1;D_ZuQbA%IoNtlEd#<2lwXyaCo2V1Oy>ki~ zE;D=DQHLe!W>?6wFj=D)C{75!sS-Uo;jFnK5=hF;d`Br02Yn$Dy#!Z8F%DRT_!yT& z68ipHDJz8H3|lCV;73j;Rtu=#xR*1hfQ59LTm$}6lWd60WgdnfR23(0>r>BCK^6pC(KhDKcq!(H`o2 zP<2V!khB;LgFYGH28tmVsUHB>s@%%M0U_s5Fi@KjS;hLRiaoZfIj+i`sz)a(Cjihf zzcHW)o3EV*d4S}*G5C+vxwkj>EgJdTww z+wZvhBoV2`vDMDXk@@-t(}R0Sn{9uZvl5ATv;s?+tkPN=)ueFVyaZ2uM*QKeh=2OF&_R5DcIGE8y~<7U7@#0_-ln{XeW4 zBXQdaGI6^GCy@Yv2HdRinyONxJCtsgPa)MQsqI0P6hXoACR{VH7R>2M7upfQ2*yGn z>3zQuNb|B#6FU=f9Ut%*5PE%j`hm>$BM~%lIpFmimq8cz9%|r*JL^$@!XkbQ~fj>f#C>0w5_kCYxil|_A z(<1SXwvEj-x2p+5*yIY+Qa>l!WJ66E*OQQp$D|v3HU*Wuu7y=o-Lj?Ycgmifeom35 z8Hr65Uihv^dxNL+5UD%A=v-2yXY(0oadQ2uof7fhB5Z3X`lwwZq`wUY6Kcg~xX5f? zgeK{D%$1d&`e<*zII6Lv&v91RZ70ML$}i+9~dg;4w!lnKdyfcnp`Wlgx)sQHB;PyY`i zZTLwCRB1yQ>Y6q2A5S}9%NEJB&dXlBz@m~zmsm7ARiI?_&Xc; zxO_VnnDCf>E)n2%-ytIAR+%wm@mm=II;iv4cv-G$+__nuD!ZXSw zdDWNju4@@{YV%Xl8yVNk$Sc-6D*siDxq3Lemo7w+SB6Eum<&=lzJ7t);=U5rr z89Uhn7TnlFz3epcplYzR)%u!#!~JUn>|yDhQ@5`9TiR&h+Oi9K;dE>|$mSA@gvvK@>E7F zyxYq<%gqZz?zY+f7qm66O1u@5;`XxysfrFd>Ld${bw{BOY}*X;OUu~e#CW?icDKt* zb>=n8VcDULd0*&w&2j0$NlQ5j^kq?C|5Asfb$*ti%xOm<)F^Bi*wAV|C(=j7sUC#J*MFFJ0G!SlGMK7AyWc<#^xBT@r%m zLV6)V+bwu*4dPUF{6M4N4}*3CFMf1CdY_eY zi8FcZ(pKV`-8Z&ksUkDD0U9&g@L1}yaTzq#=pv;kNEl8JW2?2{c#VfSE7x|%x}R44 zrCiz5rqo#Eda06WXR_JWU5%0ess^f5br@-{7Vq47LBqvYWS&q12>%}jJIqTtnS(ux z1?4pa861HGr|fByd6KbYXC4B&0xvODiHY>$81&hCSJHK&af5IZbs9fVo;y_REQi@M zCENqoQrVhqnTiwN6H!-8kOsAo6nu^(J`87@-{M4bgQ@}ot4J*geVV)gnr-ZevN|yVs}rG-Gsxn-zG=xy63a`*4VAg=Kc^z+-W71|-v|>THY}Lr==pL$ zaJzCc4o~1@?>|Lc7NPVxj<=?C!jIndt&12FS+LqBm4~&j3!)pPTyMV@tKGY_$nG)U z8b11Totw{Y8yAVn{52Z^bRuG9trJ-`>gchpSVoc0f0&qo*>}O>!~V_Wi#Dv}G9&*< z?4qzzHX(ylw^$#a8k@fLgN*8X;Sc&cHTekU?D!IGt`XVM?9e1!T0^f^Op?zDO6>d1a%*7B&om4tUutshtLq~0JOJ6l8ungYA>-( zB0(jwcIzQlg5VpL9jWt;AovLpFoFB>TsBbwY9Z6iF-@s+hr~4qOxdi?{&>1Jda;sX zB{a^O%&ZlHQYEoJz>Syxy=W?MgB{VLC~K=}pA<&JnZ(cNL9lqa_O6edP&4RBX&l27 zvBt zXZ#!5&LEUp<(6$Z2A4R>IhjbZHQL?hRQ)BQkXqeVrhG!e2e3>`9Y1j|#wwanh%)tn zgfU3{_P39fnV!H;1hGA;n@X01LuMC$r@8N4eh>;%Lr;epU#^69E;9BCT`)sr$7sqg zZ`H3*ugIg%(}D;A$~|LNf27i@&Z~}5xgpS|eQMh8yJW$*|iOOI3=k0B3N{^hkh--^aU^Ow!#H5@9(&I9@!FIKDykFeS9lsV0 zH4$1o;pQsX5S6e~q#1MyRCD5m>7Y1f!XCk$d~fS#fGTk|YNt%OXoEI=O0FKL4)UC$ zqdszh7I$B0D;=?qCnTdwnFA#!pzr+Asj24!4Lybf513QXN0E}08EQ~3CBiP5*41ho zGG$65P|UFfYO-TfE&n1H<++tVp$xo#|4A{R%Nr69s*S&fm|Yk!uZ36h#n zmWC2nmWuz^3>gKD*@{rSfTiG?S^L-k{by$QN0|`Ozz6*$hD;|$+x5-Giz_YKX>%N^ zwwCMZBQXCn_})p9H)Da152`mE%z>Zk^MnXOE#Qiu`=lt_RX~|^V>o_HGJ+L3dV)T% zM_euckYGGVy#9&MPoeUY=%-MCS9bSxfr#sBsbiNyud|i z8|AzSMS=izZ(+oSz`uEu2ZNtfG${#!lc<>S*g$nuQAbrUGmqmt=)36hr|Y1QmyGL+ zLo4@L-LPlBHda%+5ZdUC%h*^>p~1H_eZ8xL zavmLDmtJbDtTEU#f#Bh*tcxsbrs8MbZme{GBoF9^)bBMCjl>;nInFh%&4F2zPHE1j zaQpYC5j3A-exum4k_u1kuC-P0*~K_=vJDQSZe~IsKed9mL1WhI#~FyFhu5NPKhPs1 z&Y6upcoa_S#+JJ3UqsCMx~ri(sgl+@{3r2GmnJO9X{~$ZIc|Y``Qt5X4*bI*mTaE~ z&4rt|)umMNMuK%mY*0c%(k(5nmfa2R7{NIVIRoy2S3Ppb&BKq91LNZ9(r`DY+Z55@ z(}Vf=bvm4?3+L(^XDkh3%ECRjDPZFKJhLH7ZKJKRBY4?BfzG2I+)&;Gj6V5{5PTj{s?-)Fc*(*SV#bkjA1 zD+!IrHhVvU_9c=zbZ3rzo>28+tn_RBx1MQI9T;1Y4iLMB-a=u#^(|^T4N*OsrK(!6 ztiZ7ZBOEXG(S0t2eJ1rE{e5V4WfcaD3(P%qesOtV;veMGOnope3;m6&Tg1=wMe~=qFmGQ_`A1ZMYDs<5K%_*bZz$Okhfx) zChn=%OC5n6Kie}BUzFE9 zFqthu1qCl4g^zk3uK?~T4(7<r?G?(gv4qIa#0N5^7l5IW!J!b5jLu~E+c+K6n9 zct~k6|GF0UtN~<-4&<;B$^&XIpu4!!7M?l_`+U9*fEW;`3m0=F(zw5%+;CATSY{pYiF*!rfJ*sxVTnygo9X>pcq~+E*y+L~L${U2d&zXka?s zFS#r;czzQ9sNBRui~D{6b~S|JHDfy-b=I)oy4dixL0rCn9EXW3P;-CX_v5A*N-aIs zKrnrH2Dm5qot%dKgaXY3`-ZimPqb8h`E5-S0p%ky*83!=e`SBvh$-V)`~V;81g!I-}a)Q#a&Ff;3(>D2=hiXo*s z4^W-e&iIuu+sUQ-N=o-^+T!QlBwmR(T_I4=w?Y;n9fjl>nkYj%YHdBn$dUl z!aRS?Z5v5~rWB0mHMu1dVKt~WELDr2EbJH1)( zM#0}+@md6K1TUr|r;IKsxrrplvtgmVSyR+dT)AQoDi=LpPXCe?&h2_}o=L{VuB?*F zV$i{*Vo@bC80C_;MxEk%Ox{b2wee8a;G1YiM$@JnjiXURSYz+sAh8=;RKq@g)QdJT~Y=F|y#(MNJ4SzRYZ(+~i!wL2)hT0pK zJH7gvW$~!+Kfq)TPo**>>F1FIv!Bf4Aa=;duh+`|&T%fqlt5YX1;3xvxifhu9}MH? z8+vhemgSNY6jJRry|XsG=|ih-$}G@a7p1E`&Qrardj69HZT7hPo^>M50~GO!+&hq8 ze_N`&EO43QA?f^w%@1`AZi|yFRir`MWPy z%U^4XM>u|iw&u5QRfg+gCHRGEyK;%k4-4xNuvIqM5B$%QiWBQWi`YkZ{_U0w%lfe4 zm;C;>WMJq#@QT005$17Wrva#6I1^u8!vZ>Ecce588bbp$g0g5@7wY?!<33V`qSxp% z+MOyl`a^so0oTXxr(1}z7UvX)gh|WHTdM>I#PYeDmMBX^<^|V`#7k5ui@Y=30w-=d zV|ZBMT6nGK>PjOmm6ByuRe0sCn~(dOL%NI-y+D)kJbP1=Msy0XIso8VY==p@>J9J+ zT8|vfX1l9>V}XbbzOMX|G<62NGpO?mPy3-ICV(t%B;_IS;Qx+=ogER8m#DHaX4-NH z-tMQ(h|7tuL{{{m`HBQ4LI6$96+M3;cQ&|3LL@m zq10q@5gMhs0+jH74mZQjl5iwWI2|v+pX_>Q0xQ`f34Kx{qcsZ%X(c^U^lt4s=>)S{ zSu%r5Vj{JrT!KB2iNxQ9gb07m>&X8A`t);#Jz&QC@a60hK& z%4q89ad{p$B@Qd-)I?_$$e38>i zm(-rQjbEdFQ>G=0pSqA>iFF5M^*XCwiS~1nTW%1od)}6qfzmtAi99y?Kl|^9l3&(~ zWIkSUU|ay?h3q-U!fVYcJEspri#2l7tAJs^KIyPqi~^1rl@slIl!eua^WZd5zPwP* z1<~(A+#EGR_VIt6wQcaWt?+cZILlSEy>-|;h|y2C5qA;q7xYFZKSu;choWCkQ9aod z?57Aqz)b(ItFwTLYJ1!GNK1DPozmSM(jna`2t$oDGH@sn5fB(b=?3YLmXeW>7DSW| z>28$po6Ei5_0OHPX3bi2e)~Q9>^QN{-p>=j*`;(BQ&5@&aw&*%H;$m`(qoO43dq94 zbMWx+7^ZA&8x*#6+CB#F^pxzon^ za!!SL!?B|!N^P%LUcNUg^nLA;>@HjXJ|@xWDK=B71$DZn_;bP{(PHlld@!AP&dVD4 zFv#7rl(VB}_y~UDI@G6Uek~c5Mmu;uWf1rL;O8+IE+w5=nvb;C>@#%}bpcKX0r|ZL zX@e2fu_!pTPzq*;j~QwF>+*gr0fR1%zt$4h&Rqtnwg-scBEL+sT9pI*srdcLDnIE5ZGh zZ0L@d3yN-meU=8vPq(y>TtH${Raj_4LbjZu!8v16D#4mLVAu(KSM%z$9eW`ZhV)ury;N_YCJ_pI<(y@OF~W!D{v>%p;z=M+d}|d#-{2fgdRZ zvxWBleNeQSq3F{g)>bZC1`p8+=)hJIIuN2%p}sR_se34t+&HP9p&E)UbhTD(SC*&s-pu?lV@e@9H9Wm0F$Fj-^u25jLG@DhC-)Idj(tQI=R@UEz~P zmp*Gx1+z*cf8LMZv|zOQG-IH*>WSM+h}Fl1l4P+FQq_UQB-y8GH~C9J79;-IRz#5S zqmH68*ST0x{E}8t*_;<0Hr!qr#9e;4CyAJ^mG#N?!E}n8kD(QmlMPo@AjuLnVd^aL zALJckb(%m|eUH2JNYy;d&A3oaeK7AqdEN$=E9+Fjogv_*s7!vQe%?^O^O4_ONg0<% zsYa|*uo-wdKEyGJ0+P%q25#hTEm1D>bMrt-DSLZFZMCFd)C&nx*X<2EKibQCg_WzW z463kSx10$%a+;B2AQpc+VQ1ITP>x-z*I-5seGNEsDMlH{GyZrC+C;%9D6WX|0wSDk zVmrno$9|p*7DD7*`O-DIo^h=iR+}4 zC9Du)RyOG|+FtQ%OyjqQd-kR#*VUDI2k_S~>eN*!U&S$jt8Qs~-58(|WPDPXe2p{p z;;(;g#;%M0N<%*-Rm#Wn3;(4<>#@;`_Dl_zdub>56-M_owk!-`u`CgGDZQw=p z4Niy21kmC=4=c`(T{u4GeTNHr<#b>tEc2k=oL9jS&{*{no$fmh<$)pAz|b?DPRNU4 zfL@t_t4^_7=u-^~h|D_Y=)tfte^&S;A$7Ao`bn!OTjoy8gd@AHuUlemT186uK$d&5 zvT%B=AFhfz?$PIMj|!btouO&PQ(Wj`;p#g z%#H{Wg@@GN5neMtcQ~s=fD1ZDg0c+J`{NsyGw+G=w`xk!efXkkEU}r|O#RWt-;?Wi zWc|qgNOk}_JTRy3)fUe3ysz_~Mq(#Z_Mz3n4)EG*rlc=~Bu4Mi-{OHJ&O3_?mGcaD0g zvWdBz+JKd4>{pxq-GBHfOGrX!9ssT|Z1Gs58lOGW9jKa+oIHyh*Ap{rE2%7PaSbZ! zRvP!kZkQ%4xacC5Can9mqyQ**-VNr9-j<(r_TnNeD}6-jwo5kHpsK#VN?mN)0UH!! z9$;FOKflwQq{mxH;aOGYdH)0Dl8D%$??GoB8lrWJCT;O3inZ>w?3whUtI;HXWR-2S zo&9Ti=+IJpu1w_~wu~Wv7k_Zx9DA3`ehVvUtRU{5Y7rLIH+)2&)i@x42*OqRo;f3m zuoZ30lt)>9%%R3g*lUW5P#cd~p~e;ZzWLmf=UBV$8D!hO~a$uF<%;tcH`-yhI5$vsMzhmklhKTI@?~{SMd*%eln;+BM zN{=x+q<)>EB=RolOsfmGq;w-%HPMP9#6ltMNqH#aeNS`I%t{3R5Q*AYqdf4AGUv|6 zBffT9rXwmiJwvu|5&vwQ*=|q4VK)Cy{DYTGO~yW$86UBhXWzm}lun{i4# z2Bza4Zbzy2Fn-EmN)?#^0Dirgr;JnsCESJt@dWYlnT;w~VKWhQl-ZSvDkxG@b!`oa zJSubV5+7^zyoX;6H`kMjkfq{|p_Exkyvj;yYw(}mPMROFRmkB#kuevXlw7Lr((ZaX zl^&U0%_sUK+$JjOy(k|FPO%-|cJ^JjJFOzUxIFJrFlmnoLKP9&r{$d~DLaQ+l0p!t=4cTWzbqGBn!%9Oc<2CJw%tEpDo7dSKtSIem=Y!CQ-$Q61QhS=Y~ zzA7y7bU?SZr1%PPlQib;PO8bX^2LQ~A{z9Kf{YSo$%+=T7^=H~Hp3dGn5`_E6Z>&i zk0(r2-u)$<{`&V5mcthc@9MPgeo=sZ64MrR!w^le6YF&l8g# zb&qnX!9wS?RXZf+xM+Y@wP|CzQd`UgOZVsC;}`NKN|;J#)bk52aEp~=dpm8?!YG}n zx!Qzgcik8WbJ8LVkfsTs@iQ-M7H&D))I?~Fc&`yF6;Ms)2>DRYSzGKJe11=)JX**c z3&*{R`$jb_Tp~z2I6gW=NNl9)VQ@cc`~acCw60JUKfdm;?kXQAE0U30`x%cA&CKvx65fp#IBqRvRi#9qqcr9fltei6>QW?I4tA?yb-l=6rYAdVhCV1N?OTO zPT~)Q-F21sqd27_iTY>PedB}3Bx9nQ;vY;HdUCM^D%6PG?=_{EmS7|}l4o0DeEOJH zy@0C4oB_|1=vfpg@9TyEXc4REJI`V?3IU>?={FD8C1P9yUMn!y^G5SfeF$2|cEBE2 zj!?l^x@K^N1AZK9j+PHXKEl+dl;iA@2`+ZcKAoXjj^{2)Dt!xLY&anFsO$3@u|jB% zHM2K!wUH?qtH~eaOC*0>P56AkC~F_^=?G^o1n25tutw&gKvgS6w5x%sWAYmo`11u( zS>sOq7yTZTVOq`aE9_FG2R5f;KfWY>%q`|$owrN^(*VK>Xrf9SP<}rueSfayvgRFS z(5@oY#X+SZ{9#ae`Pu!|b*$j$L6FFH$%L%2!=-KG2jZIn)YzEvdcMs|Q|UozELYjC zAkB8xxKd}N?UI%$$-rbV!qR9fs);ts*J?V>!#I-6XjvKhB~YN{GqLt;GU3j6lQIQ@tt~bmPPnk9j8_~Ic}jYv>nD&f^2mSx zkT>e^$l(*r9`iG`b=BgKRqU$gPG|<7G(rmZ=o9cL=jjF3_%Sq@u|p5p{M_&w=_Y<_ zefIWmit4`fQN?S{-UL`MqDL7Uysa9@YMWO?TIlF1{T{~(S zMk9u&8z#+2$tT$F-@LVj_5{am@vFCbKatC;KlkRevzZQM7>vM*Jm4(aMPKAKRExAXhvHsJkm zprJ5Q&N3A9-}z5?wV3eg8Zcm`@9sIKM;cPOVEav=6WO~;_}oa|rXmttQkp1y@8V!6 z3n|rF_Vf6>N||ZkhFC7?9-;~yM96i{FF#s#8DRSU`U0u*vnIVZGk1M`aYPY{=ZrhA zqf0Zv2YI%IYUe+pZ6x+3uT%<==<;~PXM1dP1ADBn8qFV_^PE z9AvJ0Sjk#P@=2AMv7UfvSG>XQ6h>8zNJ=kmcu4#6BGt(hA=E=!S{m* z$tWM5^4h1x_0$(5C9Z&IhxVC$-^8_)$h}8r!;@_**4d15Tp|~+w!`ub0xII{p$9)m ztKW)hljwpa0v_Q%T@J!^%eD&~mmAUgMLB9y*}0QKEnCjUX_$^v@5-P{44^x zvFHdT!=fhs?qgDlVl}v8fdnJ3_VOjE8B|+xfYd!vjM>sgO4_Y)S`NzN?+|X$EJZSd z^X)2BW{_Nvgmj6Kq`ZeMAj1)0;|Ru7Y^2PjAiTJlGWYs|n~4y4O}}$vj4YBR2DrOf zOi+dBxUWgBj)^vAd#ppP(g=EWI9#TZQc&<59}2tB6c>63)zVx{HOK92S=)%+rAKdx z`(O);^`)KtW?Sv+#^29CZ!XNaqnen&w$od1l`85o7NRwktqwnB{VcOKSMb=JLOTVv zdy$1)>*_ss)V?Q?4f{3l66A)!1WHUG>C^Nd{8T+n=l`F_k%S!xF5y!?ERYxn&L z)As1Y4BoSZq6tPvrp+;90oPSD^RxLkx-VapeDiqwBX8E}v(G7(a3goUNxJG5(H$Gj zEh4gk8bLI4Jj=ty;t-&Jp8RZLPYA&be_D+$&JX=$`!y)L%$5v9KkBL zv9xylUOyINipAqhVrqn%$G}LawpLM_o2L|2LfeQ_-UlUUkkC)85qAUDBAS#IiZT`l z-)ECLr}=L@@Z9e8@_Pi zvdbxMCOGEwRSTY;zjOy6_{>$^>{M&LcdeivD5s04>8pp>9Bpqj&||W!Gn^R(%bRSu z5=n$UlsWQGa4Jm<`u;H7*2=lw&lgQ~CGU&K3;fMtXTn}1@Y!ldpOwi7vXw}+G_Z3$ zWr#Au4PwXy(+g;-H;^EX(#ZARCWd1plpM?SveF+Au%eT(OMd|<#ri7ZEKa}WnDLj# zkSHt2AD41;CPj}Wg{-)%g=t$9AH%xE6Oz~FERHy64HY?-NnN3j8yeRsB_iUWiVUV> zJAyc0n-z8wx|sunBh{sQn2P0u@}+u$C&@=$h@Irb@AMLwg*&rsV(57>yI4}=dW7gWD+dAK9ocyr1*1@d(E<4;_ zu*B+lnvOHuCDP)_F)@|-8EXVXwqhnzMz4}0Hz_3Q5DcC_L4WfnvG^27wFN}}xT zQY-gM@AF-IzTewL3(0-1UPEW-qTIs-hB5fwc`+ZhP|i*P3!<|H=H((GYAPW%<{^vz zp~PB~y!&kS z1}0P;$3~k4z_P8WUr{z(UO9bUuOhvVJ3WyTwqv}g+0)Bs9efE%pvaaw)c?_htHo5l z@LQ$J?|}toG~B(W!BjdWEll*;M9DQ(xw@9!ENPd4b4E{*Nq6o!ShTq1>Y!R~LNubt z@t#Ub0uAX^^%d@0(~8vI$1)EnoW#8AN- z8^R;=#HCMWv6@5Nbg%p2QzV92sof?rE8hBn_b)J#`FK^@-?nM3aA_u2S$4|Lqr2^; zBbp5@fuQ8e4vIC|5U2~jXF;79YDajIhD&DqVnGLw#0wmu^G}8Rcy7LTLL_GQTs0wk zEaIQuw)$@bmn)NM+mj3*Hq39vThwUdHjRwVR>H*SpuN^}{9fC=j5SZYSyb=QJ59c> z1s7&?B}m~f7f7Xavq{9TB|>}s1Qy~^m)=Ts0JwYO(+sb;22Ui>?>s$w)uofSPyCUr z^@Zb+M(%>!%W!WzlWGNsC97Tf%Ajr){{}28NqoV^^qI}*A$^S!(|HH(#hawIeRxo) z^wvJ5iQEUISO`mS+Pz<3_%S-$@_^RZJFU?ptmcL$vkj^NF$-$S_NFgUSeH`YM+xZUp*51iQ|E=sX+&nNUr0Z zE+hCd0Ks3s6>zf;Yr3D1`@$?H@~!smSdI6M>SG?gOCcz^?-Rq8HG=Q+T%r9%yq5{y zVc0SmvBr!+=(1G}0g;EpgK9(GeBSL2$_}+y`OBrABdq8bf;3ppu+f1xva6ADDPQJd zN7iC3vJdsXc1|)NHvJLiMI@K$d9e^$^eikumSXpU{;&DaAqo}iyqF+R8!nux&pN&r_V0>jk^7~p!w_9r-^n*A0jR^?KchGzEBs)O(S+1s+rV8#Sv~1S~#yZ&4Jv`*7s$Z%5>3{1>EW zV!4TGw`<+jj)b|8RyMbzerNs{o?~IXfeDP;@qLk{BY{jHek%(&?EeE}z<^ZjAnsecT#!Tp zOmIjUEBKG|+kcNbQW{=XrUU-t8-yIIxfSJH0SVB+`O6i+e+(f0+Z1`#;Bn3PJE6p&}57@fJv8@ejxj{v&t;0`c5}v>`XpZ*vTI zdnFI}kM_%dizmSCACL$YsgVP>DPjiySziMJao&pB>;4aX)2+dO7N~$gOt--LP$Wo> zT$aNQ{SrLqclc{~hgRxD_QO0ttX`s_WmuI%MmmzXh>n-{eUs>F+-A@1PU1 zU)*k#y}38wS~WNL&yytx#Ct26SN;v8Tq6wr_gMnj9d8#d&f6R4?}t%t@Sl?;2*hzK Y8c_NV$cE1hVg@bXAsxqS|2jwhA3-~P22L1Vj7W81cETWxT9Kkvu$<@y2F%v!T%%}hwp z_r62$Iy)o)!_*X9C^HJgt{?GDBKGR+^H05URftqkKCs5gQYNwSD-jC^P2J;1-a>w7PlCoX^O3g|Ft2fj@> z{hlP9ZTpC|p^dX}HY3J9jr5KXF*=BRS|alB#}R1?=k1>S&me=`s?liv`5iVWKxkkO zK+!Po{dq>#EE2{IH3v<+tWoT7oyIi%^!pX5;91U7GW8Gzz!uzWHq){s-Mb2r_0-&O zXgp@om_9CEDx;~t#4OYOO2cLjlZ!6u?f4pM5$A_sWJzS4Gi`24%`Dc}nFrL9+?Bh_ z(C)7FyHyTWRs&=F&H8NE6&8Cw^H4r#p^!0hGmK-1O0sN|f;ACs3fL29n(ngmox4(< zPWj`1KlfLe%7*kC7??9Cn4bWo$V>=QY`_FqsBI{st6&&JG$S}f$iYk8hHx8N%gL3f zGo-wVD$7LU$PwchA+bfA^}3g4WT3?*ea#ZxYQ#y;4!&M`y`pzV`a#*sdGq{b^{Z`~ zS+@%O_;~&<3>$-RgN&4$zC*pCzlEMwN>6rXfV9+y!O1T`6j`I(X?V~*^tB^t0c z)n~|bB$LdI6E8k}hiQh|8{3$bR0V)^k>8)b`^!$5{U6h@0p_2q%ODJhA zpY1a0QMS+)V}~_z6fO#_m1Yp!2xB$TnI}eJvW4wtEty$BEvr)lcKQK7>98}#;mSSV z)JZ5Y>YTMimPl~~wB$i=6Ixg@mg2;exd>|vRDDyN(?rKrAf-t*NoV(yy$)a)bFip2 zwu;rX8@n$oHh5uJ2CrqIbssjuDN8h@f7a?X$%+r5=uCbkpU&znI##chU_@clrYQR_ zBZhGCq{!XHA z0ziZeD>ECN68(pA?{R7CIB+nqjqm?Mc`iRPND&zsl*j-L`h`va>ScfifJ@buV4&U_ z@QeKMWY-kLu$50794!7u79GrF>DMBFbp4#!WtWQcM)C4Y`!{ z4v7fK_Ty)-7BC?QQxIYYXkKi>OY~WDm(JjqZba30>eHrb!c>iyz56aajG|n-Jdikq zyX(`0xt546rzw*hk^1?Z&8e<6N=&?RLk;IUK`K~8S=CVCObYWzNV#mFOH8=MTm;{^ z*=W(s!`Fxw9Iu=wDQCrb?iBz{fc?UbEtua4TOP=leH^ycXAJF93@kPJ8ntlzQpG@69r`++Vk8{6JE8g69&V_R`+N< zl@6=aOU40j;;+7|=e{QsL;5>cx%O`}9Kh*T*2E`W!qMHFPVr^tDdIm%oON2Easo!? zEhP=Smd_u&ky46A5-OnMpH|kpTYuVBIpUVdgnT)1tGL zFyA4&++K3TR7t0tBuO^Ob>=f(v_?y7t{5DkG^HzFJ$kX}{Z8U%^fQ;tS1KX3#BW5r z=z#0DQs<@U&B{dP_!Y_l&ddEy z{p)dT5y&g-ky~aNRw!)M=)c^P5ONdJ{g->qAQol0r!`G7R<0iIzcQfizsU+A&*he?NWH(|DorGvUb%AWT=!64!mXQT$Qv zG2&S%TJV!e!JI1a+HG23hUbLv>+gfzy%r_Lb{oQ7Jl&dki&Iz zV)9G?NkM4AKrR0EsRWb<#k4}w>I2Z>6&_(__~49)RkXD|K`UEZZ8oZg(H}}8IMxvt z%@^1AM;5932el*c=`MA|KjuW*A+4t;Ku z@B$64823~nAa+Bt9~US{wK<{phsU*_8H3014=|%+y6X?aHZ|?*4(qNb zvW|Nx;2Gu(Io>H8ORn!nG^-`cjPoBDrleCyT(#Fv@}iStDY(wjTlzrY4{qO)RI2@e zLNulcfOdZZLX-vGD|?Q$!cK9hXM$G9+7>p>j-xK-9uNk~I#=cq&-CMapLY?!!T8_% zSHqV##`6!jYA5#1mD%2=;Z74=8%^`OM~`{0j@Uw-YXhpIx^usA z_YHgqCB5RVWg5GN5z>V#6?GaS^}im)XTW&R)bcHWs9-BP931B&lLJXRHt~I*lWy8V>4u_(nAcBiMEVIaF%COP+k?;&*yDTifoSY6yAP6epn(>msHdDtwjIw|ZYf}j?XL@=Ot zeAVSH(gY3?S@&6c;b%3K{2T^X9H7*ZE@M$Gikc&5*+FU*+D~;^y;6uF*ox+R%{3gR zAmr2q9Cp%1v2X+beGpwet#$NvN$xM+x5(`p8HtQWaw9Bvz>q zjoDVgM(`8z-!fa1Fj9T-r;q`vPUEe>wMCnaKkkdp`eU;u#RxB9Ayppu?f}04t(6yh zv+G4R+%JMO!p-VGVAk-`ci$EbFR$zUSAe9l@Z@XH%;iW z1$keM;5|n*uWV055_a``LVyXRo+eTRJy}6vk_cXGj$p-J;MihV5!|&7qQMZ$@wRzF z`+;G(qRlG?;jNoF|7cgPbe%bzz%@}D@xG(q2M^-N9HrR$HDn}Vu>y(R!)H4pP;8*g zrGG{lASp7CL-9bv?L))p%5vU0RYcE@xdq3|tM)BPzGETSALhGSI{;mJW4Sm9C91dF z0@`&8o27y;(P6VUNo+c4*frZ+el&S8!_*Qv0{(B^W zQ5^HfMfdky;eIqlVvDwKT6rkn1ez|T&Fsfc zE(C=@FHgzU?r{&MF#tquClE&(vPZoHupON=&JOB`#9n_C#KXR@Z0XpPTIW3h%&D0z zS`UK5ocEjeR5tisd2*HO>^y#UumUqsnxkj_-jRE{U1Gt|mNTZclod?W;F;i_p0PX0 zK_(SC0HDp(lY$bTC3${EtH;23>b2P&)n;CKNL-wNQx>CvjsaZkAdTWf`66_zdAqWy z%(tq3%{mTzlQKKr1Y5m6gTBVNmvfsC*QAP|P#L6RjuBeM`tzR_kP$HoaZTiiGrKxM zrFW3gzarR#@R@cj`KrcL?)d2@v9Q^I41a#96XlWMb(1#%P>qgN*0GQ-=&J^GF1CXb zox7v4i~X2>CjeZ(&E0y)RE@~Nan?pA8Vu3>7DtOx1o2c>(8a@|$S z`hVX!miLUc3Il2#C06%&(K$oO59V1HF#zCL3I7rOHNX_eRjhFYJL$C$xd%(zhhkBY+rS-kv z(SGHjpPIzlW>MuGAg(D?+UP;Y1F* z&JC5LJ{R&5c4}`M$a4ulV*)Tog0>BC<9=k^wc(8=<9SP`Ht7Fqo27rAA-yNe+!2=> z;McWM#*Cg)9pmQ(p4`pGNw^P_uEtO@@pn3yeau+{PLA>VRaJN;japMP9N@399n3;+qj)2KJr#uc?-xGE3Bi zrqmDI)TZwB-#)R3T!Z~dtJk_a{K?y$n%sILR5-ujP=ah3Ba;1?U!^iwWtqm#FoVX_%A6KNg zYip*YR_8Z%X6Qe1ZcmPUgU7!lk0LZ#Hxr^M9`ogCq~fBnFoEM8@N&PXhwQ==oB_{f zmnNb$^kd_s3Pbpt-@f_-zJl{Q5?p4Bc!)?Zk2oZPmzKO!#@Bx?Ny*@vI>k5eDQNae zcv?ZZ>N*Y69r~wk@eFMH=V0D(s_0ueO`Gz4MiIOwdc2}~?x8Q%G1{em_s7kCvQPCz zO8vzCul(9slnfg|gMslPgMlf_fiU%O{z+b0fSQBSg7QDX8=C4MF^qw_GYhxgm2#%< z9x?|rH)tM$8k*$fwPm1X zyPh%H0f3bc7{Au_d==g)+PS!CjW#zIW)M^tX5?-(5D>2Cvg_9}jNZUY-3rf+Fd_pG z8t5js@^7HlWh3~4%dG__oPB2M%;J2zG^@7Ae(m7g^978MNX;G%Gw{OMtf|86q+$8I zgb^vz-*croF>%Eo;c=KW6_8 zzQxX46A@0%>Y{#<>TbfkSEk0XD*pi(6JUlVn@W5(#RU33NMDQeiosP4_BhG$`S&_& z2}KFJWSQs#bT>7V!ZX7|XfQ#e=FGu1z|M)CW(biFXSOjnO{eZXzs_@K8;zF!^5&`` z0w@Up4o2M3J-H(KjZtKXPDm?%aV`|?vGV9X{WOcb&pp#y4(dG_cWyIvj@2SN3gW=kRYLlPwoA?1O6z}PsM=+Dh518#8v7YSkjam5tSUkED z?wMk6X69}sD-}-M8lTbcR^s|I2wmY2jlzjA#VPPsP(QzLE;OtaKo<3!m}K8(K&H`` z>Syrx-}M=^pjw}4=JW?u!Ltn~rkP57 zuay7SSEc{2uR_A305Q@)fe6V-02hkrA{d`Qth6*&8m@0DE|3m3>8@(y64Dgb(sd}r z$$ui`TLymDbx<_uh5d8!^7@EuTgfwD!30z8?BT~tWV}FYIXC_%eCa$7e`gYmz$oi` zZ{H5h1wK@!+yacaAw49QycUZqv9G=_?C0vZvv+8tgvpt}Uc<3oyJ{_X0m8d)((JWz z*7nlqlFx$+*4~BLCh$O@gM)*G!PGOlubgBH)ZJ@WhuG$R7I`Tc8(ye_2+?+onA^wE zL1|sONUlE@uVHw1U13j;+2q+DpDY|L5$ppWFNc zS=tW1SGRXws9|#$q5`@&A@vqSk@*Y=kaIA2sP_s42o9V=)9|$FzNtVK_aV*aR}v+i zO%_%BTmWOk-3x-OeP5g%S(M}^S@PvhA{P^&d1>3ZYqIK@prt zpBfO13B%FDlB0*pJ%JZp1mTW3*W}gF(u-Clv6#8aE^DG{?aKc6YW`W*(#_3AU}Dyf zL4XFqMcl(DHxa1>z#XCvgD2_4-klsA;sTTu^Nzvtsu+*ge%DR2NQ9ug$8u9UIhnf(rLe!8LQzR+gEYG8bQAygtb zUs?8r^2P}grJ`678x`h}%-2`kW%@7eaRm>Dmcc=Ydc+_KDrtZcJ_`x~h)H?@h1x-> z>lZgU=7i`d38Z>OoO+XLiaNwm@6=k3y?p0(>Q!7~<-OP|b~f!(FY;+ZC9h)WJboo| zVD5`$uGR6%O&&7XZ14)gwWAYL`%Wh;@<}=A%_4l+b})9S3?+FBsYYP3q;#ib)FyEh zo8!APaBuT4>JFe-rjN&e`+HT%`#7dVs%*irWk;pvT5ws(jV6kj?V3m}k`@b21s)T< zL)hVzX}=?aD#AdhKl~*C9Vhghdded*FH9WjN_|A+mk&7$ObLvyO|moQ)7Tl^3e?jl zvzx#dqGX!hFX1GSgG?rG;iayN zR>9%+lX_A@^Y_krBKOJN^0jlJwP7K|>^X#r!g+oX3tWHu=asG4UwXZ30KR3j#=JJ2 zj(HfZiG*@ikhP7@5FtZuUo#u-;TXgdMV@rAM~bz)*Ld&dqI*xVbwna++V*FV)r+DN zcUyDv4hpm5ufr2X%Ujzc5hvH`0Z#gK1w|yUy&<%hA4)oq?Oge{(EkPPaxdbk@Sj&6 z0RI2^kBl?~00Sp95e$LvsU@we;MLYunk`G<79^y|t9V5A`)Uqx92~EvKnv~Wt=dV( z0G4OK=|9IDlt!8P`u$zyd@FnynHeNMo!$1b$!B%_LS)qa&AM>-cJJ^|;-Y$aZ#c=h zW4+Y!v9Z$9JKkxHzmZ?dtFwmK5Kix3X|%|LZlA*j4686ZgF7^gTnVdl>?{&oUugcC zv**N%i@>1M!+z@uc0fmcYzxeb@8@99g0X3%tRE4DQjdAnyb`G{@fxasW<(rLTzi3< zM^R$XV?NDgzbHL4&|5^@sC4p+AK1D^q7gV@MR9eQN$}l9CNqF!LwJaI|GDCDo%z%? zUBD~~fTRJEr&Edrp1d4UTf~qY4WU60>eOHgT52;X3@fl6eNSdcMON3BmsYkcRdzOQh9HtE+R7-Q!N;`XA_pK?Kg5JuR zfD0%3Yg-6c+fz##vgH#**t6>iMb|1u>AX`0Xd}KT3s+P&yJNtt(vBg&uGH=|4O_;= z>8hG!Zcsq)OWZ=XIn8zXqPP*yG zU`=ieYLo2a8rBa}0$pReg0!=5R~DP$gG z?IMvSQu(ovDs-mgaz=ZlL#_!Z6po}hY)~YYm@i6=9Z2r^C#Ilbj=4*5NdJ{Q%m1^n zqv?bJNmGgk%qSxxDb32%DL3fp*2oODkkF#VJQ4C zPJOU8$oyc);W!cZ6dI(e{6t@OPM3EN6JJzd*8O;)e>*xFmg5c{cHuNm?fFDjD)@rq z|BBwLTOSScijU)`jG~j*kDzm%nmDH-><_L1u3a;Xx6Y&-C;!%r;!If<&8-&dF8J>3 z5J<~J6_0G~U=&7&iL#4Iq!1L!lw%+1WdS(#93#a}JmGLcRi%*SgCaypL)$r%uyF}x zAHiul0|-X+!yQO-TtWG7PnNtiO7$=x1ln}}QGqdy!<^T2oMH)TX6koL+2Rfa*QIs9 z8@+s=J8ZPFDYK41WllP=(}(P2Z2)Qwr|N4{`K_Nh zS46cBQ17l41W;_c1a?o`woaQ#flvS`&Bi~fuKA*wgMtG1p*~sMgoA>afX#GivZ;mg zOD!-q)tUoQ}XocNn?*e;=FPNdRpP#Xcj`7Q|qh0?Snsxr%->UdW1k?XV1g;EtecwgK z3<#}<0X59ep+Nj{IlfI;ag}Pl%!!Lk0yld4l!+sWb~?JU*Bs!1GV$usx&SZS%x?jb z;wv2t0TkAJU5wh4>vY;o8l=UU0Aqv<#2ymFyFpKgfkGyRt>jJjFh}m@?(+`Dmq}Wd zuHAp|e{O2IdAsR)@+JQuZ$`aWE>1G1_6qj`^ggi`hm2ZKYjmJBilpPB>FXj4EC~em zdPMl8b)!lWsM+>%53rV>WS9{)#N`opAv??<5wS#We#LIVGExfmj3rJAOgPcv3?3oO zkJ64B=M&MyQY$;t+z(?s76{!_;y^K=3Lf=EH{#XYirNaL@08Zvpq3!43`RIpWRCa) z7y)x4mi`Gfiv*}}kPAP@m4_}|UVp70AgQ%E7i2h^$%~bwm1B-6$w4ESQI+5qT%FRX z-Y01A!K7nO?t2P3?ja3GN5I=076Jy@qw)>jeI1l=_FMz?M83J<9;y^u{F>)8#fcXG z#j%;0SnEB7Iyz51|Cot>ILA0TA?X(lU~q`ChbzVrdt{ii0Zz;OE())1i6X+u7E=}SzAcnH3KFZ)n0d=dK&RlnNF06qVdu-)q3+9%o-pcRozA-SFRxeBRA4Ie|TzMeVH> zNrAp2?>FdYU<2`pV(HxOu3JqtD>J7FrU2}!m};2jEn$qU4A%9NS1GDkdD+uIFcO;DWAGfVC{2%Z^biVNyE6jLbu^RZ|;*kKk6I_5;D zXBW8A6{aMg%n-vUj6XT#P_;M=m`6)BWYg(u&Pl6Jb$RVHX*ZQeB5gwSn(N3RZ~;g= z2k`vWZbd26Gu!CVWF|slZh@w@QCqzp3K~4aT)p&s@4OT z37kTLvQ~xc8klFyspE!rW!zNV_jViy;C5jXxJ;hEU+@1JjYzfQJu;<^mr#ST--$BslXN`EkttgH%{4M==Tmgs6$^MF0B{FNfN)>kwEfP>}E5tRd`ryKE8X>A%PFLwRP;si3o9}47SItcB_ z2upMR1mt_~$1I)@*jqt{y#NZ}>#_@3JEN@rjCP5x1kUtrGAX|cxxVGkY1aW}f{d!l z%NPc)#tj1277IsvZ458#(~0}`G}e_W3q>6fj;c{Og9thdi7Z>yYiSSf+Kl*Ilp1B2 z6Zx2TGj2Vpnls+H)wt+gT0swruI7kS!y|tzNvtA-(60wc#$oufPJr~D`v+yj2=4m* z2B%Gz`IIc;?33$)}qE zCor_k`q?rJRk~!W!a3l9erOJ=TM^k}qj~wwBQd%zT zZ|J&#L4V=*wiN8~pM6%3tq0%~p@@2de#G^N?n5REzQVT8UWMw!{;(z9uwBV|2!^N9 z?HSM-t3mGy?Mt_gg4DX5W7AK7Eb5}e@diF7NVgBW(T(y;9B_Sm_P?508N~|i5v7fX zGVK#}=YE4Ds{-Ksb%+pXi3l*A5Y(WL_v-4u(%1}u?GBmOUYVK2&E5A-mec_5%;k}d zsBY0YI|>;6t@`Wd8bE|~>H|B!V{L4Y7_c2KeH@ryVu8r8N>w1zPhJPKgy@W-RB@f} zj0+3r8YcZ17<^`sc^F(^-mQoJg#1raG0`$opF@CwfzQMIPn#<;ql2zmi2u={o)*3a z#wQZ2JPx?S{QSHoxq@73?yiI$nq=V>NDz!zDN4F*mwf1p3rr-ifB z*rl5Qem1xptHhP^DfM;>IJ<;7zVQ zDFrXfQpw9wT1G`hWi_@OyYk^ip+FYiR3%PzntI`*ak8oY#BYP#YNNt9KQdA_d@x5Z z1QU4l%`8z(a%}Pzzj7EC9GH=Cq(D)1r!A>w)`GdPzlK?)to&#n0@#;vX3O4ILrVEs zdiu6{JWV*Wiq?*!h%2EI-}L@ZrT;>(LW?&U(`;JJG`*rs-RBoGnmfc=xtgl0cqdU3}_vtH-Kvq$1iBX0;MhS@rAzbSrWoP1rJXj*H)V z*vIf^C4a^BXW*vD2Bgj*_h1vcdljLd=>4Mp83xbF2uFu2(0`7|)Twc%P+5h@5Bm)_ zJzR?EPuLbFRD!LWT0No~F`-?Me?w{Biz&{Ecqu9r;KB>m3<0g)GPGv2;<_8#MBEoe zG^MYa@4Vq@6)~=8l%)MI7ZX2Cx z|7WU=;c@1u#!*rjWMzeRA=-XXHD;sjdYTWxO*F83WcQ=ceAQoOW}8(#$K-bsxf~ys z3%yw_PNrmFSR0KlCW^}CyO75Og~o*I`QTqxO^Kz?6)eRpPxj0lWZybU-&IstZ|9hw zl^8LN7&wJR)c_q`^p#{~4p?%DTtq0&{XU2NM2E$)nzorHW5Z1m+1AY`Q(QV$mV{&D zO3vSI!6tNQ*15HnH9j!m)1e8l-qXzRa31E(h_}#R+sWwSFL%Pjq|G$?n9u{F8-A~V z*rMjvNZY|#PI{Y(sF?y7#Y<)g{C0_)89Ln$LQNt|Z$RAaVp*_lW$$Pm2ihzmU*ZuD zcp||IG1cf6R9Azwr-gGldo*2R6|S!u=Lf-TW*eRNHzE(Q!Y_C(nMOzH`>62!?Co`# zi~jn2ftZEI&9au0!zG!Ml|5zNu7FrJi^nqb5pL{Hr0*8`821#((D;W1tc>tH()UYb zv6THxEP&}-1}vGM=HB6Ftd{d*W}R+fKCG*enuxSL;e{MALp(1eP>ii)Qrhdjx^Evm zCdRX;JP=xt@TbK3XbhO|Q9)t2XmpK_gSC2fwNPL9v?CH$tm?zIz8^SToA697AQIdP zlgw6(iZXfr;2-z3L?&)A(N6&CusUybiIx6^aX@VWng8P@!~|yW5OjK&#&J-E@vIN1 z?zHnO_}d>vHHc40{mRE4Si-=ZPsr`Q|P2?ScK`GnY&f%)p&XsJ*_hm&) zw_|K&%tV4iR!zco80DeU^(Y4D!IPbZ_y%9NIR#c0w~cyXI$q&wpZ<~W3H2`vu&0J~ zaCq;B3d95@t@%i;pZ~Kvjp>ImLjUoU>i^NyA6`DdgzSJYhJe{pW0NgWyGK%ZIZkL( z%&Ra;UmT=_h%*mm%h~B+pS&tcJ<+~VYhp+U(XLd~N(diU`a`Ch)$zsO4|HKWZ5aY^0$s99zgqCk+Zs{RDe9yQXn$wlj8)JPas6_&C zzM^9z%Bz+MvCM}4w>~L}QfP6!CuLaGJ(D6zzDV%J;IK!_lbLR|Go9?rE@Sv}XiFeG zJk%%nEoqTLCwS>|kqN%!1KsS<%xG;t@w=1(t;SHju!Y$}X)rI=x$`W_={v})PJM(G z4^dsE$^?lacug&kNmu^Ir&(WQ7Y$mE13%y7va$(8V~Zn|_IvOB)f>cAHCLliuuXfv z8&vB5HpL2=U!IizHE6&7Z8aJIJk;#m79=qQ@Ux^@j!V)WlSIRb$x-Xola;ffYugL> zCl?wCsEs)9b+JxOJXc_Gf$s@_kRR$VQ7oz8$a z!7U*vxDcg1 zm+;=odO2@u*7nNHG)73(Tuu*e#Tg1INE@3)rf?eRPf%qrA2;g}Bl)6S+2Tt+;pcZe z+z(?{wp{%Rs&x}OwmIDaX!{X^I~b=FRC-Gta;*4>c8-)~ZP+m6#OUU}{rD4kMPQlV zZ!B)hadxHvoPV6`qODw2>vO!cFz$}}U=N$uw|(;a*QY~!*-C0)b&pnc7gzqJ9LAO8 zpBY?1uuLq;l&UcO`C8XJcl4Wr@JRwMGGtFr{t#g&DgLj|l}Tj@K#bv!rb*9%kf_Q` z5t5Y6-iZweQdG9A{3$sKHGPV-BG>2CcF1vSH=~q9_%sDSNR|s5Se)@`97wd-9d#W-NJj zQR+_OHhde(l$to%fUCs`7kW`bqeK%S)C$9ZACZQR4&SYCJ1b;3ETqO2*&N*XxPVg@ zvvJGe3S+Jd)5Tk4RjY5nSw3 zJ3UP7J2}V`=ct0s{Efl7vXZlY!-Fn9e}*2MznShCH7_6z0113pY!5uteS`@D7A#F3wV{Z`tm*B_|K&B6- zX5J6uXsigG6hT2Z0mSJ_yyhL&nC6Uc5eBJAdoTC(?LXnv_JBx)_8r8?ObmilM+Q~% zBY~JiSpXI)eU1ylC;=Pf9-!gI0_AJLCKZD!643$)>GBYC%#cFYZF|aT&WoldJ1OfqPH(fq#nICT#8(v^${3x&P0Uwt4B$={J_;u`!VWBFLg1z6e=1vTMS<%}!@c>%d{2WP~z^V}ebU-$`k-t2e+mepDB z)p`Gx0e7)k1@}|zD;bg&I4#^Irrnr^sUnb(sqSJm=SC1=g13DPc_f$`NrFL}B{JuS zlgfn-GSjl4$qZTfnl$@Ven74K(NiUjcPWMsfU;VC4AL6j-e^2kKGyuG>Wrd-wYRcdf@2J-VYu%Vqw?Y-Wf7#2T~5gV;20DZt?eL+LF zlFh1ktdDTEXRY=N8=vf;@H1jQrG3AIX;kvj0N?W&>v5rsX=#FmI=y9o(g`h(IPlJE z__h;rGkpus>4YbO9T3*?SfuA`_xgSBmVxdX&R_EH7GkIaR(R`3tpQe;_TQ;*DBsKw znlm-4h5n1&)C&no_CJoJ{670gXV$wup*HpZD%q}@bD6; zU%$Om559tflV=i4WxZ^7Zhd?nTyTMjZEC$bdp!BNqvjx(x+p#CYwJGsw=o>-rMbhi?$f!7Wp#OOWLDBD ziyeOi_FX9nBX0FA*WUf3a)M&XuAFD9AO62!D}m;>=>H*e{<3~H{$G>`|1V0A>dF8G zr~gbjD8Gg~PY^dbP#D6oIc%LWo}{>Ma8^_->4&`95cQ}k1@9U`Etk$s``9u#w!POq3?o4Yj0Ks`u}TjW_hl^Kd8~^PM;R50jllGm{J0J)cO%gmMTkPFuRw zpT@u3+|<0&>aBk|m<=<3IL^5E90Fbq+b;A%ZiQR_Ev#el@zZA!m^cDmxY)5aHW7zn z=Ncvqw(0oBa33Dr+}y09@YRiOoJMNogje^D)Yvg|ue?Pe;;qovu|=foVQQyybF0%B z=C}fXK>Ryh3HPB9L+A~8T#Tgbd+nLqqBozS!^0)();9~2Y~>JYk{yPkKq7{#ONA7M56J0 zaqdT0ib@e&LKfb&fvylZG)6u;z%^8YtC>aHAACS2tr5A z^Nr;rfC3ZndM4}@D8|M_e}n<2b@x;$0!%4t z_4J*TMc*#%m86joym(XD{rIv2Q2K+}myOH62B4CAI{KPHuvLZuuV|LbJY9YcBX zmPQsKVq2#n8uvV2oL}~@xycNVy8JB0&PYF-go9I13~W|yM@YzIA)v4z7KBk;_ei*$ zZJuL^BZm`jR8i~iv4A1)My&2X?EE^lytEpVU9;K{2sANua$MmJ?n%x5P_1sjtJEg1 zwt{w193lC!EKNMm*Cp;0ZW8&(!c}{}&CwQRQY@l$bkW+u7y{8pJ*S~cD?uouxLuCH zKNo*U*`ZV!iHgTG3!qP6C+XF$c)BvX6snJNX^#6|;ULd1OHPz3(@82c0QS+V^ftK# z{aW(~kHjxRS7lLMvGKO?$xX?1Q|x%zzdGcu>E`6F3qLNP9>tZUMp&piPIH)Wl46j( z+E;P;7;;ZF&SL@nutKvtgVTPGUs*kGw)i=!wAB?sBC`X?)o)#~s9R3$Nu)U{^Sm7* zt8_yfnd=Y1ps2TU=Bc01RmziF&4ja!o3Ki?Y-grY|P>eLbg=>1pxK7rtRX%cX>Fov_39(vYQ zk-EyLu$gX6H`k|GxVf2`nZ>m;)?pP@T3OB!Wq4Ku)j;1s<;W zM)wSSJVP;DxOh%F@ka^Fjrbhhr|7^$)PO>f@KRBc7$9?I=4_BAuqOM~s`aG0ja5%2 zbKRWVNu28Iju%Hfl`O?Xvy&P&0cNHa+Xh_H!dOGBOJg((FMeOU_l#TY#)K5ZofW`7 zIjJZ##jMY7pTy|SwFjZ7nN-4N@RPzpf_5x9{I<-6l6Yw#U&9w8+sqmXiqc?*!ys#K z)v#_VN8fcCIYkt9x=1TL9v&g5Y5OkO!U{6yk^&P-_w*1voLdLjS}(NpdD(HNP7drQ zmJk|aQb90p+J(iH3?aGf;4?-{{|=yps$p(a9~14LMkcc`W2glr$mKoS9-pDb+XqKIn8)a(NhE={W#=xNJ6cY=lHjaRG-H6U%78R&vJ zAiY42j5E{l7+-T!fio0<=wOYEbWIXob|$K};3gQrR=(rYZ4H0Vm56WLSP0+~uHx0L zvMxO_Tlbjlj^DPWZ-^ob$U}V#+Fiji-yZ6e5DlJQMpxrMCY^&fGzJckCFHs$Ma~f#^V5k9 z^ukLZ%T^NpO*gL~*gZLe#-Weh#BPDXoWwmjtzhU6s~elo)ui8mpVRLkb$w+OeH0O4 z370Br>neBAD0vy}Iwk5k&3D2EF?os=IjjOa* zVFgL<`W1$&V!%ayu7|f_^$>2U=+sSC=u?p=Y2h~W@M8~wgP8|W!$R+A6ty+Q!UO3bLtF!5&QyhO=7V#0B<7H##R1E$J|rT+L<^iB zHgtjMwf-xho-vYG5yj{Ncl{H&oNjfr?os>Ln|k9%FQq#KYA=7iofXQ1OX2IeC3g;r zkhM7+C)HJvnH~H!3dywe7%j#i1$bfLBO1bwfW(&#;HFA$G8*-EPf5{bE$bM{uVTzc zmdO%nigMp0YIQw{_doS<>S$gKN39~{0^3J~wJW~?0*y&ie9qxNeJpGwy&^)qQ(JUj zP@HXoHy{d9M&#Kh$&MxUW)4q@MG$=b`_;N#IJ4s;7VdhYe7d;?k2}g?H2;vZShoK; z1d3f ztTBlsfWKnWUB0!=V~F3|xo@<{MYy{n@+Wmdh!c zY?U{kfgsyJYmKq_0_oHaZg1RvW;v!Pr3k++#c@N7g-mY0EBZEr`lkHb_G;i|_zfz& z6QhhU;;h$H$a4uCER6w}Eo`E}oNtYLVhAe^dL1QY zfFdi<^381N`f+!+p@Oe&*0t?aA)oew!W1(>ZsB}!NognDZ5|_uBpHbV$h|zRG}9XY zJ7hg&>C*c& zM_Ec2>Iu%8WGmG>n)_5QUCh4_Avb7>fKLRA@i~R{1_&6)7ggWn6N)7XXiNna?{x=l z76}zPQ~sdut+nodhr}xft(gL^Z82XKL@MF_osel*?n#fCTfZ`uCr?;+K;J2YA@7>V zGXHiB%_uYk?S4SkPJ6lWa+*9A(ylkp%xhNc9Ea+-8gDKL;|qjH4YeV$WV1f#113tF zKhSt$ zt|elGn_fqNRr^RXAu7$ZniB!&*fN-wM8rfJrT?bl%;p<^XLy23LuY&X0nobh1E)b% z0|6c>J@`0^_h$;L63cK^?zDWte<|N_wbS5bdxsWraB@4`JNXQiMFUW5p&0neI@pxe zAP+Q@*_K8=(WS(1jq(NCb9&_<$@b>`5*=FwT?}Hl;JcQ5;o81A$|0SXqpO|5o)s~j zQ=C;PKDxUW$E(IKuFYx70UF>VO<%E9xC(&gLE`4%@SvQ7|3}g}1!ux^TR5Ir6K7)E zwr$(Coj1wEwr$&)*tTukKKcH0)m2@6)m2^9Ywf+B&E6JD^2-52NNrw#+N>4M>V#Vv5WgZeM=uaV5!*yPI$6%GlCu1Y*8zF`99uHk3ap>m<7=45sw8d=67;^oJ z9G2`t(QxV%Vt{FIfm#W|Q6lKuGvRw}Mg{>SeP&jXtHI!z8-ahG@UKm>ieAJnkS@Pl zSt;1}-9LR=bu*o!m9-)`O7QY-War%c+{eWiHJF!nY1}JXfW5+17w6dZ%Dpp`U+LH4 zdE$M=(rh1b1cg$48=*E*Bd`7pcZ9c^2v{Mt1dWQdpa2}argckYME-S?d17>ZKDcO{ zfO18=++0G&S3k{&MZ6fF%x4L9Q8fbo+yibHkc-K`K`Nx^+fjj`=CHxWMDzhF z@YW@{zDmXIV2>S)i!`NtiDkF~pQq&bV6Q0@bKU%?x}=X>npReV(ox>A&-i`MaikI2cL>dRvv+w)YE0rIFD%chdo?E)z1E@t5dF>~`YBPl$*iM6^=y{N<4FyL*7-;<&0JkIEak#VC^v_PR|8PBoW z@@o%4aoPwUS8|`X1BKm|zi^|+z*(B|NH>zr3c*sQzqsy8^)Dj1YrnEaciw-UcPcp4Ca!)J~~0)>h*|ppEO2BowcKR2!Tg7!?$zg zg{LVzwNYZ!v-kQfbv#eZ2Ruw8t-hwY=#03c7etBH%8_+ z#sr&$03-EBMhg*XP1_(QVshH2=5JSTDr#zS^-!l;vUQcPs%l0fomH;GUgIsV+O+c7 zOj$Oo+Po+({C2vMj+Y=62gK+-YOV3pra1*Fq);s!(xn8`31&r7){ZD;{5c!Z=t9O@Ws%zX(4vX6 z@a$^-jT0zgk|>o5)oSfF_}bAXkB=#7>fj*d79@3lIi^`unN(B8^pn0b1*Wt<4Rt*& zCy~iD{t%DGJvc0ege_B(cqAt!W`HRpO?|vhla53Ik?9hy6c!JUX}xR1$A%T431c=; zQnt8k8CxuBEj8|>d~?gU6H}t%z|?W5ZkoBk5nyiIO+%Ba-tCMqpBT3ooEj%tR>+j( zl6HzCK?O&sUpHHCp{z{XWKlRFPKqh>yc8XzaZP|AGgp>K$~4){UMZ=R1|Z$dg&-eK zPPMpdB@%TN*pM>el=;DSG>`@;T0kgKj09JPGLxbtkfqblH+8rL^P8i+I;TrCq;VIx zDW{JgNNRPsvBn5lL9BUe=FW59q35$yDEBG{Fs<(pIfOFs#Bge^<7x^=xM+%}^iyWh zSBoZrt2XQ^YYrW-+Ku!K15(GRgp4NJeNTB2RFwEjD9in;tY!06t8z6u`o-P)L&wwp z=tF)fX^;!+7SG=3+mPtw%|mMr9^iD>%vshZHe1L1S%TpofUaGhYgg1160lbqm{e}3 zyoPgZTa3?MGIzDDXAFxjHlC9#Z)B)h_@j|jZJ-!L6ab2__#;Yy07Pmczh@tY7}_yi zEf82{Nwdz(8*CDAMCYUnc^0T47iLv6%qx)Ccu?w>HTfU-Cm%%}<3!hYd02QPVB(UZ z($29coeW_UHp zT%VX;#Z1D)sl(kv0mD(kVvw&8kQBe)cpzg+8&7fOPB}SYjWFv{U98>q#QQjtSGI`q z!D)x>Yh1$%(bg*3dPFQdGAsRt8RsT$_!&PbUxQ13yr0WX)b~4Ft*81O0`2f8md`_U8k@mFi_mwI3@Kz-YXkUM@+nnF4VYX_w z{O})guUXkdyymeSU_6?`in1Mm!ZD?ck34$Vr#XUUo1F}p*1D76&(=+m#_ELJVH4^Q zmAvU|Y~}BG1yCbW{=D>ULA%9MuuV?glsPC)Q48gw79kHJlxB=F+t7+RE_r0@isCab z8`WL%Ji!sPf?va(30owY2b=ql23kem0YHib_GKDL1#LF9h729Zej_*!x>>SwS<+o& zd-ToITSfDi&XOqgGwjt)_}9y)tnDEdj}_qk`JN5)0Liu8jbw}I%Zdkq;>jd*2Tg3R zPxVlTvB}$egDhTQyiqe{i;knlH0CuC$9M7sG*mqcDvCm^s@$Uu&V_r2H(?5&$hXvT zJr&CL*<{wa-0!lFHgFV`H|9IM_B7RdcTG|-uy?Z)f5rA3Twx8#k;A^bqu)lW`E@5;U1rR`FPLLz&UlYZ6#jmq2u$F*DzWXdwHf1LlyKodt;$(^ z<@4w#3?mqj7u~k~y_8Y7!(toa1&k%!4`6LUu!;OxA^=;Tij%%M09}&X{H)`3RF&E(fq~;xbp9!VwAsaW zXAdYoFbkA5vNV&YPC}E6QC&Y!lixT;x0j``vg9?ZLfb{xP&z((FOK)ZXCHY$uSlHQ zR0=6l`_hkt+{b)}Ps0zHJ5K<4eBzb>ji2muTqjx{ZKxx>n`LCN@P~{0$+2tLJGi0? z0G`NR9{+=KTU*li>@Ky9_K=P9Q#EmFE;LEJAVS85$&2TKYc?vY@Y^VzLpAYDnt6%f z?D|^48xaUFa|%A2-YRmR&F>F~f(ig(jD3)MFca9L8^N;}-+Gvl%8&E#|AH{e6XVyM zs8|;I&ixf=`bE(M&+;@d!R#55VsqaG0FgDske=IQ#O{d|0xF~&`lDz`qFJS_w_^}8 zbK^q|0VhFb7hNnI60(_J(i*ea=c}45nW>jeG;PfNFZ%1yNGf(}y3EoGK7vN#_B7%jg0 z)7k?Obu1H0BZ6`ZlIIPJQOFPsEhcAb-Jd2k{F@aFoFfCB;m9p=uM&O0JWytTR61LR32G=J?wS*%BR9YGbRJZJ#08JsT@`Y zjj2WrXJQ)n!%TI~D705CS}|BrY-j%jz%~N@D2JF7e?U>e-4qmWi$AR8`c(?4@$NQu zVteSrylusr;EX<$MhY0K8qF8CZ|3QQuwGYM!Ls12Z7wz5&m>>c$l%%v0<4Ck{#mp- zR3k+>MOkNhMDXMuaTlOhdq_|KNp6p=3tI>ByI!PWwe$_)TaiY4x`)7pu9|3GeJBvY zwJ^|BQfKaxV(_@LLBMYPe7uAih^lGCtpzX!V^3Z*-@kgIzh(ux^(TJr@g*+r72`}ym)3p4PQs*x1${tFo>~;r%KP&{ze{V*9CEYKy(VnXE8*K z&=3t7;~C7V!%#_@6_6eB158NbuA)X|B#UEhT7dYJ|QmJ4DH|EZKylEpTu zPfriGsU2fu{GJ~hGgMq>)zkxPSykOS2YP?pVP1l|a@dajb>0zt9`O=#6BAvPr!|;x?z{+!eMRj#fxSsX6`>xk)XH>l8I$ zx8DNOumM4|Xz9%bm;)wVc5c{I@OaU2Me5NW9Fa^dSV)|;xRMo3JCd`{V3K}=_pOnq zA1afusHm>WYvWiZywSM>31SfB(8Q`)c=^2P>62L{Y11#PH&0?PI6uz8z@@V18cqdfESg$^%1Daw{$Y z<-kLsd|r;we5B}-oB43=n#%9EuC9u4Wg(j@mPX70Rt!1dH-?tD68Ng@dHv%`nL&cN za(>Ur*Ha?$>@54wL0UqMfJ3%h6HtVD^8sdj+?~RF|l zckkgl_5|$_^!H7H-tXwjfW-2?Mu+%I zrmTAiAn=hje6RFtq4RgrLil=eB3oW$ui@5BlXc;`IPrwKWO`BWm;CFq2k@|eU{CEB zpa&?MyZ9E*#a9=_S;u@G!l=E{aiPhc;cezi@1+Lhk%ZlWbCoJI+?g3Ed*#>M_A4G| zcMk^d(l_6S`eDlK$Oub_LQKtLJ^wgz!&F^Jc0h> zCSvRdq=aU(oLF`O86L>rX;KtN6N!5p5%p)9VX#^rwWc~TtWgPBh!Lrt2q+mX*sw1Y z08>>cQnboLYFoD_)pjI9rW+a`u z!+?p^3F&B6;M&W!)wW;L+Bsw_5>)#b6GUKHw~Gj(eun}0rU7Z0f|`U?PpDEVbjiyL zKdg#kdy$#c?Dd#PCe>=QfJubq#P4VThUdXArm8bvxQj%~P*28p$7Fky`0w9`d#<7_%mTmgvO4X{>vq@0^=wMqB15@Ust9>oVF?+fNsWDl?&JBtgx?#^XUVfMy94>0Yz%c#z-Cc ziIF=^eh%Tkqhn%|h`Gokfz@!s*z=IV&d%b%0lG*L+7i*tYVxWRki<*rCf`L zLGWd8JblIc<+_A9$wcGD-g8uc86~=KYJRp7y@<;3ST(@-twAbf=6Qse+KlW^V6UYS zXgqr|C%ri7{%qiB3?$!$fJwsLaeNw}BJRPBw5pZQ&?WT}k<+fP|Fs#wxJ=RbNIExk zt8mvGv7Qrgvqj(@Qo}iD*FFL|k{CyXf$s{1v7qIkGM^sSk|EI+fO1W!lB_s@Zt)V6 zM4K-Wa;qv?nB=9Skse=kM?E<@XR<4woa~-rTK1IqX1xfc^GZ+PE9i5u$tCWxn_N!K z@-&}(Hd9~z@yzo5Qhg9|XNX@hEj(^s3x5uXK(vbi2=0$Z3Og$xG%m$(9@w5BwZJfJF+l;;+_-gpe?Z7u`C8wQ0icg&e zXdL*h5>E5V5jWXR&h(TF>S7^@JyuPa_?3;q2xM&r#Y z`HS{xO6Y|8^Bg7V5WH!%^@atHmljN?dQr3ONU5Q6!)rHkTBVu;0Y+k+g~C!k!MF*e zo|Oqb0O;020PzHy6NW1-XhIjUM40q|>X$qnef^9nZ|m;Xe&LrIWvYRl>CY(@{tGwHY5mmDK{7Q_Hu+$tTGaw7xqY zclf9ep)fB7IKsDsOu1eB^q$msZ_@q8JCO05>~Ig%vQz1#Oe+XO*ygwIB;*U7c>4sr z#nF3((zXYJij?kO`%+1{uk-oO%@08kqHf0twelvPWexXXlZ^r&;2hb%kolaj-so zrk?BZyG?pcJlGhxlUzo_@1_b z(}!gtKywDTiUHpxGeQ8OGS$7`l@qws+YYI^hjJykn=-f*2=AmCAvri$-u%Z4Jq>#a zF+>)$B}vKa_-<}?iRzwHP++2G_R8U6SA4lb;1nwISm%$p%RZ_>xO=r9`6b~qWm)=g zN)6C5-L;PhO#p4XiMwl(MBc_38ggxA8Ru&SWT=7#@>n3_PLCz-;T;_Jfwa8IV}1(< z;(l|-JV!Kaj0qeAeVhIO8Fh!cxeO{D9ONI%%-ZJF@8QNP%r64OuCZJ=id36r|oX%JOg&Slr7KyAK zxoMb)rPV88v=#F2kArxaz!khc2$_u0a#1Byc!}zV085ert&rl6CHjoNCH*xMbI^v1 zMmXfaB?^nvOBw08;Fg-7rI%ikO!}$wizrK|ap5^Iyc&F4vO(ULCG)>-?H~1<}vcYyuzGq zL;SyWSg%be2cHoi;hcKd$}$6ADBIH$>ZPNZa!6?kT%>lwSuwYsvXSU~G}vjK*F+_K-HH$N znbT$JVNEeL@X$)2n-wJiqO5_Bk`^!9waX{_DdO^7Par>h42ODs!@SABjYx6@ZY%SQ zOu{7tz%Su-FWDzBIfnF^dojG^J=4ClTOZnd2g`*H1;iN-{C6f zwEcDEUH33FPMpS(vN^+Jl=h9&B9bY|a%a_f#bZj%BW)p-Db8|NT`AyWfpQ1Y(j||8 zWG+5Ys!X58xmSFh-4CQH$1Y(t&To+l9ce4=2=gi`{&VediWAG?$LdSxBq~{KZ83|2 zij->CO_AkR+(J%{XXkRanmmZ-tc8=VjPwn@LYXttwaTu)&82cm4R6#oD&Md=b@oCh zW4Cty)h$|h9Eg3uW&fJS9x{jz4{5$9Iv069zD-_h$_XWOQN6kzQe)|{qx_Q=hBf^3`1b1BVxP#q>_ zYgiby^E8)bk!B>w5o#FZN~xWjYX(ikmCAbKuj|e04AcBUeGHx~=Nw_lsTtuW^A=o( zO^vsyO*97B^d9yhN$Q#QMyh+rX83eArXjpXtuz5S+$ds z){@^L2u0R4Cig?Gxama3iEHN%Ci80r&{ABa424_>>yi>4U47?nj1ejGFQf3NmFVsB znTh*VD&lOB%U+C?rCZL_dM(jXbkK(I*e<7o*#aPy`!RvHYGyMy2>q(Q-5R>RmJ?C5sN?6)qsjP|%qlfSdiNl*RmNeH+c zdRrN1T}*}=00|JRb55@5&+SjOYd>vWG3{%r@mSVb%YN@buERk_dgJV}NZY+0s)S^;r0l1nZ2x!xy*@)%49 zYkGr#IQi053vam`d_#@SVy=oP60ejYA`*Bquj-88G!9saYjGuO!lK%YU2GJr;nR0+*bvrz}=3XRBs-QfOjLyb~>N0RNo&(NFisr>t>%s0Rg^S9PRJth!S zIA(%g23cc1he=Fnj&#T0t2%NUBSTx-S^fDM2ywZBQ*W z)5W<3WF3Auo(XfdLu8bgQCjAYo})YvO|-g|OaK>BUJ{m4G0P=06hS3NMtf`?p*R6= z*%7{oX(rfL>!m2?slb1TdY6Nj@lblkMQh&hMynhiS+1t z1>fwl?44@WZf?cM)u?t<6O_;uWNjujB@0_Y9U>VuOnD7uY+Rr?jAYVDGa-{Zy*?wO zy#Rvb#X7$@0ho};2DiZr|BtM9(XQ_Usax@_=pR%OM*&?<*r)IuE6fwTYQ|gHy6i0@ z_$|!_opzUu9ZC}?)%voda`drmDSEQyx4G&8!jdJncQ?KDVHHNaF;Z8?Fpv-e& z2#7o4wi5aFKMNuEs4zTo=4hnko7DOW9sqI=!H4{hjc??U1pUqjy#wSs0V70v3lASB zz)efb<(DIGO}%T{ddHMT1-}!v7qw_8$^CWjfSvI+e>L?%{sO~UG&xDS=R&buah^1$ zGR(E8H!L}n`Hf09Nt~uD%>vqOTF9tc)5$R@*j{QN7?puhw7usB`~fj7ok|ie0x(+B z*h6r<|0>N*m-$G$%1vOjr4%IjCiIzpg1)2(?GE?y4eM55VVlp~OElWM{)0_?I7j>V ztS%(yuG0@o@(oG{vGVI%qw@8Yk(4dq>b)hv&S`l!TD^Wa;k$P{$sOvu$b97Rk624I&Q0+GZ&;hn46=lkmnSws2D9U2TQrhvRZy>UxdqW9UxEO;D6|j zU8rZjXN6E+u-NCPnai#@U1&+d7WLd}%u3rCAmCD2o**C-wW+`v)Z|heQ>0X;OH@Luk!`y&1bP ztdTqlb}^>cEnxj>Z7f{tR(ym#FeIH>h1t;DHJF_}#A~qQ8I^+ALf89q?y$}C^$U)goAaq?&tO=FgJi7w@D+|$)Y ziV7a{%KySby`Zd6VCoptqH?s9wGok9j^(5*IbyPLw4B8?9ze?43l2rvQ}lW4=XqEy zAov@N0Z@pLU@J_X$>JmF6<`jev|I>7YPitFm=!PLGj^WcOyX#Y?DZ~pqBFg3;m4pk z9^SaAwVb5D`sQX}qNevo91a=_x23!;Qz(%gi7Xy6;b>~s(#vJ<4a(Z(5?e@9XoC~7 z-1NE2im{2ZoHzScE|{VPOL8I)i@1h1)Kvp1<*Y zgo3kE=*RL^;wj%PIAeH(&GpUCo_S$9)9~*)_r|-OR;Iy%P+oD1xMspaCx5Bxnzqu; z1?;rEKUrw!?(}ydMZutWcVGMdEFZwz0{<-n+jPvd@;4} z*x-@%;c^l^Skch^7$#9U@k2cW@R~xsHs%l0tME|<kv54*wt&#_du+Ph zRt47+#-~#d0x`+gtBI1iT{w}>*C$#BP|TuW|ZiykYL{zpr0lf?vQi z!!^V3-~S)XRg+3f7=-;n1=M5wPYjt^q9?!v&;Xh=#jHAQHlhMrqJKC6p1o1{(BZlG zt&#Kd7R*irX-h#Xziw%?QF?m0!hHlP12w%5Rma>iBmC!mh8A=^q3G(h)dzdn zirtxWPwBw)=d-%GL=ji;)QBb~BZHIO+qq-fVT*~Sv)&*j7oxi6r_~LfZU-`XWwj26 zJ-vz`lF2V447_1TN_ffCkqQm}T_Il*Y2`PBi+9&7r^VBn$4`I(2>z; zRh3q(u|i6a);RL4YcAKek+ub!1w~fFOE$IsPv29W^(Mo?w&QesS?^i*|DkK&zqa>Z z7N5IcxRG=Kv{%T^Z`ocDEt{*{l|?b9uhLHW96WOyvze?;;6xRxKM0uPiOA^J{Om;* zso}j;)4_Qo&$m>SF^$PEBpRzzoXMbBcUh_dIEwwdaW=axZ*cdB_40Qy$yI97N(P!P zsKRVKmb-Rc=DUJao@#WO%%E4BtP~g92(yR%Nw;4BaY$&mv?4>z?x~Tp09wX~0-XX8 znuNuUp$N^qT=b5&`{XK<251j(nhqJRY8R8H5A)@%-SvmYs#v{PKC9^HGZBG`g!>D* zvBAp#5KJfT9G0fY+=yeNja}NmkA$DXoLcpf`-(N$&YCTio0_@_CE6+-t0U{43^gVl zqCG2sB$oMM``zj+7~2s0?k6;+Fq4{llGy$eYMt7SQkh1RV7P^O*2IeJ4Yvl@)^0L99s2J)@nIvlORF-%|-Ic z^77ND7h%MOP?n`<1RNglmd^6r!VG6%R%lF>AX8O#R(#y+SO#n28R`*}0m)MuN{B0f z1$LtL67_|HG-w+*1vantsajVI5pz>CvOeb^r#vv)QWL+g;^u=5_O&VW?)d7xPyVC$ z)o?23D*VA(*SpKU1*s~R1tFgR+fH3iu}Qx&bJ&y>e>j&FQT7&87z` zGn~3?YXXuT)Vu4A5paGg|yeP$tL#`p@5?){)H2d&6gk^lv?Gk&Rd0@1i2vn^ zRLJV@#hn^d`ez6y>8L+XrE7&|(qR{i_i zvM!{Ik5V8K;)PmY@e0J<(2VyB|28P~xe4dWL_9k;3^8gRC$wCVpkQ@Ir&kfc7ttAU zWg2x=7M{?u%BRXa++;A7^eiaLX{G6z>YG_H#_ogS$ap8n4y94aCjC4QkgJW&sno3) zBJLz1%GlMsnRuT>)W^L1YB4`^mcq=MDV8Z=3xsoW3ysp z@RRx<5%_|VW=OtkeMxWbf^q8z=O3Y)p{u9OK|#@534*!c9^{fMcv&%3Sw6J6FMpGI zz&!E^w3@smc~CO&j7+craD6gjBW9(*W%w?Q&UXhSBG^B|YMC}0pKCAoKU7fX1(6OC zehUnB#wAZ?SVm8v6P$%Ylo~HJ9ckTDJgD8@9W+9@NOM(J^tWfL+0cZnh~;ClUDQo2 zdFQ0zF@$q0;?7%toSX%(O$r%d5t@`HuIHkKld`V;rtEVGn0BlONNh}!W?gaCr;T+6 zTdId%5th&{1j5=WG!ZI0?PEYB47aT>#^t98Vbw;EM9k-sbPURNtwgVl{~^gE>j=^tV6qdac~4OH9K*hZWy)Vh0&_IGz)TxsxjF$iQlp-R^gnUZANSC}*3s7Bbw|F|!3ps&%k}@7@Xo96Z`XUvsncvRu zNGx*lRFPNHa`c^7p=0W(-sQEMYguX94puwjlFtJGfHsB{Tn%mjd*x3t4>(`1LgDDbcC!6 z`L-$H9>kB>PuJVO#whWd2*1-YagIhj|>gg)DHHeNSK!vqU7vs*^1dk?jmFR%nQ}mjurFpWt;vap|89W-ExpMv&_V9AfDAH8^nKAl_Pvw)2+~w&RZh z<}L-CiB2}3+DQJ`6@YskbC3vI{~)Cd3tC}|{XZNU+^zY>Vl)KvQ9cdoM6BTiOKg=< zGxu?MCU0{XFO7wDe)X3@(xdhPFxlM6yC&m0UEdA}eq*+le@UAny5m<{Ytf5^ zZF+-q*C$6w{$8<{nmbh<-TKgtS{Q1uaANr@6um^J{%y!!L8nXG_0q7`I1m@vf*}BmYjZ!! zD%o;kqn!zVC>NgKh5|pDpat#l+_@VQjl)(*6O6E?i?w_7i4lJ$iMdtANw5irufhfx z__v3nsuw>{<19jS)Tvv%(&c~yAXhvR^c+_5<=3(#-g*`46BB}d2J_upwxX>%-56%M z7?k1;B|;Yn%77Zrw~kD-fo7zFKSIikBC;XK0>q6MLv?gGfdD{NOC<^^tO)TJdEGIZDLNe!37@r(yk_sWtu^^(CTnxbn4A zVIc%Jju70k$n;#bzf+<#iHLLflk6N>FSxlEUX=-#J+KzRnMbl>#0j`%ueTIsQY7o2 z?0h2mCzPhagV%Gz;}bMhzzzAyuJRp;CYIOMI|jH>_GH2VD%~<}T-#3QV0Yk#@fr7b|iw(moKg9wZR!}-2>dW8N4jqWzi}3y} zPm3VWR9lA=tJ_ETs;VBg2>OITv8zB31@?`YsCRlU2!r9>su+O_08wfd*mefc(E5rJ zuwJY)mP6;*Ic!#q>p$r&CO9KAitgh-sESZ_*5Q?JCJ#mYedxFK<5$u)k9>k~x1rPX z2Xyl>GJTs5VWi*rVyoA714LVlS=94#2H&77d?E;*&2Q=6x5s!TQ|<}Z^`7M$PRY2E zB(<*w82@PZbeij=0Xdvtx2bOrc?rDud*?XR$FmFBj6A;3l!J;Uo*?F4jAgZIiekvR za?T^z*mo|lulqu9-MF`$w4RjUzdnyV$_72ubHiu@Mxh{WI^EzKd1a(3X5Oxh54mm=BT8Cs0QHX7{3v9dE?ouE z+g$y8$8nQ_t&%m&YmOY%#46E~3zWmGYm~!OCzc#nfI=Nd={a2v_&FpF+`IyM_PF5M z9fwG1j^q;ojyt;=u*s5x6Mph>cJ;ozSCiAF6$d^lInTrUEdNvA$3EWRjFEcejU4|5)WMEwHs+WLFp z9Vc9%OFef{d5_(%`{$5|w@yQgjhApjlSF1Xa5ZwN1rb-s`=Zsu63O7(N?dmqNZ21M z)pgORDxj;j`nN>mkOV}P3POqh5$^tm>OS}ZzDtrvRto#&fyeqLD3E9>`C-xzd@JGf zB$?AiM2pUPG*Z(7G_9#3s1C1L=)$v=8macY1RfFxqZd>jAI6L_C)%fH*D01PCly4g zq#b+;PD0j@1{G{2FF5%Sfvw3-->=l8UldL1*mi5|Ky%$v26t5LYPm2jsv};wi0ggC z0kLTfd&Twa-sw+OrCLbVcbkAhu2PqMrT$?@2V!*Z7bX;4h2?|J@7?)E#;yRe$E%%r z!TyEt_IivcFivin(4_17z^nGF9pgiWr4|K@N>ys)(3gF=h;=LxG}g*s_%mJnp{M9R zvZFkv(j_g3^5sA$tij90cNS=v90v@3k-B8Dv#Vb zB3yAQiUfx*8b8I{X8cjyX~(JV8?HHSH{2VskL(;bRD}KndRV?-Qg*6cj*|*G66M ztCz=CDq~$RvYA zE>0hLeJfPGzQOWH_Q+!(3=M%Q(pP5Hm^6(3O=k}U z1X+bjcCFdmqe6TV9^??B=Z*ba#ti3Kt*Xj~TBZwbFVv2wuv6G~%HYW|`>J$dAQ%5@ za&|_VB^W%bDg5gb={ZL#l|ZLR=!M<&jL@87L_P+U9(Fz>PNu|*k^de=^t57joB7Qg zXtZy98YAaDFzh*24kBU1)i9Zp;j~Z8Qu+_kD{xARoV^MJV`Vc9KtD27MEjh+2tL7r ziOA+?D58%G`CYawM_j1n6kkCx8J>*`-Yqs4Sh^WUw5b2156ThX;Z1fnQP6!DcdawH z0j2t-1+Ihd7&rde{XeK7IIg;e*3X0u%^xH_b;3;^2_R-#5|jaPi0rARDclEyq(rq{ zr;?{q1q_KBDqQe-{=%8fhP8uu-4pR0zblBW_wRq^snYD<->EUzDR!g>_vfFWK%%u| zJ0_i7G1&(wiviZu!-|u}dga_yjlGJ;tRr`+sa%YK*)NPDc%_L8eRNE8!%WQCZ}s8< zuo3*No)U~d4I~-nQU{GPsnsJMz7ZbG?3ls=(p0Y-UZf?7-Kd)6) zw-U3P@%@Ce?m<)T`rplswE?t|A8( zV%-~K$9Pz2)1fwg4NEnj8?i=&x0Pkypyo;wJn#F>?H#+D!PaSe3BOimD;d+NF7J28 zu1>)B`(X_bX>IS#!ES%igj*fR@=}mSq|8vGA~oiGWqB3$#yky^N>g~iK{P#>8#o2k zh77<0HLt3}cQHyPxpg<(c!IX1d_(pWcxYhY<>dvn-i7h~i)5Q#d`H#&3>ha#V@ZbK z&n9((vk*J&Afbop#hp5-3JP`|o}fOg<rbiTsCW~hAbW0QXt@n;>4I;2~F2_{86}RchsIB8?MrYipHQ= z)HSB71pCy(R*pe9{SjI@Sax$$rhGKvWpknPTwuiuDYM@%+&9zg#BR!ds?mq;m;(@? zhWd}70EdF!-bZN=pO)SkB?RqA|Y$p_pD{?lK9wD*0C?e@0vcJeCP9<$7BAw&&TV1&YZ_RbI!T%`+gl4 zlSpXW742v2KswJacms=9BIf>*vyGsA+B6 zWC5eQ91~XIDca6;B9dF|{WYrC$KXJrcBBeLFkYLkd5^}6QTPeJ>3QroEnkI7 zgwyRzboaKKSG%%KEu?6kNOXs{KXf$?;&@u5_#^9%ct{sZL}v+;)}BX5owJc4^^B*m zhb}%LC}BHlm%Hs=*p(1o-t6V56R|jEp`oW;*P3-<^^(Blh-Pb5I_L z&RDA$HKD7g;V%}`Wdf(7a3M_c^rDESPEF3yI2DG>=UCs!>g$*p!ndNKTX(4LZ*6s5 zJzo%kW4O_`)Nxd8+2@^Nlbx7&o%jp?Kw)}(6k3ye;KVYW&x%QR#ywZurzY7&*|)iA5B0CbJ_)`waN@x2S0Qg^LO-QSMn_QgjBTpwbv6c+Xv#?22ho~IZy z_>$uA)X~FlV-g?3c1B^9g-I*Sful|H*(`OCw;3wJ^n2CMbz1#-qL-X_U`t1hHf8u? zsli6D85>2zyukz7Pa-16e;85hZfJe#Xp}eSs%Im3P0Zy&d%j^l>^quA=d!Y6vOY)+ zvCMOz)EH@2^H7Pl^1Pi0-8njOScBqHgU;8s@Sk6%JNofND;r__Pmhg0V?d3Px<2Ck zOdy)#m+R}z-H*W6C3i2;O46dcad7?Y}ikg{4^4+~N!ttN|<;DfYdyRXaJM zScC#4npL`(RZ1s_%F=!ldMonV()~T=n$V3;{5svQP7+#MlXgaaEi4ajEZoNLtqgGk z#$&p{pn9b9tSl?Xlb%x+?JE7M-Gdq;Px@CVRiBOWa%*|O`C|5J#cyT5hr4!%a;eYxel=92@EjVoo z=N-d^+)CTZi^O2c$2rb({xx^lZb@J*Eqalyjx^$ZO!sAga`P^cA|n(H%ts~iF4Ik*X8xma}y7Hlq$m^r--fV*Hg!&ZZf8OsHMHz7tf%9-R~As{A>816zdd1x#(oAv|1`C%B=@}%zMF;3io15cR2hgp z#?zd8XmB)fY8msEUhpgnmMg8^9iwbw)Nxcj%-&rY?DLq8ynZc9kVRlm1vY&rTR<4>AS;`7F(y2>+a^)e0^{zAb2Ba?b5L?p1N@jS8Ew!Mz03 zl#XYxe`&Z)Kwf{?Woql(l-C@yC+ukwEt(ja7;}4+lhHF~)6%1^b#g9MThpF#^k=-Z z!(j^zYRqk~glOnn`tun#bak;Ju%)|6wfOrzRb{jCd3__-utjDdhk_jrfODVp1BhZ(|8;Hk(`CUreu4wHEuQtCT$RHbnvan zp6DfJuNrNavOAkWW08LH>AQ71hK^a;P_|Cr=vWj4e?sj2fbykKZzDMadmA zE-qg~dbF+WD(Mwp%HLrdzGU{veq)U5NGma4Qn=hgcld6{XpZ2I_l9@d92qSo{&EjV zwp(Jm+K}#Ode&1*_NKz9x@D$2w$Q;^s)fw2v5C$yO^=v+~vWHrxUX! zs*04jw})&>oQ%kPwMWgKRO=#Tw&UD5Q`FOxsK-t-Yj@k_tJ6zNaYA~CR(Gr(x8~u3 zs*_xrTo~o3=+ZaEr2?xk&F@cQN(u;SBTb-`2$!AI(PxlTUYy&xsVaJ*zC{P!;O7r@ zM?ZX)v8wh6)DO2l)-f(#UeL!uh0h=2*syNoFoJtFDa$N866>lt!O^%HN4; zu*>d&ri?#Bc<2X>1Tl%Z)2@N4ac+El11G~HC)VO4d|Z+%u@kMr>C)lF-@r(xbJX6? zRHCeRgYvh~I$cAruez}(c48+IXT&bUWv@-FyrEW6&Ww-S{7cLu<3WZwrz*bwwUzFS zVK@$$ z@+{f)pkw<=d|=Kou6-p$!xf^WKBNLdCgpNuq{i{zq~&pb68XPY=JI4D1Lr=ePHNd7 z8)_&rx!x%FckyM!Z@*pu(4qtYa+MeSzvKP3t>z}hJTQs{02#8F-vtinr4kh4zzg)h zJ>C}jmn8KVe&9I?01{-H!6IPFI~~MtBS5G&Jk$jRG9X^`x0J|xX~e%qS>4qC9fCkK z0A3Oo-|qnYz^3NEREre&^}QnEkHHEw<|1UlvM>PnOIC{XJN!160D#i}H=gG50GKK# zPofTt44`7QWLg8*eTsA6k%H8$gYx$PaGs2uRRROb_`t=B0wnOD0y_YRk%6+RU|l&I z=vFQX|5HF38dLJPqUsQ20sm7$7Xr?asSvdw;3W9fgqIZVf9tLBl7Y4tArJv-n=_KY zgA!c;aE1(ga+%bw0LN1#@Ze1-06>v}9cKT4N5Hqvbl^fIH~e?1;C`kc0PvB)x$gTg zjpn~^QGw`UZup(x$ujyAcORw*bIHrkik=1nyKJ;eXEBpfTnqgD9Sm zAd?qtq%QqAT7tro-~2@}BrvO51pa6H2;JABWNK$)Nf2etIrzUzYCUL5BJV(JA_@9u m%Sj4*Fn0lfAekc9^MBxz;9L#$QC@%-U}69Ou8jTp>;C}U*Eiw- 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/template/Template.java b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java similarity index 60% rename from src/main/java/com/modularmc/template/Template.java rename to src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java index 7cf08a3..3f7163b 100644 --- a/src/main/java/com/modularmc/template/Template.java +++ b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java @@ -1,20 +1,20 @@ -package com.modularmc.template; +package com.modularmc.mmclutils; import net.minecraft.resources.Identifier; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.common.Mod; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +@Mod(ModularMCLibUtils.MOD_ID) +public class ModularMCLibUtils { -@Mod(Template.MOD_ID) -public class Template { - - public static final String MOD_ID = "template"; - public static final String MOD_NAME = "Template"; + public static final String MOD_ID = "mmclutils"; + public static final String MOD_NAME = "ModularMCLib Utils"; public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); - public Template(IEventBus bus) {} + public ModularMCLibUtils(IEventBus bus) {} public static Identifier id(String path) { return Identifier.fromNamespaceAndPath(MOD_ID, path); diff --git a/src/main/java/com/modularmc/mmclutils/mixin/MMCLibUtilsMixinConfig.java b/src/main/java/com/modularmc/mmclutils/mixin/MMCLibUtilsMixinConfig.java new file mode 100644 index 0000000..f148ba2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/MMCLibUtilsMixinConfig.java @@ -0,0 +1,5 @@ +package com.modularmc.mmclutils.mixin; + +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; + +public class MMCLibUtilsMixinConfig implements IMixinConfigPlugin {} diff --git a/src/main/java/com/modularmc/template/mixin/TemplateMixinConfig.java b/src/main/java/com/modularmc/template/mixin/TemplateMixinConfig.java deleted file mode 100644 index 4605d86..0000000 --- a/src/main/java/com/modularmc/template/mixin/TemplateMixinConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.modularmc.template.mixin; - -import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.extensibility.IMixinConfig; -import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; -import org.spongepowered.asm.mixin.extensibility.IMixinConfigSource; - -import java.util.Set; - -public class TemplateMixinConfig implements IMixinConfig { - @Override - public MixinEnvironment getEnvironment() { - return null; - } - - @Override - public String getName() { - return ""; - } - - @Override - public IMixinConfigSource getSource() { - return null; - } - - @Override - public String getCleanSourceId() { - return ""; - } - - @Override - public String getMixinPackage() { - return ""; - } - - @Override - public int getPriority() { - return 0; - } - - @Override - public IMixinConfigPlugin getPlugin() { - return null; - } - - @Override - public boolean isRequired() { - return false; - } - - @Override - public Set getTargets() { - return Set.of(); - } - - @Override - public void decorate(String key, V value) { - - } - - @Override - public boolean hasDecoration(String key) { - return false; - } - - @Override - public V getDecoration(String key) { - return null; - } -} diff --git a/src/main/resources/assets/template/lang/en_us.json b/src/main/resources/assets/template/lang/en_us.json deleted file mode 100644 index 83042ac..0000000 --- a/src/main/resources/assets/template/lang/en_us.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "itemGroup.template": "Example Mod Tab", - "block.template.example_block": "Example Block", - "item.template.example_item": "Example Item" -} diff --git a/src/main/resources/mmclutils.mixins.json b/src/main/resources/mmclutils.mixins.json new file mode 100644 index 0000000..e2c431d --- /dev/null +++ b/src/main/resources/mmclutils.mixins.json @@ -0,0 +1,15 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "com.modularmc.mmclutils.mixin", + "plugin": "com.modularmc.mmclutils.mixin.MMCLibUtilsMixinConfig", + "compatibilityLevel": "JAVA_25", + "mixins": [], + "client": [], + "injectors": { + "defaultRequire": 1 + }, + "overwrites": { + "requireAnnotations": true + } +} diff --git a/src/main/resources/template.mixins.json b/src/main/resources/template.mixins.json deleted file mode 100644 index d185040..0000000 --- a/src/main/resources/template.mixins.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "required": true, - "minVersion": "0.8", - "package": "com.modularmc.template.mixin", - "compatibilityLevel": "JAVA_25", - "mixins": [ - ], - "client": [ - ], - "injectors": { - "defaultRequire": 1 - }, - "overwrites": { - "requireAnnotations": true - } -} From 893fa76e6a3c99a68777cce4c44549fd324051e2 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 00:45:58 +0800 Subject: [PATCH 02/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E9=9B=86=E5=90=88?= =?UTF-8?q?=E4=B8=8E=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/collection/CyclicIterator.java | 42 + .../mmclutils/collection/IntrusiveDeque.java | 240 ++++ .../mmclutils/collection/cache/ByteCache.java | 175 +++ .../collection/cache/CacheReferenceQueue.java | 46 + .../mmclutils/collection/cache/ChainNode.java | 9 + .../collection/cache/CustomHashCache.java | 213 +++ .../collection/cache/CustomHashInterner.java | 177 +++ .../collection/cache/DoubleCache.java | 176 +++ .../collection/cache/FloatCache.java | 175 +++ .../mmclutils/collection/cache/HashCache.java | 84 ++ .../collection/cache/HashInterner.java | 47 + .../collection/cache/HashSegment.java | 91 ++ .../collection/cache/IdentityHashCache.java | 202 +++ .../mmclutils/collection/cache/IntCache.java | 176 +++ .../mmclutils/collection/cache/Interner.java | 24 + .../collection/cache/LoadingCache.java | 35 + .../mmclutils/collection/cache/LongCache.java | 176 +++ .../collection/cache/ReclaimableCache.java | 7 + .../collection/cache/SegmentedCache.java | 47 + .../cache/WeakCustomHashInterner.java | 189 +++ .../collection/cache/WeakHashInterner.java | 180 +++ .../collection/cache/WeakHashSegment.java | 103 ++ .../collection/cache/WeakReferenceNode.java | 27 + .../cache/WeakReferenceValueNode.java | 29 + .../collection/cache/WeakSegmentedCache.java | 28 + .../collection/cache/WeakValueByteCache.java | 211 +++ .../cache/WeakValueCustomHashCache.java | 221 ++++ .../cache/WeakValueDoubleCache.java | 211 +++ .../collection/cache/WeakValueFloatCache.java | 211 +++ .../collection/cache/WeakValueHashCache.java | 211 +++ .../cache/WeakValueIdentityHashCache.java | 237 ++++ .../collection/cache/WeakValueIntCache.java | 211 +++ .../collection/cache/WeakValueLongCache.java | 211 +++ .../mmclutils/collection/map/MultiMap.java | 169 +++ .../mmclutils/collection/map/NestedMap.java | 173 +++ .../collection/map/NestedMultiMap.java | 243 ++++ .../collection/map/enums/Enum2BooleanMap.java | 497 +++++++ .../collection/map/enums/Enum2ByteMap.java | 540 ++++++++ .../collection/map/enums/Enum2CharMap.java | 534 ++++++++ .../collection/map/enums/Enum2DoubleMap.java | 535 ++++++++ .../collection/map/enums/Enum2FloatMap.java | 535 ++++++++ .../collection/map/enums/Enum2IntMap.java | 534 ++++++++ .../collection/map/enums/Enum2LongMap.java | 534 ++++++++ .../collection/map/enums/Enum2ObjectMap.java | 524 ++++++++ .../collection/map/enums/Enum2ShortMap.java | 534 ++++++++ .../collection/map/enums/EnumMaps.java | 20 + .../hash/Object2BooleanOpenCachedHashMap.java | 1081 ++++++++++++++++ ...Object2BooleanOpenCustomCachedHashMap.java | 1084 ++++++++++++++++ .../hash/Object2ByteOpenCachedHashMap.java | 1131 ++++++++++++++++ .../Object2ByteOpenCustomCachedHashMap.java | 1134 ++++++++++++++++ .../hash/Object2CharOpenCachedHashMap.java | 1131 ++++++++++++++++ .../Object2CharOpenCustomCachedHashMap.java | 1134 ++++++++++++++++ .../hash/Object2DoubleOpenCachedHashMap.java | 1133 ++++++++++++++++ .../Object2DoubleOpenCustomCachedHashMap.java | 1137 +++++++++++++++++ .../hash/Object2FloatOpenCachedHashMap.java | 1132 ++++++++++++++++ .../Object2FloatOpenCustomCachedHashMap.java | 1136 ++++++++++++++++ .../map/hash/Object2IntOpenCachedHashMap.java | 1131 ++++++++++++++++ .../Object2IntOpenCustomCachedHashMap.java | 1134 ++++++++++++++++ .../hash/Object2LongOpenCachedHashMap.java | 1130 ++++++++++++++++ .../Object2LongOpenCustomCachedHashMap.java | 1134 ++++++++++++++++ .../hash/Object2ObjectOpenCachedHashMap.java | 1080 ++++++++++++++++ .../Object2ObjectOpenCustomCachedHashMap.java | 1077 ++++++++++++++++ .../hash/Object2ShortOpenCachedHashMap.java | 1131 ++++++++++++++++ .../Object2ShortOpenCustomCachedHashMap.java | 1134 ++++++++++++++++ .../map/hash/ObjectOpenCachedHashSet.java | 482 +++++++ .../hash/ObjectOpenCustomCachedHashSet.java | 489 +++++++ .../mmclutils/function/TriConsumer.java | 8 + 67 files changed, 30957 insertions(+) create mode 100644 src/main/java/com/modularmc/mmclutils/collection/CyclicIterator.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/IntrusiveDeque.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/ByteCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/CacheReferenceQueue.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/ChainNode.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/CustomHashCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/CustomHashInterner.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/DoubleCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/FloatCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/HashCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/HashInterner.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/HashSegment.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/IdentityHashCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/IntCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/Interner.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/LoadingCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/LongCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/ReclaimableCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/SegmentedCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakCustomHashInterner.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakHashInterner.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakHashSegment.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakReferenceNode.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakReferenceValueNode.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakSegmentedCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueByteCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueCustomHashCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueDoubleCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueFloatCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueHashCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueIdentityHashCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueIntCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueLongCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/MultiMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/NestedMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/NestedMultiMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2BooleanMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ByteMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2CharMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2DoubleMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2FloatMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2IntMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2LongMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ObjectMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ShortMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/enums/EnumMaps.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ObjectOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ObjectOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/ObjectOpenCachedHashSet.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/hash/ObjectOpenCustomCachedHashSet.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/TriConsumer.java diff --git a/src/main/java/com/modularmc/mmclutils/collection/CyclicIterator.java b/src/main/java/com/modularmc/mmclutils/collection/CyclicIterator.java new file mode 100644 index 0000000..121a6db --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/CyclicIterator.java @@ -0,0 +1,42 @@ +package com.modularmc.mmclutils.collection; + +import java.util.Iterator; + +/** 依次遍历非空元素集合,到达末尾后从头继续。 */ +public final class CyclicIterator implements Iterable, Iterator { + + 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; + + 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/collection/IntrusiveDeque.java b/src/main/java/com/modularmc/mmclutils/collection/IntrusiveDeque.java new file mode 100644 index 0000000..a8fb30c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/IntrusiveDeque.java @@ -0,0 +1,240 @@ +package com.modularmc.mmclutils.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; + } + + public T removeFirst() { + final T f = pollFirst(); + if (f == null) throw new NoSuchElementException(); + return f; + } + + 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()); + } + } + + 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/collection/cache/ByteCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/ByteCache.java new file mode 100644 index 0000000..a765b71 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/ByteCache.java @@ -0,0 +1,175 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.bytes.Byte2ObjectFunction; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/CacheReferenceQueue.java b/src/main/java/com/modularmc/mmclutils/collection/cache/CacheReferenceQueue.java new file mode 100644 index 0000000..28cb231 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/CacheReferenceQueue.java @@ -0,0 +1,46 @@ +package com.modularmc.mmclutils.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(); + } + }, "FastCollection 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/collection/cache/ChainNode.java b/src/main/java/com/modularmc/mmclutils/collection/cache/ChainNode.java new file mode 100644 index 0000000..50fa0a1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/ChainNode.java @@ -0,0 +1,9 @@ +package com.modularmc.mmclutils.collection.cache; + +/** 分段哈希表的链式节点。重排时只修改后继引用。 */ +interface ChainNode> { + + N getNext(); + + void setNext(N next); +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/cache/CustomHashCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/CustomHashCache.java new file mode 100644 index 0000000..841c336 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/CustomHashCache.java @@ -0,0 +1,213 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/CustomHashInterner.java b/src/main/java/com/modularmc/mmclutils/collection/cache/CustomHashInterner.java new file mode 100644 index 0000000..bbddfb9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/CustomHashInterner.java @@ -0,0 +1,177 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.UnaryOperator; + +/** 按相等策略驻留或查找对象。驻留条目由该实例持有。 */ +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/collection/cache/DoubleCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/DoubleCache.java new file mode 100644 index 0000000..7afe55f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/DoubleCache.java @@ -0,0 +1,176 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.DoubleFunction; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/FloatCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/FloatCache.java new file mode 100644 index 0000000..cb53c56 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/FloatCache.java @@ -0,0 +1,175 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.floats.Float2ObjectFunction; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/HashCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/HashCache.java new file mode 100644 index 0000000..b58d8c5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/HashCache.java @@ -0,0 +1,84 @@ +package com.modularmc.mmclutils.collection.cache; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/HashInterner.java b/src/main/java/com/modularmc/mmclutils/collection/cache/HashInterner.java new file mode 100644 index 0000000..c6e5147 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/HashInterner.java @@ -0,0 +1,47 @@ +package com.modularmc.mmclutils.collection.cache; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** 按相等策略驻留或查找对象。驻留条目由该实例持有。 */ +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/collection/cache/HashSegment.java b/src/main/java/com/modularmc/mmclutils/collection/cache/HashSegment.java new file mode 100644 index 0000000..b530da4 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/HashSegment.java @@ -0,0 +1,91 @@ +package com.modularmc.mmclutils.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/collection/cache/IdentityHashCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/IdentityHashCache.java new file mode 100644 index 0000000..f4133ca --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/IdentityHashCache.java @@ -0,0 +1,202 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/IntCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/IntCache.java new file mode 100644 index 0000000..d9c3ef3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/IntCache.java @@ -0,0 +1,176 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.IntFunction; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/Interner.java b/src/main/java/com/modularmc/mmclutils/collection/cache/Interner.java new file mode 100644 index 0000000..50301b9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/Interner.java @@ -0,0 +1,24 @@ +package com.modularmc.mmclutils.collection.cache; + +import java.util.function.UnaryOperator; + +/** 驻留相等对象并返回共享实例。弱引用实现允许无外部引用的实例被回收。 */ +public interface Interner { + + UnaryOperator IDENTITY_OPERATOR = UnaryOperator.identity(); + + @SuppressWarnings("unchecked") + static UnaryOperator identityMappingFunction() { + return (UnaryOperator) IDENTITY_OPERATOR; + } + + T intern(final T sample); + + T intern(final T sample, UnaryOperator mappingFunction); + + boolean isPresent(final T sample); + + boolean addIfAbsent(final T sample); + + void clear(); +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/cache/LoadingCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/LoadingCache.java new file mode 100644 index 0000000..0fa7b42 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/LoadingCache.java @@ -0,0 +1,35 @@ +package com.modularmc.mmclutils.collection.cache; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** 按键获取或计算缓存值。提供给计算函数的执行时机由各方法说明,缺失返回空值,缓存支持主动清除。 */ +public interface LoadingCache { + + V getCache(final K k, Function createFunction); + + V getCache(final K k, Function createFunction, UnaryOperator keyMappingFunction); + + V getCacheRecursive(final K k, Function createFunction); + + V getCacheRecursive(final K k, Function createFunction, UnaryOperator keyMappingFunction); + + /** 根据参数构造容器。 */ + default Function createFunction() { + return null; + } + + default V getCache(final K k) { + return getCache(k, createFunction()); + } + + default V getCacheRecursive(final K k) { + return getCacheRecursive(k, createFunction()); + } + + V getIfPresent(final K k); + + V putIfAbsent(final K k, final V v); + + void clear(); +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/cache/LongCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/LongCache.java new file mode 100644 index 0000000..c956e95 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/LongCache.java @@ -0,0 +1,176 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.LongFunction; + +/** 按键保存可复用的值。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/ReclaimableCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/ReclaimableCache.java new file mode 100644 index 0000000..ec3f18f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/ReclaimableCache.java @@ -0,0 +1,7 @@ +package com.modularmc.mmclutils.collection.cache; + +/** 弱引用缓存向清理线程提供的回收入口。 */ +interface ReclaimableCache { + + void clearCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/cache/SegmentedCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/SegmentedCache.java new file mode 100644 index 0000000..84489bc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/SegmentedCache.java @@ -0,0 +1,47 @@ +package com.modularmc.mmclutils.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/collection/cache/WeakCustomHashInterner.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakCustomHashInterner.java new file mode 100644 index 0000000..43f3717 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakCustomHashInterner.java @@ -0,0 +1,189 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.UnaryOperator; + +/** 按相等策略驻留或查找对象。无强引用的条目可以回收。 */ +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/collection/cache/WeakHashInterner.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakHashInterner.java new file mode 100644 index 0000000..8d20a85 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakHashInterner.java @@ -0,0 +1,180 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.UnaryOperator; + +/** 按相等策略驻留或查找对象。无强引用的条目可以回收。 */ +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/collection/cache/WeakHashSegment.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakHashSegment.java new file mode 100644 index 0000000..78cc8e8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakHashSegment.java @@ -0,0 +1,103 @@ +package com.modularmc.mmclutils.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/collection/cache/WeakReferenceNode.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakReferenceNode.java new file mode 100644 index 0000000..7423f85 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakReferenceNode.java @@ -0,0 +1,27 @@ +package com.modularmc.mmclutils.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/collection/cache/WeakReferenceValueNode.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakReferenceValueNode.java new file mode 100644 index 0000000..32ec861 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakReferenceValueNode.java @@ -0,0 +1,29 @@ +package com.modularmc.mmclutils.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/collection/cache/WeakSegmentedCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakSegmentedCache.java new file mode 100644 index 0000000..133573a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakSegmentedCache.java @@ -0,0 +1,28 @@ +package com.modularmc.mmclutils.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/collection/cache/WeakValueByteCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueByteCache.java new file mode 100644 index 0000000..c3b273a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueByteCache.java @@ -0,0 +1,211 @@ +package com.modularmc.mmclutils.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; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/WeakValueCustomHashCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueCustomHashCache.java new file mode 100644 index 0000000..fc30cdb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueCustomHashCache.java @@ -0,0 +1,221 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/WeakValueDoubleCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueDoubleCache.java new file mode 100644 index 0000000..de17ee2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueDoubleCache.java @@ -0,0 +1,211 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.function.DoubleFunction; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/WeakValueFloatCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueFloatCache.java new file mode 100644 index 0000000..01dbe2a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueFloatCache.java @@ -0,0 +1,211 @@ +package com.modularmc.mmclutils.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; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/WeakValueHashCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueHashCache.java new file mode 100644 index 0000000..d60430d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueHashCache.java @@ -0,0 +1,211 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/WeakValueIdentityHashCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueIdentityHashCache.java new file mode 100644 index 0000000..b693e2d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueIdentityHashCache.java @@ -0,0 +1,237 @@ +package com.modularmc.mmclutils.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; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/WeakValueIntCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueIntCache.java new file mode 100644 index 0000000..44f2482 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueIntCache.java @@ -0,0 +1,211 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.function.IntFunction; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/cache/WeakValueLongCache.java b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueLongCache.java new file mode 100644 index 0000000..10e22b8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/WeakValueLongCache.java @@ -0,0 +1,211 @@ +package com.modularmc.mmclutils.collection.cache; + +import it.unimi.dsi.fastutil.HashCommon; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.function.LongFunction; + +/** 按键保存弱引用值,无外部引用的值可由回收线程移除。 计算函数在锁外运行,并发写入在分段锁内合并。 */ +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/collection/map/MultiMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/MultiMap.java new file mode 100644 index 0000000..ab5ec33 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/MultiMap.java @@ -0,0 +1,169 @@ +package com.modularmc.mmclutils.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; + +/** 实例由单个调用线程使用。 */ +public interface MultiMap { + + static MultiMap create(Map> map, Supplier> factory) { + return new MultiMapWrapper<>(map, factory); + } + + 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(); + + 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/collection/map/NestedMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/NestedMap.java new file mode 100644 index 0000000..5e605d7 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/NestedMap.java @@ -0,0 +1,173 @@ +package com.modularmc.mmclutils.collection.map; + +import com.modularmc.mmclutils.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; + +/** 实例由单个调用线程使用。 */ +public interface NestedMap { + + static NestedMap create(Map> map, Supplier> factory) { + return new NestedMapWrapper<>(map, factory); + } + + static NestedMap create(Supplier> factory) { + return new NestedMapWrapper<>(new HashMap<>(), factory); + } + + 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(); + + 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/collection/map/NestedMultiMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/NestedMultiMap.java new file mode 100644 index 0000000..a0cfbd2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/NestedMultiMap.java @@ -0,0 +1,243 @@ +package com.modularmc.mmclutils.collection.map; + +import com.modularmc.mmclutils.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; + +/** 实例由单个调用线程使用。 */ +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(); + + final class NestedMultiMapWrapper implements NestedMultiMap { + + private final Map>> map; + private final Reference2ReferenceFunction>> mapFactory; + private final Reference2ReferenceFunction> collectionFactory; + private final boolean isRefMap; + + private boolean isInnerRefMap; + + 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/collection/map/enums/Enum2BooleanMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2BooleanMap.java new file mode 100644 index 0000000..2710f17 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2BooleanMap.java @@ -0,0 +1,497 @@ +package com.modularmc.mmclutils.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/collection/map/enums/Enum2ByteMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ByteMap.java new file mode 100644 index 0000000..fea59ad --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ByteMap.java @@ -0,0 +1,540 @@ +package com.modularmc.mmclutils.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; + } + + 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/collection/map/enums/Enum2CharMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2CharMap.java new file mode 100644 index 0000000..4058c1a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2CharMap.java @@ -0,0 +1,534 @@ +package com.modularmc.mmclutils.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; + } + + 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/collection/map/enums/Enum2DoubleMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2DoubleMap.java new file mode 100644 index 0000000..a3e2c10 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2DoubleMap.java @@ -0,0 +1,535 @@ +package com.modularmc.mmclutils.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; + } + + 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/collection/map/enums/Enum2FloatMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2FloatMap.java new file mode 100644 index 0000000..c4d59ea --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2FloatMap.java @@ -0,0 +1,535 @@ +package com.modularmc.mmclutils.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; + } + + 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/collection/map/enums/Enum2IntMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2IntMap.java new file mode 100644 index 0000000..71774ad --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2IntMap.java @@ -0,0 +1,534 @@ +package com.modularmc.mmclutils.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; + } + + 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/collection/map/enums/Enum2LongMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2LongMap.java new file mode 100644 index 0000000..0223404 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2LongMap.java @@ -0,0 +1,534 @@ +package com.modularmc.mmclutils.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; + } + + 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/collection/map/enums/Enum2ObjectMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ObjectMap.java new file mode 100644 index 0000000..d01af6c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ObjectMap.java @@ -0,0 +1,524 @@ +package com.modularmc.mmclutils.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/collection/map/enums/Enum2ShortMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ShortMap.java new file mode 100644 index 0000000..97cbccc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/Enum2ShortMap.java @@ -0,0 +1,534 @@ +package com.modularmc.mmclutils.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; + } + + 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/collection/map/enums/EnumMaps.java b/src/main/java/com/modularmc/mmclutils/collection/map/enums/EnumMaps.java new file mode 100644 index 0000000..00bc57b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/enums/EnumMaps.java @@ -0,0 +1,20 @@ +package com.modularmc.mmclutils.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/collection/map/hash/Object2BooleanOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCachedHashMap.java new file mode 100644 index 0000000..0b6a7c2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCachedHashMap.java @@ -0,0 +1,1081 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.booleans.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2BooleanOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2BooleanOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2BooleanOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2BooleanOpenCachedHashMap(final Object2BooleanMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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(key)) 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/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java new file mode 100644 index 0000000..56caedf --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java @@ -0,0 +1,1084 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.booleans.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2BooleanOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2BooleanOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2BooleanOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2BooleanOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2BooleanOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2BooleanOpenCustomCachedHashMap(final Object2BooleanMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = 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 (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 = 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 (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 = 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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2ByteOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCachedHashMap.java new file mode 100644 index 0000000..1b25cbd --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCachedHashMap.java @@ -0,0 +1,1131 @@ +package com.modularmc.mmclutils.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.bytes.ByteBinaryOperator; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2ByteOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2ByteOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2ByteOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2ByteOpenCachedHashMap(final Object2ByteMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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(key)) 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/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java new file mode 100644 index 0000000..b22d2e2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java @@ -0,0 +1,1134 @@ +package com.modularmc.mmclutils.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.bytes.ByteBinaryOperator; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2ByteOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2ByteOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2ByteOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2ByteOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2ByteOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2ByteOpenCustomCachedHashMap(final Object2ByteMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = 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 (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 = 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 (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 = 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 (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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2CharOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCachedHashMap.java new file mode 100644 index 0000000..340bda9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCachedHashMap.java @@ -0,0 +1,1131 @@ +package com.modularmc.mmclutils.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.chars.CharBinaryOperator; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2CharOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2CharOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2CharOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2CharOpenCachedHashMap(final Object2CharMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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(key)) 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/collection/map/hash/Object2CharOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCustomCachedHashMap.java new file mode 100644 index 0000000..ab906a5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCustomCachedHashMap.java @@ -0,0 +1,1134 @@ +package com.modularmc.mmclutils.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.chars.CharBinaryOperator; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2CharOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2CharOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2CharOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2CharOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2CharOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2CharOpenCustomCachedHashMap(final Object2CharMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = 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 (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 = 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 (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 = 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 (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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2DoubleOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCachedHashMap.java new file mode 100644 index 0000000..4bf949a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCachedHashMap.java @@ -0,0 +1,1133 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.doubles.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2DoubleOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2DoubleOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2DoubleOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2DoubleOpenCachedHashMap(final Object2DoubleMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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(key)) 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/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java new file mode 100644 index 0000000..b6162d8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java @@ -0,0 +1,1137 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.doubles.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2DoubleOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2DoubleOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2DoubleOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2DoubleOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2DoubleOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2DoubleOpenCustomCachedHashMap(final Object2DoubleMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = 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 (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 = 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 (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 = 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 (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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2FloatOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCachedHashMap.java new file mode 100644 index 0000000..c31de0d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCachedHashMap.java @@ -0,0 +1,1132 @@ +package com.modularmc.mmclutils.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.floats.FloatBinaryOperator; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2FloatOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2FloatOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2FloatOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2FloatOpenCachedHashMap(final Object2FloatMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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(key)) 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/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java new file mode 100644 index 0000000..89403fd --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java @@ -0,0 +1,1136 @@ +package com.modularmc.mmclutils.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.floats.FloatBinaryOperator; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2FloatOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2FloatOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2FloatOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2FloatOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2FloatOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2FloatOpenCustomCachedHashMap(final Object2FloatMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = 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 (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 = 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 (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 = 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 (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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2IntOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCachedHashMap.java new file mode 100644 index 0000000..0ae1a11 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCachedHashMap.java @@ -0,0 +1,1131 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.ints.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2IntOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2IntOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2IntOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2IntOpenCachedHashMap(final Object2IntMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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(key)) 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/collection/map/hash/Object2IntOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCustomCachedHashMap.java new file mode 100644 index 0000000..67a69af --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCustomCachedHashMap.java @@ -0,0 +1,1134 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.ints.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2IntOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2IntOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2IntOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2IntOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2IntOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2IntOpenCustomCachedHashMap(final Object2IntMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = strategy.hashCode(k); + 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 = 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 (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 = 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 (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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2LongOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java new file mode 100644 index 0000000..db72312 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java @@ -0,0 +1,1130 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.longs.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2LongOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2LongOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2LongOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2LongOpenCachedHashMap(final Object2LongMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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; + } + + @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(key)) 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/collection/map/hash/Object2LongOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCustomCachedHashMap.java new file mode 100644 index 0000000..843c4f1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCustomCachedHashMap.java @@ -0,0 +1,1134 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.longs.*; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2LongOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2LongOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2LongOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2LongOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2LongOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2LongOpenCustomCachedHashMap(final Object2LongMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = strategy.hashCode(k); + 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 = 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 (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 = 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 (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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2ObjectOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ObjectOpenCachedHashMap.java new file mode 100644 index 0000000..aa75cf1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ObjectOpenCachedHashMap.java @@ -0,0 +1,1080 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2ObjectOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2ObjectOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2ObjectOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2ObjectOpenCachedHashMap(final Object2ObjectMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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/collection/map/hash/Object2ObjectOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ObjectOpenCustomCachedHashMap.java new file mode 100644 index 0000000..8981674 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ObjectOpenCustomCachedHashMap.java @@ -0,0 +1,1077 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.objects.*; + +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; + + public Object2ObjectOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2ObjectOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2ObjectOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2ObjectOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2ObjectOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2ObjectOpenCustomCachedHashMap(final Object2ObjectMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 = 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 (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 = 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 (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 (((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 (((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; + } + 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/collection/map/hash/Object2ShortOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCachedHashMap.java new file mode 100644 index 0000000..88e062c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCachedHashMap.java @@ -0,0 +1,1131 @@ +package com.modularmc.mmclutils.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 it.unimi.dsi.fastutil.shorts.ShortBinaryOperator; + +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; + + public Object2ShortOpenCachedHashMap(final int expected, final float f) { + super(expected, f); + hash = new int[n + 1]; + } + + 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]; + } + + public Object2ShortOpenCachedHashMap(final Map m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(m); + } + + public Object2ShortOpenCachedHashMap(final Map m) { + this(m, DEFAULT_LOAD_FACTOR); + } + + public Object2ShortOpenCachedHashMap(final Object2ShortMap m, final float f) { + super(m.size(), f); + hash = new int[n + 1]; + putAll(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(key)) 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/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java new file mode 100644 index 0000000..e07f5d3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java @@ -0,0 +1,1134 @@ +package com.modularmc.mmclutils.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 it.unimi.dsi.fastutil.shorts.ShortBinaryOperator; + +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; + + public Object2ShortOpenCustomCachedHashMap(final int expected, final float f, final Strategy strategy) { + super(expected, f, strategy); + hash = new int[n + 1]; + } + + public Object2ShortOpenCustomCachedHashMap(final int expected, final Strategy strategy) { + super(expected, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2ShortOpenCustomCachedHashMap(final Strategy strategy) { + super(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR, strategy); + hash = new int[n + 1]; + } + + public Object2ShortOpenCustomCachedHashMap(final Map m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + public Object2ShortOpenCustomCachedHashMap(final Map m, final Strategy strategy) { + this(m, DEFAULT_LOAD_FACTOR, strategy); + } + + public Object2ShortOpenCustomCachedHashMap(final Object2ShortMap m, final float f, final Strategy strategy) { + super(m.size(), f, strategy); + hash = new int[n + 1]; + putAll(m); + } + + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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(key)) 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 = 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 (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 = 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 (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 = 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 (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 (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 (((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 (((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; + } + 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/collection/map/hash/ObjectOpenCachedHashSet.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/ObjectOpenCachedHashSet.java new file mode 100644 index 0000000..ce57232 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/ObjectOpenCachedHashSet.java @@ -0,0 +1,482 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.objects.*; + +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; + + 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); + } + + public ObjectOpenCachedHashSet(final ObjectCollection c, final float f) { + super(c.size(), f); + hash = new int[n + 1]; + addAll(c); + } + + 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/collection/map/hash/ObjectOpenCustomCachedHashSet.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/ObjectOpenCustomCachedHashSet.java new file mode 100644 index 0000000..2c23788 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/ObjectOpenCustomCachedHashSet.java @@ -0,0 +1,489 @@ +package com.modularmc.mmclutils.collection.map.hash; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.HashCommon; +import it.unimi.dsi.fastutil.objects.*; + +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; + + 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); + } + + public ObjectOpenCustomCachedHashSet(final ObjectCollection c, final float f, final Hash.Strategy strategy) { + super(c.size(), f, strategy); + hash = new int[n + 1]; + addAll(c); + } + + 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 (k == null) { + if (containsNull) return false; + containsNull = true; + } 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 (k == null) { + if (containsNull) return key[n]; + containsNull = true; + } 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 (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 (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 (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; + } + 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/function/TriConsumer.java b/src/main/java/com/modularmc/mmclutils/function/TriConsumer.java new file mode 100644 index 0000000..f92c503 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/TriConsumer.java @@ -0,0 +1,8 @@ +package com.modularmc.mmclutils.function; + +/** 接收三个参数的操作接口,用于避免在迭代中分配临时元组。 */ +@FunctionalInterface +public interface TriConsumer { + + void accept(A a, B b, C c); +} From 8bd66ac32fa09b612af62feefa427a156b63d6f3 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 00:46:00 +0800 Subject: [PATCH 03/79] =?UTF-8?q?=E6=8E=A5=E5=85=A5=E7=BB=B4=E5=BA=A6?= =?UTF-8?q?=E8=B0=83=E5=BA=A6=E4=B8=8E=E5=BC=82=E6=AD=A5=E5=AD=98=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 17 +- gradle/scripts/jars.gradle | 3 +- .../client/ModularMCLibUtilsClient.java | 14 + .../client/level/ClientChunkVisibility.java | 57 + .../schedule/ClientSchedulerEvents.java | 29 + .../concurrent/SerialTaskExecutor.java | 36 + .../modularmc/mmclutils/io/BinaryFiles.java | 61 + .../mmclutils/level/LevelLifecycle.java | 23 + .../mmclutils/level/LevelSlotHolder.java | 17 + .../modularmc/mmclutils/level/LevelStore.java | 189 +++ .../mmclutils/level/LoadedChunkSource.java | 13 + .../mmclutils/level/LoadedChunks.java | 55 + .../mmclutils/level/RecentChunks.java | 43 + .../client/level/ClientChunkCacheMixin.java | 40 + .../client/level/ClientChunkStorageMixin.java | 33 + .../mmclutils/mixin/level/LevelMixin.java | 39 + .../mixin/level/ServerChunkCacheMixin.java | 58 + .../mixin/level/ServerLevelSaveMixin.java | 21 + .../mixin/spatial/BlockEntityMixin.java | 25 + .../mixin/spatial/LevelChunkMixin.java | 77 ++ .../mmclutils/persistence/ChangeTracker.java | 24 + .../mmclutils/persistence/FastSavedData.java | 177 +++ .../mmclutils/schedule/AsyncLane.java | 152 +++ .../modularmc/mmclutils/schedule/Cadence.java | 57 + .../modularmc/mmclutils/schedule/Cell.java | 143 +++ .../mmclutils/schedule/CoalescedTask.java | 84 ++ .../mmclutils/schedule/KeyedSignal.java | 96 ++ .../mmclutils/schedule/OwnedScope.java | 35 + .../modularmc/mmclutils/schedule/Poll.java | 49 + .../mmclutils/schedule/Schedulers.java | 128 ++ .../modularmc/mmclutils/schedule/Scope.java | 1040 +++++++++++++++++ .../mmclutils/schedule/ScopeKey.java | 30 + .../mmclutils/schedule/ScopeKind.java | 201 ++++ .../mmclutils/schedule/ScopeSlot.java | 91 ++ .../mmclutils/schedule/SharedPool.java | 158 +++ .../modularmc/mmclutils/schedule/Signal.java | 248 ++++ .../modularmc/mmclutils/schedule/Task.java | 23 + .../mmclutils/schedule/TickBatch.java | 81 ++ .../mmclutils/schedule/TickScheduler.java | 735 ++++++++++++ .../mmclutils/schedule/WaitList.java | 129 ++ .../mmclutils/spatial/BlockEntityIndex.java | 121 ++ .../spatial/BlockEntityTracking.java | 62 + .../mmclutils/spatial/BlockIndex.java | 258 ++++ .../mmclutils/spatial/BlockOctree.java | 653 +++++++++++ .../mmclutils/spatial/BlockPositions.java | 130 +++ .../mmclutils/spatial/BlockRange.java | 126 ++ .../mmclutils/spatial/LevelBlockIndex.java | 54 + .../mmclutils/spatial/LevelSections.java | 149 +++ .../spatial/ProbedBlockEntityIndex.java | 72 ++ .../mmclutils/spatial/ProbedSink.java | 178 +++ .../mmclutils/spatial/SectionScan.java | 372 ++++++ .../mmclutils/spatial/TrackedBlockEntity.java | 11 + .../mmclutils/spatial/TrackedChunk.java | 11 + .../modularmc/mmclutils/spatial/Tracker.java | 113 ++ .../mmclutils/spatial/TypedSink.java | 53 + .../resources/META-INF/accesstransformer.cfg | 1 + src/main/resources/mmclutils.mixins.json | 13 +- .../templates/META-INF/neoforge.mods.toml | 2 - 58 files changed, 6888 insertions(+), 22 deletions(-) create mode 100644 src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/schedule/ClientSchedulerEvents.java create mode 100644 src/main/java/com/modularmc/mmclutils/concurrent/SerialTaskExecutor.java create mode 100644 src/main/java/com/modularmc/mmclutils/io/BinaryFiles.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/LevelLifecycle.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/LevelSlotHolder.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/LevelStore.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/LoadedChunkSource.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/LoadedChunks.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/RecentChunks.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/client/level/ClientChunkCacheMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/client/level/ClientChunkStorageMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/level/LevelMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/level/ServerChunkCacheMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/level/ServerLevelSaveMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/spatial/BlockEntityMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/spatial/LevelChunkMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/persistence/ChangeTracker.java create mode 100644 src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/AsyncLane.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/Cadence.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/Cell.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/CoalescedTask.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/KeyedSignal.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/OwnedScope.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/Poll.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/Schedulers.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/Scope.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/ScopeKey.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/ScopeKind.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/ScopeSlot.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/SharedPool.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/Signal.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/Task.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/TickBatch.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/TickScheduler.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/WaitList.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockEntityIndex.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockEntityTracking.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockIndex.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockOctree.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockPositions.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockRange.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/LevelBlockIndex.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/ProbedBlockEntityIndex.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/ProbedSink.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/SectionScan.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/TrackedBlockEntity.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/TrackedChunk.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/Tracker.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/TypedSink.java diff --git a/build.gradle b/build.gradle index f187d92..e1cb842 100644 --- a/build.gradle +++ b/build.gradle @@ -27,34 +27,20 @@ sourceSets { srcDir 'src/generated/resources' } - client { - compileClasspath += main.output - runtimeClasspath += main.output + main.runtimeClasspath - } - extra { compileClasspath += main.output runtimeClasspath += main.output + main.runtimeClasspath } - - clientExtra { - compileClasspath += client.output + extra.compileClasspath - runtimeClasspath += client.output + client.runtimeClasspath + extra.runtimeClasspath - } } configurations { // set these as unresolvable so we don't accidentally force all dependents to use them with us - clientRuntimeOnly.canBeResolved = false extraRuntimeOnly.canBeResolved = false - clientExtraRuntimeOnly.canBeResolved = false testImplementation.canBeResolved = false testRuntimeOnly.canBeResolved = false runtimeClasspath.extendsFrom localRuntime extraRuntimeClasspath.extendsFrom extraLocalRuntime - clientRuntimeClasspath.extendsFrom clientLocalRuntime - extraClientRuntimeClasspath.extendsFrom clientExtraLocalRuntime renderNurseCfg { canBeConsumed = false @@ -77,10 +63,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" -} \ No newline at end of file +} diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 68f1c5d..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': "mmclutils.mixins.json", 'Specification-Title': project.name, 'Specification-Version': mod_version, 'Specification-Vendor': 'ModularMCLib Team', 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..be8fca5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java @@ -0,0 +1,14 @@ +package com.modularmc.mmclutils.client; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; + +/** 注册仅在物理客户端加载的入口。 */ +@Mod(value = ModularMCLibUtils.MOD_ID, dist = Dist.CLIENT) +public final class ModularMCLibUtilsClient { + + public ModularMCLibUtilsClient(IEventBus modBus) {} +} 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..3588f0e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/ClientChunkVisibility.java @@ -0,0 +1,57 @@ +package com.modularmc.mmclutils.client.level; + +import com.modularmc.mmclutils.spatial.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/schedule/ClientSchedulerEvents.java b/src/main/java/com/modularmc/mmclutils/client/schedule/ClientSchedulerEvents.java new file mode 100644 index 0000000..89aff72 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/schedule/ClientSchedulerEvents.java @@ -0,0 +1,29 @@ +package com.modularmc.mmclutils.client.schedule; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.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; + +@ApiStatus.Internal +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID, value = Dist.CLIENT) +public final class ClientSchedulerEvents { + + private ClientSchedulerEvents() {} + + @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/concurrent/SerialTaskExecutor.java b/src/main/java/com/modularmc/mmclutils/concurrent/SerialTaskExecutor.java new file mode 100644 index 0000000..500fda6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/concurrent/SerialTaskExecutor.java @@ -0,0 +1,36 @@ +package com.modularmc.mmclutils.concurrent; + +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** 单工作者按提交顺序执行操作。关闭时等待已接收的操作执行完毕。 */ +public final class SerialTaskExecutor implements AutoCloseable { + + private final ExecutorService executor; + + public SerialTaskExecutor(String name) { + executor = Executors.newSingleThreadExecutor(Thread.ofVirtual().name(name).factory()); + } + + 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/io/BinaryFiles.java b/src/main/java/com/modularmc/mmclutils/io/BinaryFiles.java new file mode 100644 index 0000000..7749d6c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/io/BinaryFiles.java @@ -0,0 +1,61 @@ +package com.modularmc.mmclutils.io; + +import org.jspecify.annotations.NullMarked; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** 以缓冲流读写二进制文件。写入在同一目录内完成原子替换。 */ +@NullMarked +public final class BinaryFiles { + + private BinaryFiles() {} + + /** 读取存在的文件。回调返回后流由本方法关闭。 */ + public static T read(Path path, Reader reader) throws IOException { + try (var input = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) { + return reader.read(input); + } + } + + /** 仅在输出流关闭成功后替换目标。读取方始终看到一份完整的文件。 */ + public static void writeAtomically(Path path, T value, Writer writer) throws IOException { + Path target = path.toAbsolutePath().normalize(); + Path directory = target.getParent(); + Files.createDirectories(directory); + Path temporary = Files.createTempFile(directory, ".mmclutils-", ".tmp"); + try { + try (var output = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(temporary)))) { + writer.write(output, value); + } + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException | RuntimeException | Error failure) { + try { + Files.deleteIfExists(temporary); + } catch (IOException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + } + + /** 读取一个完整的值。调用期间输入流有效,格式错误通过 IOException 报告。 */ + @FunctionalInterface + public interface Reader { + + T read(DataInputStream input) throws IOException; + } + + /** 按与读取器相同的布局写入值。输出流由调用方管理。 */ + @FunctionalInterface + public interface Writer { + + void write(DataOutputStream output, T value) throws IOException; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/level/LevelLifecycle.java b/src/main/java/com/modularmc/mmclutils/level/LevelLifecycle.java new file mode 100644 index 0000000..abe7bb8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/LevelLifecycle.java @@ -0,0 +1,23 @@ +package com.modularmc.mmclutils.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 org.jetbrains.annotations.ApiStatus; + +/** 维度卸载时释放挂在实例上的状态和调度资源。 */ +@ApiStatus.Internal +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID) +public final class LevelLifecycle { + + private LevelLifecycle() {} + + @SubscribeEvent + private static void onUnload(LevelEvent.Unload event) { + if (event.getLevel() instanceof Level level) LevelStore.releaseAll(level); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/level/LevelSlotHolder.java b/src/main/java/com/modularmc/mmclutils/level/LevelSlotHolder.java new file mode 100644 index 0000000..81951f8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/LevelSlotHolder.java @@ -0,0 +1,17 @@ +package com.modularmc.mmclutils.level; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +@ApiStatus.Internal +public interface LevelSlotHolder { + + @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/level/LevelStore.java b/src/main/java/com/modularmc/mmclutils/level/LevelStore.java new file mode 100644 index 0000000..06d0a98 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/LevelStore.java @@ -0,0 +1,189 @@ +package com.modularmc.mmclutils.level; + +import net.minecraft.world.level.Level; + +import com.mojang.logging.LogUtils; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.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}:维度卸载时由 GTOUtils 统一调用,逐个调用释放回调后丢弃全部,之后 {@link #isReleased} + * 为真
  • + *
  • 按维度实例区分,客户端和服务端的维度互不影响;任何线程都能读写,存放的对象本身是否线程安全由使用方负责
  • + *
+ */ +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((LevelSlotHolder) level); + } + + public @Nullable T getIfPresent(Level level) { + return forHolderIfPresent((LevelSlotHolder) level); + } + + public void set(Level level, @Nullable T value) { + setHolder((LevelSlotHolder) level, value); + } + + public void release(Level level) { + releaseHolder((LevelSlotHolder) level); + } + + public static void releaseAll(Level level) { + releaseAllHolder((LevelSlotHolder) level); + } + + public static boolean isReleased(Level level) { + return ((LevelSlotHolder) level).mmclutils$released(); + } + + @ApiStatus.Internal + @SuppressWarnings("unchecked") + public T forHolder(LevelSlotHolder 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(LevelSlotHolder holder) { + Object[] slots = holder.mmclutils$slots(); + return slots != null && slot < slots.length ? (T) SLOT.getAcquire(slots, slot) : null; + } + + @ApiStatus.Internal + public void setHolder(LevelSlotHolder 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(LevelSlotHolder 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(LevelSlotHolder 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(LevelSlotHolder 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(LevelSlotHolder 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("GTOUtils: level store release callback failed", t); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/level/LoadedChunkSource.java b/src/main/java/com/modularmc/mmclutils/level/LoadedChunkSource.java new file mode 100644 index 0000000..4e53173 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/LoadedChunkSource.java @@ -0,0 +1,13 @@ +package com.modularmc.mmclutils.level; + +import net.minecraft.world.level.chunk.LevelChunk; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +@ApiStatus.Internal +public interface LoadedChunkSource { + + @Nullable + LevelChunk mmclutils$loadedChunk(int chunkX, int chunkZ); +} diff --git a/src/main/java/com/modularmc/mmclutils/level/LoadedChunks.java b/src/main/java/com/modularmc/mmclutils/level/LoadedChunks.java new file mode 100644 index 0000000..3b28aa6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/LoadedChunks.java @@ -0,0 +1,55 @@ +package com.modularmc.mmclutils.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.Nullable; + +/** + * 只读已加载完成的区块,绝不触发加载,也不阻塞主线程。功能: + *
    + *
  • {@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 LoadedChunkSource 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; + } + + 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; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/level/RecentChunks.java b/src/main/java/com/modularmc/mmclutils/level/RecentChunks.java new file mode 100644 index 0000000..00b7baf --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/RecentChunks.java @@ -0,0 +1,43 @@ +package com.modularmc.mmclutils.level; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; + +/** + * 最近取过的 4 个区块的缓存,供多个线程无锁共用。功能: + *
    + *
  • {@link #get}:按打包坐标找,命中返回缓存的值,否则返回 null
  • + *
  • {@link #put}:轮流覆盖 4 个槽位;坐标和值放在同一个不可变对象里,并发读写时只会读到某一次完整写入的坐标和值,不会读到错位的一对
  • + *
  • {@link #clear}:清空全部槽位
  • + *
+ */ +@ApiStatus.Internal +public 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/mixin/client/level/ClientChunkCacheMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/client/level/ClientChunkCacheMixin.java new file mode 100644 index 0000000..859add6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/client/level/ClientChunkCacheMixin.java @@ -0,0 +1,40 @@ +package com.modularmc.mmclutils.mixin.client.level; + +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/client/level/ClientChunkStorageMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/client/level/ClientChunkStorageMixin.java new file mode 100644 index 0000000..38c7b73 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/client/level/ClientChunkStorageMixin.java @@ -0,0 +1,33 @@ +package com.modularmc.mmclutils.mixin.client.level; + +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/level/LevelMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/level/LevelMixin.java new file mode 100644 index 0000000..79ef916 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/level/LevelMixin.java @@ -0,0 +1,39 @@ +package com.modularmc.mmclutils.mixin.level; + +import com.modularmc.mmclutils.level.LevelSlotHolder; + +import net.minecraft.world.level.Level; + +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +@Mixin(Level.class) +public abstract class LevelMixin implements LevelSlotHolder { + + @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/level/ServerChunkCacheMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/level/ServerChunkCacheMixin.java new file mode 100644 index 0000000..318e64b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/level/ServerChunkCacheMixin.java @@ -0,0 +1,58 @@ +package com.modularmc.mmclutils.mixin.level; + +import com.modularmc.mmclutils.level.LoadedChunkSource; +import com.modularmc.mmclutils.level.RecentChunks; + +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.jetbrains.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 LoadedChunkSource { + + @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/level/ServerLevelSaveMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/level/ServerLevelSaveMixin.java new file mode 100644 index 0000000..a0dacb3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/level/ServerLevelSaveMixin.java @@ -0,0 +1,21 @@ +package com.modularmc.mmclutils.mixin.level; + +import com.modularmc.mmclutils.persistence.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 ServerLevelSaveMixin { + + @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/mixin/spatial/BlockEntityMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/spatial/BlockEntityMixin.java new file mode 100644 index 0000000..274cd24 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/spatial/BlockEntityMixin.java @@ -0,0 +1,25 @@ +package com.modularmc.mmclutils.mixin.spatial; + +import com.modularmc.mmclutils.spatial.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/spatial/LevelChunkMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/spatial/LevelChunkMixin.java new file mode 100644 index 0000000..deb4605 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/spatial/LevelChunkMixin.java @@ -0,0 +1,77 @@ +package com.modularmc.mmclutils.mixin.spatial; + +import com.modularmc.mmclutils.spatial.BlockEntityTracking; +import com.modularmc.mmclutils.spatial.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/persistence/ChangeTracker.java b/src/main/java/com/modularmc/mmclutils/persistence/ChangeTracker.java new file mode 100644 index 0000000..6972408 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/persistence/ChangeTracker.java @@ -0,0 +1,24 @@ +package com.modularmc.mmclutils.persistence; + +/** 区分当前状态与已经成功写盘的版本。变更和快照由拥有者线程产生。 */ +public final class ChangeTracker { + + private volatile long revision; + private volatile long persisted; + + public void markChanged() { + revision++; + } + + public long revision() { + return revision; + } + + public boolean isDirty() { + return revision != persisted; + } + + void persisted(long writtenRevision) { + persisted = writtenRevision; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java b/src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java new file mode 100644 index 0000000..82ad2d2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java @@ -0,0 +1,177 @@ +package com.modularmc.mmclutils.persistence; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.concurrent.SerialTaskExecutor; +import com.modularmc.mmclutils.io.BinaryFiles; +import com.modularmc.mmclutils.level.LevelStore; + +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; + +/** 按维度和稳定标识保存二进制数据。值的修改、取快照及保存调度均在服务器线程执行。 */ +@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 final ChangeTracker changes = new ChangeTracker(); + 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; + } + + /** 类型实例和标识由调用方长期持有。同一个标识在一份维度存储中只能注册一种类型。 */ + 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 = BinaryFiles.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; + } + + public T value() { + return value; + } + + /** 修改 value 后调用。已经在写盘的快照仍可完成,此次修改会进入下一次保存。 */ + public void setDirty() { + changes.markChanged(); + } + + public boolean isDirty() { + return changes.isDirty(); + } + + @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 revision = changes.revision(); + if (changes.isDirty() && (submitted != revision || pending.isCompletedExceptionally())) { + T snapshot = type.snapshot().apply(value); + submitted = revision; + pending = executor.submit(() -> { + BinaryFiles.writeAtomically(path, snapshot, type.writer()); + changes.persisted(revision); + return null; + }); + pending.whenComplete((ignored, failure) -> { + if (failure != null) ModularMCLibUtils.LOGGER.error("写入二进制存档 {} 失败", path, failure); + }); + } + if (wait) pending.handle((ignored, 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("存档须在所属服务器线程访问"); + } + + /** snapshot 应当返回可由写盘线程独立读取的值。读取失败时保留原有的存档文件。 */ + public record Type(Identifier id, Supplier factory, UnaryOperator snapshot, + BinaryFiles.Reader reader, BinaryFiles.Writer writer, + @Nullable LegacyFile legacy) { + + public Type(Identifier id, Supplier factory, UnaryOperator snapshot, + BinaryFiles.Reader reader, BinaryFiles.Writer writer) { + this(id, factory, snapshot, reader, writer, null); + } + } + + /** 指定相对于世界目录的旧存档和其读取方式。旧文件读取在服务器线程进行。 */ + public record LegacyFile(Path relativePath, LegacyReader reader) { + + public LegacyFile { + if (relativePath.isAbsolute()) throw new IllegalArgumentException("旧存档路径须相对于世界目录"); + } + } + + /** 支持读取原有的二进制或 NBT。需要注册表的读取器可使用所属维度的上下文。 */ + @FunctionalInterface + public interface LegacyReader { + + T read(ServerLevel level, Path path) throws IOException; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/schedule/AsyncLane.java b/src/main/java/com/modularmc/mmclutils/schedule/AsyncLane.java new file mode 100644 index 0000000..7415318 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/AsyncLane.java @@ -0,0 +1,152 @@ +package com.modularmc.mmclutils.schedule; + +import com.modularmc.mmclutils.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; + +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); + } + + 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; + } + + 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; + }; + } + + 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("GTOUtils: async task on lane {} failed, owner {}", 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/schedule/Cadence.java b/src/main/java/com/modularmc/mmclutils/schedule/Cadence.java new file mode 100644 index 0000000..65a35bd --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/Cadence.java @@ -0,0 +1,57 @@ +package com.modularmc.mmclutils.schedule; + +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); + } + + 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; + } + + public static Cadence every(int period) { + int p = Math.max(1, period); + return p < CACHED.length ? CACHED[p] : new Cadence(p, AUTO); + } + + public Cadence phase(int phase) { + return new Cadence(period, Math.floorMod(phase, period)); + } + + public int period() { + return period; + } + + public boolean isAutoPhase() { + return phase == AUTO; + } + + 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/schedule/Cell.java b/src/main/java/com/modularmc/mmclutils/schedule/Cell.java new file mode 100644 index 0000000..8f19d18 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/Cell.java @@ -0,0 +1,143 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.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; + } + + public static Cell of(T initial) { + return new Cell<>(initial); + } + + public T get() { + changed.track(); + return value; + } + + public T peek() { + return value; + } + + 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/schedule/CoalescedTask.java b/src/main/java/com/modularmc/mmclutils/schedule/CoalescedTask.java new file mode 100644 index 0000000..4843a32 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/CoalescedTask.java @@ -0,0 +1,84 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.annotations.Nullable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.Objects; + +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); + } + + 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/schedule/KeyedSignal.java b/src/main/java/com/modularmc/mmclutils/schedule/KeyedSignal.java new file mode 100644 index 0000000..fa9b911 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/KeyedSignal.java @@ -0,0 +1,96 @@ +package com.modularmc.mmclutils.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/schedule/OwnedScope.java b/src/main/java/com/modularmc/mmclutils/schedule/OwnedScope.java new file mode 100644 index 0000000..c6b8816 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/OwnedScope.java @@ -0,0 +1,35 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +/** + * 拥有者手里的作用域:比 {@link Scope} 多一个结束的能力。功能: + *
    + *
  • {@link #root}:建一个无父作用域,绑定一条车道;名字可以给任意对象,用到时才转成字符串,作用域结束后不再引用它;在派生函数求值期间建立记一次误用
  • + *
  • {@link #dispose}:结束本作用域;幂等
  • + *
  • 只有 {@link Scope#child} 和 root 建出 OwnedScope;回调里拿到的作用域都不是它的实例,强转结束不了
  • + *
+ */ +public final class OwnedScope extends Scope { + + OwnedScope(Object label, TickScheduler lane, @Nullable Scope parent) { + super(label, lane, parent); + } + + public static OwnedScope root(String name, TickScheduler lane) { + checkFrame(name); + return new OwnedScope(name, lane, null); + } + + public static OwnedScope root(Object label, TickScheduler lane) { + Objects.requireNonNull(label, "label"); + checkFrame(label); + return new OwnedScope(label, lane, null); + } + + public void dispose() { + end(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/schedule/Poll.java b/src/main/java/com/modularmc/mmclutils/schedule/Poll.java new file mode 100644 index 0000000..6a58006 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/Poll.java @@ -0,0 +1,49 @@ +package com.modularmc.mmclutils.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/schedule/Schedulers.java b/src/main/java/com/modularmc/mmclutils/schedule/Schedulers.java new file mode 100644 index 0000000..7fe3825 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/Schedulers.java @@ -0,0 +1,128 @@ +package com.modularmc.mmclutils.schedule; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.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.jetbrains.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; + } + + public static TickScheduler of(Level level) { + if (LevelStore.isReleased(level)) return TickScheduler.CLOSED; + return MAIN.get(level); + } + + public static TickScheduler async(Level level) { + return AsyncLane.DEFAULT.scheduler(level); + } + + 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(); + } + + @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/schedule/Scope.java b/src/main/java/com/modularmc/mmclutils/schedule/Scope.java new file mode 100644 index 0000000..01448e1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/Scope.java @@ -0,0 +1,1040 @@ +package com.modularmc.mmclutils.schedule; + +import com.mojang.logging.LogUtils; +import org.jetbrains.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 OwnedScope#root} 返回能结束的 + * {@link OwnedScope},select、when、each、模块挂载、共享池、{@link ScopeSlot} 交给回调的作用域都不是 OwnedScope,强转后结束不了
  • + *
  • {@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 ScopeKey} 向所属实例(最近的 {@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 permits OwnedScope, Scope.Inner { + + 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("GTOUtils: {} failed in {}", what, place, 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("GTOUtils: {} failed in {}; later failures of this kind are only counted", what, place, error); + else if (n % FAILURE_SUMMARY_EVERY == 0) LOGGER.error("GTOUtils: {} failed {} times so far, latest in {}: {}", 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("GTOUtils scope misuse: " + what + " @ " + where); + if (REPORTED.putIfAbsent(what, Boolean.TRUE) != null) return; + String place = String.valueOf(where); + LOGGER.warn("GTOUtils: {} ({}) on thread {}; later occurrences are only counted", what, place, Thread.currentThread().getName(), new Throwable("call site")); + 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; + } + + public final boolean isActive() { + return active; + } + + public final OwnedScope child(String name) { + checkFrame(this); + return new OwnedScope(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(ScopeKey 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)); + } + + @Nullable + @SuppressWarnings("unchecked") + public final V lookup(ScopeKey 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; + } + + public final V require(ScopeKey key) { + V value = lookup(key); + if (value == null) throw new IllegalStateException("No " + key + " in scope " + this); + return value; + } + + private void put(ScopeKey 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(ScopeKey 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 { + + void mount(Scope scope, T value); + } + + @FunctionalInterface + public interface KeyedBody { + + 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) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/schedule/ScopeKey.java b/src/main/java/com/modularmc/mmclutils/schedule/ScopeKey.java new file mode 100644 index 0000000..92f6b3d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/ScopeKey.java @@ -0,0 +1,30 @@ +package com.modularmc.mmclutils.schedule; + +/** + * 作用域里一项带类型的服务的键。功能: + *
    + *
  • {@link #of}:建一个键;同名的两个键互不相同,按对象身份区分
  • + *
  • {@link Scope#provide}/{@link Scope#lookup}:在作用域里放入服务、沿父作用域向上查找;在派生里查找即自动依赖经过的实例,实例上放入或撤下服务时重算
  • + *
+ */ +public final class ScopeKey { + + private final String name; + + private ScopeKey(String name) { + this.name = name; + } + + public static ScopeKey of(String name) { + return new ScopeKey<>(name); + } + + public String name() { + return name; + } + + @Override + public String toString() { + return "ScopeKey[" + name + "]"; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/schedule/ScopeKind.java b/src/main/java/com/modularmc/mmclutils/schedule/ScopeKind.java new file mode 100644 index 0000000..835d5e3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/ScopeKind.java @@ -0,0 +1,201 @@ +package com.modularmc.mmclutils.schedule; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; +import org.jetbrains.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 OwnedScope},拿到的一方强转后结束不了;每个模块挂在实例下自己的子作用域里,它用 {@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 { + + 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, ScopeKey key) { + Scope scope = get(owner); + return scope == null ? null : scope.lookup(key); + } + + public V require(T owner, ScopeKey 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; + } + + 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); + } + + 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/schedule/ScopeSlot.java b/src/main/java/com/modularmc/mmclutils/schedule/ScopeSlot.java new file mode 100644 index 0000000..3aae9e6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/ScopeSlot.java @@ -0,0 +1,91 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.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 OwnedScope},强转后结束不了,只能经 {@link #close} 或再次 open 结束
  • + *
  • {@link #close}:结束槽里的作用域;幂等,槽空、作用域已自行结束、车道已关闭时什么也不做;在别的线程上调用按 {@link OwnedScope#dispose} 的规矩转投
  • + *
  • {@link #current}/{@link #isOpen}:槽里仍在活动的作用域,没有时为 null;槽字段是 volatile,别的线程上读到的是车道线程最近一次写入的作用域(写入用 + * release,不加全屏障)
  • + *
+ */ +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/schedule/SharedPool.java b/src/main/java/com/modularmc/mmclutils/schedule/SharedPool.java new file mode 100644 index 0000000..69b1dca --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/SharedPool.java @@ -0,0 +1,158 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.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 OwnedScope},{@link Pooled#scope} 拿到的一方强转后结束不了
  • + *
+ */ +public final class SharedPool { + + @FunctionalInterface + public interface Factory { + + 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/schedule/Signal.java b/src/main/java/com/modularmc/mmclutils/schedule/Signal.java new file mode 100644 index 0000000..488d6f7 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/Signal.java @@ -0,0 +1,248 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.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/schedule/Task.java b/src/main/java/com/modularmc/mmclutils/schedule/Task.java new file mode 100644 index 0000000..d19a6d2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/Task.java @@ -0,0 +1,23 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.annotations.Nullable; + +public interface Task { + + boolean isActive(); + + void cancel(); + + int period(); + + void setPeriod(int period); + + static @Nullable Task cancel(@Nullable Task task) { + if (task != null) task.cancel(); + return null; + } + + static boolean isActive(@Nullable Task task) { + return task != null && task.isActive(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/schedule/TickBatch.java b/src/main/java/com/modularmc/mmclutils/schedule/TickBatch.java new file mode 100644 index 0000000..510c555 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/TickBatch.java @@ -0,0 +1,81 @@ +package com.modularmc.mmclutils.schedule; + +import com.modularmc.mmclutils.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/schedule/TickScheduler.java b/src/main/java/com/modularmc/mmclutils/schedule/TickScheduler.java new file mode 100644 index 0000000..f680865 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/TickScheduler.java @@ -0,0 +1,735 @@ +package com.modularmc.mmclutils.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.jetbrains.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 { + + 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; + } + + 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[] snapshot = Arrays.copyOf(roots, rootCount); + for (Scope root : snapshot) 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/schedule/WaitList.java b/src/main/java/com/modularmc/mmclutils/schedule/WaitList.java new file mode 100644 index 0000000..efc2e36 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/WaitList.java @@ -0,0 +1,129 @@ +package com.modularmc.mmclutils.schedule; + +import org.jetbrains.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; + } + + public static final class Waiter { + + private final T owner; + private @Nullable WaitList list; + private int slot; + private int stamp; + + 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/spatial/BlockEntityIndex.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockEntityIndex.java new file mode 100644 index 0000000..d90be3d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockEntityIndex.java @@ -0,0 +1,121 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LevelSlotHolder; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; + +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * 按类型自动维护的方块实体索引:区块放入、替换、移除方块实体和区块卸载时由 GTOUtils 登记注销,使用方不用在方块实体里写钩子。 + * 必须在模组加载阶段创建(声明成静态常量,并在模组构造时触发所在类初始化),维度开始加载方块实体后再创建会抛异常。功能: + *
    + *
  • {@link #create(Class)}:收录运行时类是该类型子类型的方块实体;{@link #create(Class, Predicate)}:另在登记时判一次条件,只收录通过的
  • + *
  • {@link #all()}:全部方块实体共用的一份索引,供只能逐个判断能力的查找和 {@link ProbedBlockEntityIndex} 的待探测部分使用;第一次调用时创建,同样必须在加载阶段调用
  • + *
  • {@link #query}/{@link #forEach}/{@link #findAny}/{@link #findNearest}:按 {@link BlockRange} 查某维度范围内的方块实体,语义同 + * {@link BlockIndex}
  • + *
  • {@link #findAny(Level, Predicate)}/{@link #forEach(Level, Consumer)}:遍历某维度全部收录的方块实体
  • + *
  • {@link #get}/{@link #size}/{@link #version}:按坐标取、数量、内容变化计数
  • + *
  • 索引存放在维度实例上,随维度回收;只在拥有该维度的线程上查询
  • + *
+ */ +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); + } + + 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((LevelSlotHolder) 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/spatial/BlockEntityTracking.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockEntityTracking.java new file mode 100644 index 0000000..aa81b98 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockEntityTracking.java @@ -0,0 +1,62 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LevelSlotHolder; + +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.jetbrains.annotations.Nullable; + +@ApiStatus.Internal +public final class BlockEntityTracking { + + static final Tracker TRACKER = new Tracker<>(new Tracker.Access<>() { + + @Override + public @Nullable LevelSlotHolder holder(BlockEntity be) { + return be.getLevel() instanceof LevelSlotHolder 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); + } + + 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); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/BlockIndex.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockIndex.java new file mode 100644 index 0000000..3158e19 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockIndex.java @@ -0,0 +1,258 @@ +package com.modularmc.mmclutils.spatial; + +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}
  • + *
  • {@link #version()}:每次登记内容变化加一,使用方据此判断自己缓存的查询结果是否过期
  • + *
  • 不是线程安全的,只在拥有该维度的线程上使用
  • + *
+ */ +public final class BlockIndex { + + public static final int MIN_XZ = -(1 << 25); + public static final int MAX_XZ = (1 << 25) - 1; + public static final int MIN_Y = -2048; + 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; + } + + 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); + } + + 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/spatial/BlockOctree.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockOctree.java new file mode 100644 index 0000000..3b6a700 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockOctree.java @@ -0,0 +1,653 @@ +package com.modularmc.mmclutils.spatial; + +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;不是线程安全的
  • + *
+ */ +@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; + + 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); + } + + 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); + } + + 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/spatial/BlockPositions.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockPositions.java new file mode 100644 index 0000000..05ec3f8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockPositions.java @@ -0,0 +1,130 @@ +package com.modularmc.mmclutils.spatial; + +import net.minecraft.core.BlockPos; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +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 BlockPositions { + + private BlockPositions() {} + + 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 (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 (int i = 0; i < n; i++) { + BlockPos p = pos.apply(list.get(i)); + 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) | (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 (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 (int i = 0, n = list.size(); i < n; i++) { + BlockPos p = pos.apply(list.get(i)); + 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)]); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/BlockRange.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockRange.java new file mode 100644 index 0000000..57ded38 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockRange.java @@ -0,0 +1,126 @@ +package com.modularmc.mmclutils.spatial; + +/** + * 以某个方块为中心的查询范围,供 {@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); + } + + 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 ((long) (r + 1) * (r + 1) <= 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); + } + + public Shape shape() { + return shape; + } + + public int radiusX() { + return rx; + } + + public int radiusY() { + return ry; + } + + public int radiusZ() { + return rz; + } + + 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 ax * ax + ay * ay + az * az <= radiusSq; + } + + @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 + ")"; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/LevelBlockIndex.java b/src/main/java/com/modularmc/mmclutils/spatial/LevelBlockIndex.java new file mode 100644 index 0000000..83c6626 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/LevelBlockIndex.java @@ -0,0 +1,54 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LevelSlotHolder; +import com.modularmc.mmclutils.level.LevelStore; + +import net.minecraft.world.level.Level; + +import org.jetbrains.annotations.Nullable; + +/** + * 由使用方自己登记、注销的按维度索引:每个维度实例各有一份 {@link BlockIndex},存放在 {@link LevelStore} 里,通常声明成静态常量。 + * 成员由条件决定(成型、入网等)时用它;成员只由方块实体类型决定时改用自动维护的 {@link BlockEntityIndex}。功能: + *
    + *
  • {@link #create()}:新建一类索引
  • + *
  • {@link #get}:取该维度的索引,没有就创建;{@link #getIfPresent}:只读,没有时返回 null,不创建
  • + *
  • {@link #release}:丢弃该维度的索引;维度卸载时 GTOUtils 通过 {@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); + } + + BlockIndex forHolder(LevelSlotHolder holder) { + return store.forHolder(holder); + } + + @Nullable + BlockIndex forHolderIfPresent(LevelSlotHolder holder) { + return store.forHolderIfPresent(holder); + } + + void releaseHolder(LevelSlotHolder holder) { + store.releaseHolder(holder); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java b/src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java new file mode 100644 index 0000000..2d8d178 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java @@ -0,0 +1,149 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LoadedChunks; + +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.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.function.Predicate; + +/** + * 把维度的方块状态按区段交给 {@link SectionScan}。功能: + *
    + *
  • 读到的值与逐格调用 {@code Level.getBlockState} 相同,未加载的区块也和它一样按需取:高度范围外与空区块整段是虚空空气,全空气区段整段是空气, + * 其余区段用调色板判断能否跳过,调试世界退回逐格读取
  • + *
  • {@link #betweenClosed}/{@link #inRange}/{@link #withinManhattan}:对某维度直接做 {@link SectionScan} 的三种扫描,betweenClosed + * 的角点顺序随意, + * 同 {@code BlockPos.betweenClosed(a, b)}
  • + *
  • 带 {@link Unloaded} 参数的版本可以选未加载区块的处理:{@link Unloaded#LOAD} 同上按需加载,{@link Unloaded#SKIP} 不触发加载,整段当作虚空空气
  • + *
+ */ +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.LOAD); + } + + 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.LOAD, 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.LOAD, 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); + } + + 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.LOAD, 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.LOAD, 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); + } + + 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.LOAD, 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.LOAD, 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); + } + + 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/spatial/ProbedBlockEntityIndex.java b/src/main/java/com/modularmc/mmclutils/spatial/ProbedBlockEntityIndex.java new file mode 100644 index 0000000..59d0b6d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/ProbedBlockEntityIndex.java @@ -0,0 +1,72 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LevelSlotHolder; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; + +import org.jetbrains.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; + } + + public static ProbedBlockEntityIndex create(Function, Kind> classifier, Predicate probe) { + return create(classifier, probe, null); + } + + 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))); + } + + public int query(Level level, BlockPos center, BlockRange range, @Nullable Predicate filter, Collection out) { + return sink.query((LevelSlotHolder) 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((LevelSlotHolder) 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((LevelSlotHolder) level, center.getX(), center.getY(), center.getZ(), range, filter); + } + + public int candidateCount(Level level) { + return sink.candidateCount((LevelSlotHolder) level); + } + + public int sweptSectionCount(Level level) { + return sink.sweptSectionCount((LevelSlotHolder) level); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/ProbedSink.java b/src/main/java/com/modularmc/mmclutils/spatial/ProbedSink.java new file mode 100644 index 0000000..7d39c62 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/ProbedSink.java @@ -0,0 +1,178 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LevelSlotHolder; +import com.modularmc.mmclutils.level.LevelStore; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; + +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.jetbrains.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(LevelSlotHolder 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(LevelSlotHolder 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(LevelSlotHolder 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(LevelSlotHolder 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(LevelSlotHolder 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(LevelSlotHolder holder) { + State state = store.forHolderIfPresent(holder); + return state == null ? 0 : state.candidates.size(); + } + + int sweptSectionCount(LevelSlotHolder holder) { + State state = store.forHolderIfPresent(holder); + return state == null ? 0 : state.swept.size(); + } + + int freshCount(LevelSlotHolder holder) { + State state = store.forHolderIfPresent(holder); + return state == null ? 0 : state.fresh.size(); + } + + @Nullable + private State prepare(LevelSlotHolder 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/spatial/SectionScan.java b/src/main/java/com/modularmc/mmclutils/spatial/SectionScan.java new file mode 100644 index 0000000..235524c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/SectionScan.java @@ -0,0 +1,372 @@ +package com.modularmc.mmclutils.spatial; + +import net.minecraft.core.BlockPos; + +import org.jetbrains.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 { + + public interface Sections { + + @Nullable + T seek(int sectionX, int sectionY, int sectionZ); + + boolean mayContain(Predicate palette); + + T get(int localX, int localY, int localZ); + } + + public interface CellTest { + + 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/spatial/TrackedBlockEntity.java b/src/main/java/com/modularmc/mmclutils/spatial/TrackedBlockEntity.java new file mode 100644 index 0000000..cbd1380 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/TrackedBlockEntity.java @@ -0,0 +1,11 @@ +package com.modularmc.mmclutils.spatial; + +import org.jetbrains.annotations.ApiStatus; + +@ApiStatus.Internal +public interface TrackedBlockEntity { + + int mmclutils$probedMask(); + + void mmclutils$setProbedMask(int mask); +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/TrackedChunk.java b/src/main/java/com/modularmc/mmclutils/spatial/TrackedChunk.java new file mode 100644 index 0000000..0f081df --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/TrackedChunk.java @@ -0,0 +1,11 @@ +package com.modularmc.mmclutils.spatial; + +import org.jetbrains.annotations.ApiStatus; + +@ApiStatus.Internal +public interface TrackedChunk { + + boolean mmclutils$hidden(); + + void mmclutils$setHidden(boolean hidden); +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/Tracker.java b/src/main/java/com/modularmc/mmclutils/spatial/Tracker.java new file mode 100644 index 0000000..ce28956 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/Tracker.java @@ -0,0 +1,113 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LevelSlotHolder; + +import net.minecraft.core.BlockPos; + +import org.jetbrains.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 + LevelSlotHolder 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(LevelSlotHolder holder, E e, BlockPos pos); + + abstract void removed(LevelSlotHolder 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; + LevelSlotHolder 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; + LevelSlotHolder 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/spatial/TypedSink.java b/src/main/java/com/modularmc/mmclutils/spatial/TypedSink.java new file mode 100644 index 0000000..790f61c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/TypedSink.java @@ -0,0 +1,53 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LevelSlotHolder; + +import net.minecraft.core.BlockPos; + +import org.jetbrains.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 LevelBlockIndex store = LevelBlockIndex.create(); + + TypedSink(Class type, @Nullable Predicate admit) { + this.type = type; + this.admit = admit; + } + + @Override + boolean accepts(Class c) { + return type.isAssignableFrom(c); + } + + @Override + void added(LevelSlotHolder 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(LevelSlotHolder holder, E e, BlockPos pos) { + BlockIndex index = store.forHolderIfPresent(holder); + if (index != null) index.remove(pos, type.cast(e)); + } + + @Nullable + BlockIndex index(LevelSlotHolder holder) { + return store.forHolderIfPresent(holder); + } +} diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index e69de29..87d83b4 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -0,0 +1 @@ +public net.minecraft.client.multiplayer.ClientChunkCache$Storage diff --git a/src/main/resources/mmclutils.mixins.json b/src/main/resources/mmclutils.mixins.json index e2c431d..e6215cc 100644 --- a/src/main/resources/mmclutils.mixins.json +++ b/src/main/resources/mmclutils.mixins.json @@ -4,8 +4,17 @@ "package": "com.modularmc.mmclutils.mixin", "plugin": "com.modularmc.mmclutils.mixin.MMCLibUtilsMixinConfig", "compatibilityLevel": "JAVA_25", - "mixins": [], - "client": [], + "mixins": [ + "level.LevelMixin", + "level.ServerLevelSaveMixin", + "level.ServerChunkCacheMixin", + "spatial.BlockEntityMixin", + "spatial.LevelChunkMixin" + ], + "client": [ + "client.level.ClientChunkCacheMixin", + "client.level.ClientChunkStorageMixin" + ], "injectors": { "defaultRequire": 1 }, diff --git a/src/main/templates/META-INF/neoforge.mods.toml b/src/main/templates/META-INF/neoforge.mods.toml index b128cc3..8711092 100644 --- a/src/main/templates/META-INF/neoforge.mods.toml +++ b/src/main/templates/META-INF/neoforge.mods.toml @@ -18,8 +18,6 @@ enumExtensions = "META-INF/enum_extensions.json" [[mixins]] config = "${mod_id}.mixins.json" -[[mixins]] - config = "${mod_id}.mixins.json" [[accessTransformers]] file = "META-INF/accesstransformer.cfg" From ff7f97835e3ab75a3ebf15a137c6715abd188cf0 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 00:46:33 +0800 Subject: [PATCH 04/79] UpData --- build.gradle | 14 ++++++++++++++ gradle/scripts/jars.gradle | 1 + 2 files changed, 15 insertions(+) diff --git a/build.gradle b/build.gradle index e1cb842..d06d878 100644 --- a/build.gradle +++ b/build.gradle @@ -27,20 +27,34 @@ sourceSets { srcDir 'src/generated/resources' } + client { + compileClasspath += main.output + runtimeClasspath += main.output + main.runtimeClasspath + } + extra { compileClasspath += main.output runtimeClasspath += main.output + main.runtimeClasspath } + + clientExtra { + compileClasspath += client.output + extra.compileClasspath + runtimeClasspath += client.output + client.runtimeClasspath + extra.runtimeClasspath + } } configurations { // set these as unresolvable so we don't accidentally force all dependents to use them with us + clientRuntimeOnly.canBeResolved = false extraRuntimeOnly.canBeResolved = false + clientExtraRuntimeOnly.canBeResolved = false testImplementation.canBeResolved = false testRuntimeOnly.canBeResolved = false runtimeClasspath.extendsFrom localRuntime extraRuntimeClasspath.extendsFrom extraLocalRuntime + clientRuntimeClasspath.extendsFrom clientLocalRuntime + extraClientRuntimeClasspath.extendsFrom clientExtraLocalRuntime renderNurseCfg { canBeConsumed = false diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index cd13acd..a9d8b40 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -28,6 +28,7 @@ afterEvaluate { tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { destinationDirectory = file('build/libs/') manifest.attributes([ + 'MixinConfigs': "mmclutils.mixins.json", 'Specification-Title': project.name, 'Specification-Version': mod_version, 'Specification-Vendor': 'ModularMCLib Team', From a188112d8dfad1960299b0bde9225458b31d022a Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 01:21:07 +0800 Subject: [PATCH 05/79] =?UTF-8?q?=E5=A3=B0=E6=98=8E=E9=9B=86=E5=90=88?= =?UTF-8?q?=E4=BE=9D=E8=B5=96=E4=B8=8E=E7=BB=9F=E4=B8=80=20Mixin=20?= =?UTF-8?q?=E5=85=83=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dependencies.gradle | 3 +++ gradle/libs.versions.toml | 4 +++- gradle/scripts/jars.gradle | 1 - 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 84f58d9..662eb14 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -2,6 +2,9 @@ dependencies { compileOnly(libs.jetbrains.annotations) compileOnly(libs.jspecify) + // 与 Minecraft 共用运行库,供使用原始类型集合的公共接口声明依赖。 + api(libs.fastutil) + jarJar(api(libs.kotlin.stdlib.get())) { exclude group: 'org.jetbrains', module: 'annotations' } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1df33c1..95277ed 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -9,6 +9,7 @@ modDevGradle = "2.0.148" kotlin = "2.4.21" jetbrains-annotations = "26.1.0" jspecify = "1.0.0" +fastutil = "8.5.18" renderNurse = "0.0.26" mixin = "0.8.7" @@ -21,6 +22,7 @@ renderNurse = { module = "net.neoforged:render-nurse", version.ref = 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" } @@ -28,4 +30,4 @@ shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } 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" } \ No newline at end of file +kotlin-lombok = { id = "org.jetbrains.kotlin.plugin.lombok", version.ref = "kotlin" } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index a9d8b40..cd13acd 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -28,7 +28,6 @@ afterEvaluate { tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { destinationDirectory = file('build/libs/') manifest.attributes([ - 'MixinConfigs': "mmclutils.mixins.json", 'Specification-Title': project.name, 'Specification-Version': mod_version, 'Specification-Vendor': 'ModularMCLib Team', From a675cf9bc35bbb74148f834cbf01ee7420750e96 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 01:21:25 +0800 Subject: [PATCH 06/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E6=95=88=E6=9E=9C=E5=92=8C=E5=8F=8C=E7=AB=AF=E5=85=A5?= =?UTF-8?q?=E5=8F=A3=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/ModularMCLibUtils.java | 52 +++ .../client/ModularMCLibUtilsClient.java | 36 +- .../client/render/effect/BeamEffects.java | 96 ++++ .../client/render/effect/BeamStyle.java | 7 + .../client/render/effect/BurstEffects.java | 35 ++ .../client/render/effect/BurstStyle.java | 7 + .../client/render/effect/EffectClock.java | 61 +++ .../client/render/effect/EffectPalette.java | 65 +++ .../render/effect/EffectQuadBuffer.java | 93 ++++ .../render/effect/EffectRenderPipelines.java | 98 ++++ .../client/render/effect/EffectRenderer.java | 231 ++++++++++ .../client/render/effect/EffectSource.java | 14 + .../client/render/effect/EffectVertices.java | 55 +++ .../client/render/effect/FlowStyle.java | 7 + .../render/effect/GpuParticleRenderer.java | 424 ++++++++++++++++++ .../client/render/effect/MoteLook.java | 31 ++ .../client/render/effect/MoteSprite.java | 67 +++ .../client/render/effect/ParticleEffects.java | 36 ++ .../render/effect/ParticleEmitters.java | 88 ++++ .../render/effect/ParticleGeometry.java | 140 ++++++ .../client/render/effect/ParticleRing.java | 137 ++++++ .../effect/PlayerAttachmentRenderer.java | 192 ++++++++ .../client/render/effect/PulseStyle.java | 9 + .../client/render/effect/RingGeometry.java | 63 +++ .../client/render/effect/RingRenderer.java | 325 ++++++++++++++ .../client/render/effect/RingShape.java | 14 + .../client/render/effect/RingStyle.java | 7 + .../client/render/effect/SphereHighlight.java | 75 ++++ .../effect/TransformFeedbackProgram.java | 76 ++++ .../render/geometry/MeshPrimitives.java | 82 ++++ .../client/render/geometry/SpriteQuads.java | 114 +++++ ...erEvents.java => ClientTickScheduler.java} | 4 +- .../mixin/client/render/GlBufferAccessor.java | 13 + .../assets/mmclutils/shaders/effect/mote.vsh | 150 +++++++ .../mmclutils/shaders/effect/ring_common.glsl | 70 +++ .../mmclutils/shaders/effect/ring_glow.vsh | 20 + .../mmclutils/shaders/effect/ring_ribbon.vsh | 52 +++ .../mmclutils/shaders/effect/ring_voxel.vsh | 35 ++ src/main/resources/mmclutils.mixins.json | 3 +- 39 files changed, 3080 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/BeamEffects.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/BeamStyle.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/BurstEffects.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/BurstStyle.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/EffectClock.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/EffectPalette.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/EffectQuadBuffer.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/EffectSource.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/EffectVertices.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/FlowStyle.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/MoteLook.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/MoteSprite.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEffects.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleGeometry.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleRing.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/PulseStyle.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/RingShape.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/RingStyle.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/SphereHighlight.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/geometry/MeshPrimitives.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/geometry/SpriteQuads.java rename src/main/java/com/modularmc/mmclutils/client/schedule/{ClientSchedulerEvents.java => ClientTickScheduler.java} (91%) create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/client/render/GlBufferAccessor.java create mode 100644 src/main/resources/assets/mmclutils/shaders/effect/mote.vsh create mode 100644 src/main/resources/assets/mmclutils/shaders/effect/ring_common.glsl create mode 100644 src/main/resources/assets/mmclutils/shaders/effect/ring_glow.vsh create mode 100644 src/main/resources/assets/mmclutils/shaders/effect/ring_ribbon.vsh create mode 100644 src/main/resources/assets/mmclutils/shaders/effect/ring_voxel.vsh diff --git a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java index 3f7163b..4e15f12 100644 --- a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java +++ b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java @@ -1,11 +1,23 @@ package com.modularmc.mmclutils; +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 { @@ -19,4 +31,44 @@ public ModularMCLibUtils(IEventBus bus) {} public static Identifier id(String path) { return Identifier.fromNamespaceAndPath(MOD_ID, path); } + + /** 返回当前专用服或本地集成服。服务器尚未启动或已停止时返回空值。 */ + public static @Nullable MinecraftServer getMinecraftServer() { + return ServerLifecycleHooks.getCurrentServer(); + } + + /** 在传入服务器的主线程上执行命令,抑制命令反馈。 */ + public static void runCommandSilently(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(); + } + + 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/client/ModularMCLibUtilsClient.java b/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java index be8fca5..3d363e8 100644 --- a/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java +++ b/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java @@ -1,14 +1,48 @@ package com.modularmc.mmclutils.client; import com.modularmc.mmclutils.ModularMCLibUtils; +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 { - public ModularMCLibUtilsClient(IEventBus modBus) {} + public ModularMCLibUtilsClient(IEventBus modBus) { + EffectRenderer.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; + } + + 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/render/effect/BeamEffects.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamEffects.java new file mode 100644 index 0000000..9212e3e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamEffects.java @@ -0,0 +1,96 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.util.Mth; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import java.util.SplittableRandom; + +@OnlyIn(Dist.CLIENT) +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; + } + + 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); + } + + 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); + } + + 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); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamStyle.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamStyle.java new file mode 100644 index 0000000..42e9003 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/BeamStyle.java @@ -0,0 +1,7 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +public record BeamStyle(float spacing, float spacingJitter, int life, float size, float alpha, boolean rainbow) {} 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..06d003d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/BurstEffects.java @@ -0,0 +1,35 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.util.Mth; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import java.util.SplittableRandom; + +@OnlyIn(Dist.CLIENT) +public final class BurstEffects { + + private static final SplittableRandom RANDOM = new SplittableRandom(0x5DEECE66DL); + + private BurstEffects() {} + + 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); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/BurstStyle.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/BurstStyle.java new file mode 100644 index 0000000..2f41312 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/BurstStyle.java @@ -0,0 +1,7 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +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..d4c0ded --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectClock.java @@ -0,0 +1,61 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import java.util.Map; +import java.util.WeakHashMap; + +@OnlyIn(Dist.CLIENT) +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; + } + + 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; + } + + 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; + } + + public float intensity() { + return intensity; + } + + public double time() { + return time; + } + + 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..99f7177 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectPalette.java @@ -0,0 +1,65 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.util.Mth; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; + +import java.util.SplittableRandom; + +@OnlyIn(Dist.CLIENT) +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() {} + + 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..844480b --- /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.client.render.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..d510018 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderPipelines.java @@ -0,0 +1,98 @@ +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"); + 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; + } +} 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..c5ebb1f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectRenderer.java @@ -0,0 +1,231 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +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; + +/** 每帧收集环和线流命令,在世界渲染阶段批量提交。 */ +@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 boolean collecting; + 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; + } + + public static boolean collecting(Level level) { + return collecting && level == lastLevel; + } + + static boolean open() { + return collecting; + } + + public static void addSource(EffectSource source) { + if (!SOURCES.contains(source)) SOURCES.add(source); + } + + public static void removeSource(EffectSource source) { + SOURCES.remove(source); + } + + public static double now() { + Minecraft client = Minecraft.getInstance(); + return client.level == null ? Double.NaN : clientTicks + client.getDeltaTracker().getGameTimeDeltaPartialTick(false); + } + + 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))); + } + + 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); + } + + 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 (!collecting) 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(); + GpuParticleRenderer.beginFrame(); + event.getRenderState().setRenderData(FRAME, ++frame); + Vec3 eye = camera.position(); + collecting = true; + try { + for (int index = 0; index < SOURCES.size(); index++) { + SOURCES.get(index).collect(event.getLevel(), frameTime, eye.x, eye.y, eye.z); + } + } finally { + collecting = false; + } + } + + 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(); + 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(); + SphereHighlight.release(); + } + + @SubscribeEvent + private static void clearOnDisconnect(ClientPlayerNetworkEvent.LoggingOut event) { + clearWorldEffects(); + lastLevel = null; + } + + @SubscribeEvent + private static void releaseOnShutdown(GameShuttingDownEvent event) { + clearWorldEffects(); + releaseRenderBuffers(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectSource.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectSource.java new file mode 100644 index 0000000..465091d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectSource.java @@ -0,0 +1,14 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.multiplayer.ClientLevel; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +/** 在世界渲染状态提取时提交效果,回调在客户端渲染线程执行。 */ +@OnlyIn(Dist.CLIENT) +@FunctionalInterface +public interface EffectSource { + + /** 使用当前世界、动画时间和相机坐标生成本帧指令。回调返回后本帧收集结束。 */ + 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..5e55174 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/EffectVertices.java @@ -0,0 +1,55 @@ +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.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) { + bytes.putFloat(x).putFloat(y).putFloat(z); + bytes.putFloat((rgb >> 16 & 255) / 255f).putFloat((rgb >> 8 & 255) / 255f).putFloat((rgb & 255) / 255f) + .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/FlowStyle.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/FlowStyle.java new file mode 100644 index 0000000..7aacb48 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/FlowStyle.java @@ -0,0 +1,7 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +public record FlowStyle(int period, int travel, float size, float sizeJitter, float jitter, float alpha) {} 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..87b4911 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/GpuParticleRenderer.java @@ -0,0 +1,424 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +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; + +/** + * 光点产生时写入槽位池。每帧通过变换反馈批量展开为朝向相机的四边形,再用原版管线绘制。 + */ +@OnlyIn(Dist.CLIENT) +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 = 64; + 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 = RingRenderer.available(); + 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/MoteLook.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/MoteLook.java new file mode 100644 index 0000000..09a6912 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/MoteLook.java @@ -0,0 +1,31 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import org.jspecify.annotations.Nullable; + +/** + * 光点样式可选择带亮芯的像素光晕,或由调用方提供的粒子精灵。 + */ +@OnlyIn(Dist.CLIENT) +public record MoteLook(@Nullable MoteSprite sprite, boolean animated, float rollSpeed, float core) { + + 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); + } + + 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/MoteSprite.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/MoteSprite.java new file mode 100644 index 0000000..f3cfa8e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/MoteSprite.java @@ -0,0 +1,67 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.particle.SpriteSet; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import java.util.ArrayList; + +/** + * 从粒子图集读取并缓存各帧的 UV,资源重载后重新解析。 + */ +@OnlyIn(Dist.CLIENT) +public final class MoteSprite { + + 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; + } + + public static MoteSprite of(SpriteSet set) { + return new MoteSprite(set); + } + + private void resolve() { + if (seen == generation) return; + seen = generation; + tableRow = -1; + var list = new ArrayList(); + TextureAtlasSprite last = null; + for (int i = 0; i <= 64; i++) { + TextureAtlasSprite s; + try { + s = set.get(i, 64); + } catch (RuntimeException e) { + break; + } + if (s != null && s != last && !list.contains(s)) list.add(s); + last = 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(); + } + } + + 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..8c44a83 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEffects.java @@ -0,0 +1,36 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +/** + * 在客户端提交带阻力和重力的光点,或提交向指定位置移动的光点。 + * 粒子工厂可以传入自己的精灵,由批量管线统一计算和绘制。 + */ +@OnlyIn(Dist.CLIENT) +public final class ParticleEffects { + + public static final int SHRINK = GpuParticleRenderer.SHRINK, PULSE = GpuParticleRenderer.PULSE_SIZE, CONSTANT = GpuParticleRenderer.CONSTANT; + public static final int FADE = 1, THROUGH_WALLS = 2; + public static final double SPAWN_DISTANCE = 64; + + private ParticleEffects() {} + + 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); + } + + 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); + } +} 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..92e4194 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleEmitters.java @@ -0,0 +1,88 @@ +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 net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import java.util.ArrayList; + +/** + * 使用原版粒子工厂发射一次性高斯爆散,或在客户端 Tick 中持续发射粒子。 + */ +@OnlyIn(Dist.CLIENT) +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 ArrayList ACTIVE = new ArrayList<>(); + private static final ArrayList POOL = new ArrayList<>(); + + private ParticleEmitters() {} + + 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); + } + + 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..ff6c867 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/ParticleRing.java @@ -0,0 +1,137 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; +import java.util.SplittableRandom; + +@OnlyIn(Dist.CLIENT) +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; + private int dataTexture = -1; + + public ParticleRing(float majorRadius, float tubeRadius, int count, float minSpeed, float maxSpeed, long seed) { + 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; + } + + double phase(int index, double time) { + return phase[index] + orbit[index] * time; + } + + 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 dataTexture() { + return dataTexture; + } + + void dataTexture(int id) { + dataTexture = id; + } + + int dataRows() { + return (count * 4 + DATA_WIDTH - 1) / DATA_WIDTH; + } + + ByteBuffer createData() { + var data = MemoryUtil.memCalloc(dataRows() * DATA_WIDTH * 16); + 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; + } +} 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..9caa4ce --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/PlayerAttachmentRenderer.java @@ -0,0 +1,192 @@ +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.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 org.joml.Matrix4f; +import org.joml.Vector4f; + +/** 复用玩家模型的实际姿态,延后绘制像素附着层。 */ +public final class PlayerAttachmentRenderer { + + private static final ObjectArrayList LISTENERS = new ObjectArrayList<>(); + private static final ObjectArrayList PENDING = new ObjectArrayList<>(); + private static int count; + private static boolean active; + + private PlayerAttachmentRenderer() {} + + public static void add(Attachment attachment) { + if (!LISTENERS.contains(attachment)) LISTENERS.add(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() { + clearFrame(); + active = true; + } + + static void clearFrame() { + for (int i = 0; i < count; i++) PENDING.get(i).sheet = null; + count = 0; + active = false; + } + + 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(); + } + } + + public static void draw(PixelSheet sheet, PoseStack poses, float red, float green, float blue) { + if (!active) 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); + } + + /** + * 在渲染线程上采集玩家附着效果,复用已完成动画的模型姿态。 + * 可以暂时变换 PoseStack 来定位身体部件,返回前须恢复原有姿态。 + */ + @FunctionalInterface + public interface Attachment { + + 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 (!active) 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); + } + + /** 不可变的本地像素面,可对多个实体复用。绘制资源须在客户端渲染线程释放。 */ + public static final class PixelSheet implements AutoCloseable { + + private final float[] pixels; + private final float scale; + 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 scale, float halo, float core) { + this.pixels = pixels; + this.scale = scale; + this.halo = halo; + this.core = core; + } + + public static Builder builder(float scale, float halo, float core) { + return new Builder(scale, halo, core); + } + + public int count() { + return pixels.length / 4; + } + + private void draw(Matrix4f transform, Vector4f tint) { + if (!uploaded) { + upload(glow, halo); + upload(center, core); + uploaded = true; + } + Matrix4f matrix = new Matrix4f(EffectRenderer.modelView()).mul(transform); + glow.draw(EffectRenderPipelines.GLOW, EffectRenderPipelines.GLOW_TEXTURE, matrix, tint); + center.draw(EffectRenderPipelines.GLOW, EffectRenderPipelines.WHITE_TEXTURE, matrix, tint); + } + + private void upload(EffectQuadBuffer output, float radius) { + var vertices = new EffectVertices(); + vertices.begin(count()); + try { + for (int i = 0; i < pixels.length; i += 4) { + float x = pixels[i] * scale, y = pixels[i + 1] * scale; + int color = Float.floatToRawIntBits(pixels[i + 2]); + float alpha = pixels[i + 3], size = radius * scale * .5f; + vertices.writeVertex(x - size, y - size, 0, color, alpha, 0, 0); + vertices.writeVertex(x - size, y + size, 0, color, alpha, 0, 1); + vertices.writeVertex(x + size, y + size, 0, color, alpha, 1, 1); + vertices.writeVertex(x + size, y - size, 0, color, alpha, 1, 0); + } + vertices.upload(output); + } finally { + vertices.release(); + } + } + + @Override + public void close() { + glow.close(); + center.close(); + uploaded = false; + } + + public static final class Builder { + + private final FloatArrayList pixels = new FloatArrayList(); + private final float scale; + private final float halo; + private final float core; + + private Builder(float scale, float halo, float core) { + this.scale = scale; + this.halo = halo; + this.core = core; + } + + 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(), scale, halo, core); + } + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/effect/PulseStyle.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/PulseStyle.java new file mode 100644 index 0000000..3c2806f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/PulseStyle.java @@ -0,0 +1,9 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import org.jspecify.annotations.Nullable; + +@OnlyIn(Dist.CLIENT) +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/RingGeometry.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java new file mode 100644 index 0000000..0ad7195 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingGeometry.java @@ -0,0 +1,63 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.minecraft.client.Camera; +import net.minecraft.core.Direction; + +import org.joml.Vector3f; + +import java.util.List; + +/** 按环的数据和样式生成无变换反馈时使用的顶点。 */ +final class RingGeometry { + + private static final Vector3f LEFT = new Vector3f(); + private static final Vector3f UP = new Vector3f(); + private static final EffectVertices VERTICES = new EffectVertices(); + + private RingGeometry() {} + + static void draw(List commands, int count, Camera camera, EffectQuadBuffer output) { + LEFT.set(-1, 0, 0).rotate(camera.rotation()); + UP.set(0, 1, 0).rotate(camera.rotation()); + for (int i = 0; i < count; i++) { + var command = commands.get(i); + VERTICES.begin(command.ring.count()); + for (int p = 0; p < command.ring.count(); p++) { + double phase = command.ring.phase(p, command.time); + double angle = phase; + float height = command.ring.vertical(p, command.time); + var shape = command.shape; + if (shape.strands() > 0) { + double fraction = phase / (2 * Math.PI) - Math.floor(phase / (2 * Math.PI)); + angle = 2 * Math.PI * (fraction * shape.turns() + (p % shape.strands()) / (double) shape.strands()); + height += (float) ((fraction - .5) * shape.height()); + } + float radius = command.ring.radial(p, command.time); + float x = (float) (Math.cos(angle) * radius); + float z = (float) (Math.sin(angle) * radius); + float y = height; + Direction.Axis axis = command.axis; + if (axis == Direction.Axis.X) { + float previous = x; + x = y; + y = -previous; + } else if (axis == Direction.Axis.Z) { + float previous = z; + z = y; + y = -previous; + } + int rgb = command.palette[command.ring.tone(p)]; + float alpha = Math.min(1f, command.spriteStrength / 255f); + VERTICES.facing(command.x + x, command.y + y, command.z + z, LEFT, UP, command.spriteSize, 0, + (rgb >> 16 & 255) / 255f * alpha, (rgb >> 8 & 255) / 255f * alpha, (rgb & 255) / 255f * alpha, + alpha, 0, 0, 1, 1); + } + VERTICES.upload(output); + output.draw(EffectRenderPipelines.GLOW, EffectRenderPipelines.GLOW_TEXTURE); + } + } + + static void release() { + VERTICES.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..29f2b0e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingRenderer.java @@ -0,0 +1,325 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.client.Camera; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.opengl.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; +import org.joml.Vector3f; +import org.lwjgl.opengl.GL; +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.List; + +@OnlyIn(Dist.CLIENT) +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 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[][] 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) { + if (!RenderSystem.getDevice().getBackendName().equalsIgnoreCase("OpenGL")) { + state = 0; + return false; + } + var caps = GL.getCapabilities(); + boolean supported = caps.OpenGL33 || caps.GL_ARB_instanced_arrays; + 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 void ensureData(ParticleRing ring) { + if (ring.dataTexture() != -1) return; + var data = ring.createData(); + ring.dataTexture(texture(GL30.GL_RGBA32F, ParticleRing.DATA_WIDTH, ring.dataRows(), GL11.GL_FLOAT, data)); + 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; + ensureData(GROUP_RING[g]); + } + 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]; + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(ring.dataTexture()); + 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]; + GlStateManager._activeTexture(GL13.GL_TEXTURE0); + GlStateManager._bindTexture(ring.dataTexture()); + 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, 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); + 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/RingShape.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingShape.java new file mode 100644 index 0000000..a47fd21 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingShape.java @@ -0,0 +1,14 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +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 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/RingStyle.java b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingStyle.java new file mode 100644 index 0000000..4071e59 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/RingStyle.java @@ -0,0 +1,7 @@ +package com.modularmc.mmclutils.client.render.effect; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +public record RingStyle(float spriteScale, int spriteStrength, float hazeWidth, int hazeStrength, float coreWidth, int coreStrength) {} 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..23c3530 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/SphereHighlight.java @@ -0,0 +1,75 @@ +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 { + + 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..2e87179 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/effect/TransformFeedbackProgram.java @@ -0,0 +1,76 @@ +package com.modularmc.mmclutils.client.render.effect; + +import com.modularmc.mmclutils.ModularMCLibUtils; + +import net.minecraft.client.Minecraft; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import org.jspecify.annotations.Nullable; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +@OnlyIn(Dist.CLIENT) +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); + } + + 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("ModularMCLibUtils program {} failed to link: {}", vertex, GL20.glGetProgramInfoLog(program, 32768)); + GL20.glDeleteProgram(program); + return null; + } + return new TransformFeedbackProgram(program); + } catch (IOException e) { + ModularMCLibUtils.LOGGER.error("ModularMCLibUtils program {} failed to load", 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("ModularMCLibUtils shader {} failed to compile: {}", 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/SpriteQuads.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SpriteQuads.java new file mode 100644 index 0000000..877879e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SpriteQuads.java @@ -0,0 +1,114 @@ +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 net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import org.joml.Matrix4f; + +/** + * 按每格十六像素生成轴对齐的纹理面,使流体或面板可以跨方块连续平铺。 + * 顶点包含位置、颜色、UV、覆盖层、亮度和法线。 + */ +@OnlyIn(Dist.CLIENT) +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() {} + + public static int bit(Direction face) { + return 1 << face.get3DDataValue(); + } + + 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); + } + } + + 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/schedule/ClientSchedulerEvents.java b/src/main/java/com/modularmc/mmclutils/client/schedule/ClientTickScheduler.java similarity index 91% rename from src/main/java/com/modularmc/mmclutils/client/schedule/ClientSchedulerEvents.java rename to src/main/java/com/modularmc/mmclutils/client/schedule/ClientTickScheduler.java index 89aff72..1114a49 100644 --- a/src/main/java/com/modularmc/mmclutils/client/schedule/ClientSchedulerEvents.java +++ b/src/main/java/com/modularmc/mmclutils/client/schedule/ClientTickScheduler.java @@ -13,9 +13,9 @@ @ApiStatus.Internal @EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID, value = Dist.CLIENT) -public final class ClientSchedulerEvents { +public final class ClientTickScheduler { - private ClientSchedulerEvents() {} + private ClientTickScheduler() {} @SubscribeEvent private static void onTick(ClientTickEvent.Post event) { diff --git a/src/main/java/com/modularmc/mmclutils/mixin/client/render/GlBufferAccessor.java b/src/main/java/com/modularmc/mmclutils/mixin/client/render/GlBufferAccessor.java new file mode 100644 index 0000000..4a3df40 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/client/render/GlBufferAccessor.java @@ -0,0 +1,13 @@ +package com.modularmc.mmclutils.mixin.client.render; + +import com.mojang.blaze3d.opengl.GlBuffer; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(GlBuffer.class) +public interface GlBufferAccessor { + + @Accessor("handle") + int mmclutils$handle(); +} diff --git a/src/main/resources/assets/mmclutils/shaders/effect/mote.vsh b/src/main/resources/assets/mmclutils/shaders/effect/mote.vsh new file mode 100644 index 0000000..f1618eb --- /dev/null +++ b/src/main/resources/assets/mmclutils/shaders/effect/mote.vsh @@ -0,0 +1,150 @@ +#version 150 + +uniform float Now; +uniform vec3 CamHi; +uniform vec3 CamLo; +uniform vec3 CameraLeft; +uniform vec3 CameraUp; +uniform float CullDistance; +uniform int CorePass; +uniform int Premultiply; +uniform sampler2D SpriteFrames; + +in vec4 Ring0; +in vec4 Ring1; +in vec4 Ring2; +in vec4 Ring3; +in vec4 Ring4; +in vec4 Ring5; +in vec4 Ring6; +in vec4 Ring7; + +out vec3 tfPosition; +out vec4 tfColor; +out vec2 tfUV; + +const vec2 CORNERS[4] = vec2[](vec2(1.0, -1.0), vec2(-1.0, -1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0)); +const int BALLISTIC = 0; +const int SLIDE = 1; +const int PULSE = 2; +const int BURST = 3; +const int FLOW = 4; +const int FADE = 1; +const int ANIMATED = 4; + +float hash(float n) { + return fract(sin(n) * 43758.5453123); +} + +float edge(float f, float e) { + return f < e ? f / e : (f > 1.0 - e ? (1.0 - f) / e : 1.0); +} + +void hide() { + tfPosition = vec3(0.0, -100000.0, 0.0); + tfColor = vec4(0.0); + tfUV = vec2(0.0); +} + +float pulseDistance(float t, float speed, float lag) { + return speed * (t - lag * (1.0 - exp(-t / lag))); +} + +void main() { + int motion = int(Ring2.w + 0.5); + int flags = int(Ring6.y + 0.5); + vec3 origin = (Ring1.xyz - CamHi) + (Ring0.xyz - CamLo); + float age = Now - Ring0.w; + float life = max(Ring1.w, 0.0001); + float f = age / life; + float alpha = Ring3.w; + float sizeMul = 1.0; + vec3 p = origin; + if (motion == FLOW) { + float period = max(Ring7.x, 1.0); + float travel = max(Ring7.y, 1.0); + float slot = floor((Now + Ring7.z) / period) - Ring7.w; + float emitted = slot * period - Ring7.z; + f = (Now - emitted) / travel; + if (f < 0.0 || f >= 1.0) { + hide(); + return; + } + float s = Ring6.z * 131.0 + slot * 0.6180339; + vec3 j0 = vec3(hash(s + 1.0), hash(s + 2.0), hash(s + 3.0)) - 0.5; + vec3 j1 = vec3(hash(s + 4.0), hash(s + 5.0), hash(s + 6.0)) - 0.5; + p = mix(origin + j0 * Ring3.y, origin + Ring2.xyz + j1 * Ring3.y, f); + sizeMul = 1.0 + Ring3.x * hash(s + 7.0); + alpha *= edge(f, 0.18); + f = 0.5; + } else { + if (age < 0.0 || f >= 1.0) { + hide(); + return; + } + if (motion == SLIDE) { + p = origin + Ring2.xyz * f; + } else if (motion == PULSE) { + float delay = Ring7.x; + float duration = Ring7.w; + float t = age - delay; + if (t < 0.0 || t > duration) { + hide(); + return; + } + float len = Ring7.z; + float d = len > 0.0001 ? min(len, pulseDistance(t, Ring3.x, max(Ring3.y, 0.01))) / len : 0.0; + p = origin + Ring2.xyz * d; + sizeMul = Ring7.y; + } else if (motion == BURST) { + float ease = 1.0 - (1.0 - f) * (1.0 - f); + p = origin + Ring2.xyz * ease + vec3(0.0, Ring3.y * age, 0.0); + alpha *= min(1.0, age / 1.5); + } else { + float d = Ring3.x; + float move, fall; + if (abs(1.0 - d) < 0.000001) { + move = age; + fall = age * (age + 1.0) * 0.5; + } else { + float dn = pow(d, age); + move = (1.0 - dn) / (1.0 - d); + fall = (age - d * move) / (1.0 - d); + } + p = origin + Ring2.xyz * move - vec3(0.0, Ring3.y * fall, 0.0); + } + if ((flags & FADE) != 0) alpha *= 1.0 - f; + } + if (dot(p, p) > CullDistance * CullDistance || alpha <= 0.004) { + hide(); + return; + } + int curve = int(Ring6.x + 0.5); + float scale = curve == 0 ? 1.0 - f : (curve == 1 ? (f < 0.5 ? f * 2.0 : 2.0 - f * 2.0) : 1.0); + float size = Ring3.z * sizeMul * scale; + vec3 rgb = Ring4.rgb; + if (CorePass != 0) { + if (Ring4.a <= 0.0) { + hide(); + return; + } + size *= Ring4.a; + rgb = mix(rgb, vec3(1.0), 0.55); + } + vec2 corner = CORNERS[gl_VertexID]; + float angle = motion == FLOW ? 0.0 : Ring6.z + Ring6.w * age; + if (angle != 0.0) { + float c = cos(angle), sn = sin(angle); + corner = vec2(corner.x * c - corner.y * sn, corner.x * sn + corner.y * c); + } + tfPosition = p + (CameraLeft * corner.x + CameraUp * corner.y) * size * 0.5; + tfColor = Premultiply != 0 ? vec4(rgb * alpha, alpha) : vec4(rgb, alpha); + vec4 rect = Ring5; + if ((flags & ANIMATED) != 0) { + float frames = max(Ring5.y, 1.0); + float index = min(frames - 1.0, floor(age * (frames - 1.0) / life)); + rect = texelFetch(SpriteFrames, ivec2(int(index), int(Ring5.x)), 0); + } + vec2 base = CORNERS[gl_VertexID]; + tfUV = vec2(base.x > 0.0 ? rect.x : rect.z, base.y > 0.0 ? rect.y : rect.w); +} diff --git a/src/main/resources/assets/mmclutils/shaders/effect/ring_common.glsl b/src/main/resources/assets/mmclutils/shaders/effect/ring_common.glsl new file mode 100644 index 0000000..2c1b8f9 --- /dev/null +++ b/src/main/resources/assets/mmclutils/shaders/effect/ring_common.glsl @@ -0,0 +1,70 @@ +uniform sampler2D ParticleData; +uniform sampler2D PaletteAtlas; +uniform int ParticleCount; + +in vec4 Ring0; +in vec4 Ring1; +in vec4 Ring2; +in vec4 Ring3; +in vec4 Ring4; +in vec4 Ring5; +in vec4 Ring6; + +out vec3 tfPosition; +out vec4 tfColor; +out vec2 tfUV; + +vec4 particle(int index, int part) { + int texel = index * 4 + part; + return texelFetch(ParticleData, ivec2(texel % 1024, texel / 1024), 0); +} + +mat3 ringBasis(float axis) { + if (axis < 0.5) return mat3(0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); + if (axis < 1.5) return mat3(1.0); + return mat3(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0); +} + +const float TAU = 6.28318530718; + +float pathScale = 1.0; + +float helixLength() { + float around = Ring5.z * TAU * Ring2.y; + return sqrt(around * around + Ring5.y * Ring5.y); +} + +float helixFade(float along) { + return smoothstep(0.0, max(Ring6.x, 0.0001), along) * smoothstep(0.0, max(Ring6.y, 0.0001), 1.0 - along); +} + +float helixAlong(float sweep) { + float taper = Ring5.w; + if (taper < 0.0001) return sweep; + float lead = 1.0 + taper; + return (lead - sqrt(max(lead * lead - 4.0 * taper * sweep, 0.0))) / (2.0 * taper); +} + +vec3 helixPoint(float strand, float sweep, float radial, float lift) { + float theta = TAU * (strand / Ring5.x + Ring5.z * sweep); + return Ring0.xyz + ringBasis(Ring2.x) * vec3(cos(theta) * radial, helixAlong(sweep) * Ring5.y + lift, sin(theta) * radial); +} + +vec3 ringPoint(vec4 motion, vec4 drift) { + float time = Ring0.w; + float radial = Ring2.y + drift.z * sin(motion.z * time + drift.x); + float lift = drift.w * sin(motion.w * time + drift.y); + if (Ring5.x < 0.5) { + float theta = motion.x + motion.y * time; + return Ring0.xyz + ringBasis(Ring2.x) * vec3(cos(theta) * radial, lift, sin(theta) * radial); + } + float slot = motion.x / TAU * Ring5.x; + float strand = floor(slot); + float sweep = fract(slot - strand + motion.y * Ring2.y / helixLength() * time); + pathScale = helixFade(helixAlong(sweep)); + return helixPoint(strand, sweep, radial, lift); +} + +vec3 paletteColor(float tone) { + return texelFetch(PaletteAtlas, ivec2(int(tone + 0.5), int(Ring1.w + 0.5)), 0).rgb; +} diff --git a/src/main/resources/assets/mmclutils/shaders/effect/ring_glow.vsh b/src/main/resources/assets/mmclutils/shaders/effect/ring_glow.vsh new file mode 100644 index 0000000..4824804 --- /dev/null +++ b/src/main/resources/assets/mmclutils/shaders/effect/ring_glow.vsh @@ -0,0 +1,20 @@ +#version 150 + +//COMMON + +uniform vec3 CameraLeft; +uniform vec3 CameraUp; + +const vec2 CORNERS[4] = vec2[](vec2(1.0, -1.0), vec2(-1.0, -1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0)); + +void main() { + int index = gl_InstanceID % ParticleCount; + vec4 motion = particle(index, 0); + vec4 drift = particle(index, 1); + vec4 spin = particle(index, 2); + vec2 corner = CORNERS[gl_VertexID]; + vec3 center = ringPoint(motion, drift); + tfPosition = center + (CameraLeft * corner.x + CameraUp * corner.y) * Ring1.y * pathScale; + tfColor = vec4(paletteColor(spin.z) * Ring1.z * pathScale, 1.0); + tfUV = vec2(corner.x > 0.0 ? 0.0 : 1.0, corner.y > 0.0 ? 0.0 : 1.0); +} diff --git a/src/main/resources/assets/mmclutils/shaders/effect/ring_ribbon.vsh b/src/main/resources/assets/mmclutils/shaders/effect/ring_ribbon.vsh new file mode 100644 index 0000000..02245d7 --- /dev/null +++ b/src/main/resources/assets/mmclutils/shaders/effect/ring_ribbon.vsh @@ -0,0 +1,52 @@ +#version 150 + +//COMMON + +uniform int Segments; + +vec3 ribbonPoint(mat3 basis, int segment, out vec3 side, float width) { + float angle = TAU * float(segment) / float(Segments); + vec3 point = Ring0.xyz + basis * vec3(cos(angle) * Ring2.y, 0.0, sin(angle) * Ring2.y); + vec3 tangent = basis * vec3(-sin(angle), 0.0, cos(angle)); + side = cross(tangent, point); + side *= width / max(length(side), 0.0001); + return point; +} + +vec3 helixRibbonPoint(float strand, float sweep, out vec3 side, float width) { + vec3 point = helixPoint(strand, sweep, Ring2.y, 0.0); + vec3 ahead = helixPoint(strand, sweep + 0.001, Ring2.y, 0.0); + side = cross(ahead - point, point); + side *= width * helixFade(helixAlong(sweep)) / max(length(side), 0.0001); + return point; +} + +void main() { + int local = gl_InstanceID % (Segments * 2); + int layer = local / Segments; + int segment = local - layer * Segments; + float width = layer == 0 ? Ring2.z : Ring2.w; + vec3 sideA; + vec3 sideB; + vec3 a; + vec3 b; + if (Ring5.x < 0.5) { + mat3 basis = ringBasis(Ring2.x); + a = ribbonPoint(basis, segment, sideA, width); + b = ribbonPoint(basis, segment + 1, sideB, width); + } else { + int strands = int(Ring5.x + 0.5); + int perStrand = Segments / strands; + int strand = min(segment / perStrand, strands - 1); + int piece = segment - strand * perStrand; + a = helixRibbonPoint(float(strand), float(piece) / float(perStrand), sideA, width); + b = helixRibbonPoint(float(strand), float(piece + 1) / float(perStrand), sideB, width); + } + vec3 quad[4] = vec3[](a + sideA, a - sideA, b - sideB, b + sideB); + vec2 uv[4] = vec2[](vec2(0.0, 0.5), vec2(1.0, 0.5), vec2(1.0, 0.5), vec2(0.0, 0.5)); + int corner = gl_VertexID; + if (dot(cross(quad[1] - quad[0], quad[2] - quad[0]), quad[0]) > 0.0) corner = 3 - corner; + tfPosition = quad[corner]; + tfUV = uv[corner]; + tfColor = vec4(layer == 0 ? Ring3.rgb : Ring4.rgb, 1.0); +} diff --git a/src/main/resources/assets/mmclutils/shaders/effect/ring_voxel.vsh b/src/main/resources/assets/mmclutils/shaders/effect/ring_voxel.vsh new file mode 100644 index 0000000..a4eadb0 --- /dev/null +++ b/src/main/resources/assets/mmclutils/shaders/effect/ring_voxel.vsh @@ -0,0 +1,35 @@ +#version 150 + +//COMMON + +mat3 spinMatrix(vec3 a, float angle) { + float c = cos(angle); + float s = sin(angle); + float t = 1.0 - c; + return mat3( + t * a.x * a.x + c, t * a.x * a.y + s * a.z, t * a.x * a.z - s * a.y, + t * a.x * a.y - s * a.z, t * a.y * a.y + c, t * a.y * a.z + s * a.x, + t * a.x * a.z + s * a.y, t * a.y * a.z - s * a.x, t * a.z * a.z + c); +} + +const vec2 CORNERS[4] = vec2[](vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0)); + +void main() { + int index = gl_InstanceID % ParticleCount; + vec4 motion = particle(index, 0); + vec4 drift = particle(index, 1); + vec4 spin = particle(index, 2); + vec3 spinAxis = particle(index, 3).xyz; + mat3 rotation = spinMatrix(spinAxis, spin.x * Ring0.w + spin.y); + vec3 center = ringPoint(motion, drift); + int face = gl_VertexID / 4; + vec2 corner = CORNERS[gl_VertexID - face * 4]; + vec3 normal = rotation[face]; + if (dot(normal, center) > 0.0) normal = -normal; + vec3 tangent = rotation[(face + 1) % 3]; + vec3 bitangent = cross(normal, tangent); + tfPosition = center + (normal + corner.x * tangent + corner.y * bitangent) * Ring1.x * pathScale; + float shade = 0.75 + 0.25 * normal.y + 0.05 * (abs(normal.z) - abs(normal.x)); + tfColor = vec4(paletteColor(spin.z) * shade, 1.0); + tfUV = vec2(0.5); +} diff --git a/src/main/resources/mmclutils.mixins.json b/src/main/resources/mmclutils.mixins.json index e6215cc..26c1cfb 100644 --- a/src/main/resources/mmclutils.mixins.json +++ b/src/main/resources/mmclutils.mixins.json @@ -13,7 +13,8 @@ ], "client": [ "client.level.ClientChunkCacheMixin", - "client.level.ClientChunkStorageMixin" + "client.level.ClientChunkStorageMixin", + "client.render.GlBufferAccessor" ], "injectors": { "defaultRequire": 1 From 3ccc4b4f5870f9fd0eef787870e34ae5877c0054 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 01:28:12 +0800 Subject: [PATCH 07/79] =?UTF-8?q?=E6=95=B4=E7=90=86=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E6=8C=89=E9=94=AE=E5=90=8C=E6=AD=A5=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/ModularMCLibUtils.java | 5 +- .../client/ModularMCLibUtilsClient.java | 2 + .../mmclutils/client/input/ClientInput.java | 48 ++++ .../client/input/ClientKeyBindings.java | 207 ++++++++++++++++++ .../mmclutils/input/SyncedKeyMappings.java | 189 ++++++++++++++++ 5 files changed, 450 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java create mode 100644 src/main/java/com/modularmc/mmclutils/input/SyncedKeyMappings.java diff --git a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java index 4e15f12..ce2dc9f 100644 --- a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java +++ b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java @@ -1,6 +1,7 @@ package com.modularmc.mmclutils; import com.modularmc.mmclutils.client.ModularMCLibUtilsClient; +import com.modularmc.mmclutils.input.SyncedKeyMappings; import net.minecraft.resources.Identifier; import net.minecraft.server.MinecraftServer; @@ -26,7 +27,9 @@ public class ModularMCLibUtils { public static final String MOD_NAME = "ModularMCLib Utils"; public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); - public ModularMCLibUtils(IEventBus bus) {} + public ModularMCLibUtils(IEventBus modBus) { + SyncedKeyMappings.init(modBus); + } public static Identifier id(String path) { return Identifier.fromNamespaceAndPath(MOD_ID, path); diff --git a/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java b/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java index 3d363e8..9f11aef 100644 --- a/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java +++ b/src/main/java/com/modularmc/mmclutils/client/ModularMCLibUtilsClient.java @@ -1,6 +1,7 @@ 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; @@ -22,6 +23,7 @@ public final class ModularMCLibUtilsClient { public ModularMCLibUtilsClient(IEventBus modBus) { EffectRenderer.init(modBus); + ClientKeyBindings.init(modBus); } public static boolean isClientThread() { 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..22847a5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java @@ -0,0 +1,48 @@ +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 { + + public static final int CONTROL = 1; + public static final int SHIFT = 2; + public static final int ALT = 4; + public static final int COMMAND = 8; + + 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); + } + + 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; + }; + } + + /** 直接读取主键。扫描码使用原版记录的状态,当前输入事件可以提供更早的状态变化。 */ + 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..58bf0f4 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java @@ -0,0 +1,207 @@ +package com.modularmc.mmclutils.client.input; + +import com.modularmc.mmclutils.ModularMCLibUtils; +import com.modularmc.mmclutils.input.SyncedKeyMappings.ChangeSet; +import com.modularmc.mmclutils.input.SyncedKeyMappings.Key; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.resources.Identifier; +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.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.settings.KeyModifier; + +import com.mojang.blaze3d.platform.InputConstants; +import it.unimi.dsi.fastutil.objects.Object2BooleanLinkedOpenHashMap; +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.Supplier; + +/** 绑定原版按键,采样组合键并同步状态变化。 */ +@EventBusSubscriber(modid = ModularMCLibUtils.MOD_ID, value = Dist.CLIENT) +public final class ClientKeyBindings { + + private static final Reference2ObjectLinkedOpenHashMap BINDINGS = new Reference2ObjectLinkedOpenHashMap<>(); + 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); + } + + @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 + private static void sampleMouse(InputEvent.MouseButton.Post event) { + sample(InputConstants.Type.MOUSE.getOrCreate(event.getButton()), event.getAction() == GLFW.GLFW_PRESS); + } + + private static void sample(InputConstants.@Nullable Key changed, boolean down) { + if (BINDINGS.isEmpty()) return; + Minecraft client = Minecraft.getInstance(); + if (client.player == null) return; + if (owner != client.player) { + clearLocalState(); + owner = client.player; + } + boolean available = client.isWindowActive() && client.screen == null && !client.isPaused(); + int modifiers = available ? ClientInput.modifiers() : 0; + ObjectArrayList changes = null; + 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; + boolean pressed = mainDown && available && !binding.waitingForRelease && binding.matches(mapping, modifiers); + if (binding.down == pressed) continue; + binding.down = pressed; + if (changes == null) changes = new ObjectArrayList<>(); + changes.add(binding); + } + if (changes == null) return; + var connection = client.getConnection(); + 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) { + clearLocalState(); + owner = null; + } + + private static void clearLocalState() { + for (Binding binding : BINDINGS.values()) { + binding.waitingForRelease = false; + if (!binding.down) continue; + binding.down = false; + 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 @Nullable KeyMapping mapping; + private int extraModifiers; + 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 Binding withModifiers(int modifiers) { + if ((modifiers & ~(ClientInput.CONTROL | ClientInput.SHIFT | ClientInput.ALT | ClientInput.COMMAND)) != 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); + } + + private 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.modifierBit(KeyModifier.getKeyModifier(mapping.getKey())); + int expected = (extraModifiers | ClientInput.modifierBit(mapping.getKeyModifier())) & ~mainModifier; + return mapping.getKeyConflictContext().isActive() && (modifiers & ~mainModifier) == expected; + } + + private void notifyListeners() { + for (Listener listener : listeners) listener.changed(this, down); + } + } + + /** 在客户端线程接收绑定的按下和释放通知。 */ + @FunctionalInterface + public interface Listener { + + /** 在本地绑定状态已经更新时调用。失焦与断开连接都会产生释放。 */ + void changed(Binding binding, boolean down); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/input/SyncedKeyMappings.java b/src/main/java/com/modularmc/mmclutils/input/SyncedKeyMappings.java new file mode 100644 index 0000000..2604f7b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/input/SyncedKeyMappings.java @@ -0,0 +1,189 @@ +package com.modularmc.mmclutils.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 { + + /** 在状态已更新时收到通知。退出时仍处于按下状态的键会发出释放通知。 */ + void changed(ServerPlayer player, Key key, boolean down); + } + + @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; + } + } +} From 2fcd63a94f3aca91743577a5e1fa1740b637738c Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 02:14:04 +0800 Subject: [PATCH 08/79] =?UTF-8?q?=E6=89=A9=E5=B1=95=E9=9B=86=E5=90=88?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E4=B8=8E=E4=BB=BB=E5=8A=A1=E8=B0=83=E5=BA=A6?= =?UTF-8?q?=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/collection/ArrayOperations.java | 237 +++++++++++++++++ .../collection/CollectionCopies.java | 127 +++++++++ .../mmclutils/collection/MapIterators.java | 36 +++ .../cache/ConcurrentWeakIdentityHashMap.java | 241 ++++++++++++++++++ .../collection/map/LongCounters.java | 117 +++++++++ .../hash/Object2LongOpenCachedHashMap.java | 5 + .../concurrent/BoundedVirtualTaskQueue.java | 232 +++++++++++++++++ .../concurrent/PriorityTaskExecutor.java | 54 ++++ .../mmclutils/concurrent/ScopedOverride.java | 86 +++++++ .../mmclutils/concurrent/ServerExecutors.java | 37 +++ .../concurrent/SlidingWindowCounter.java | 60 +++++ .../mmclutils/concurrent/TaskFailures.java | 34 +++ .../mmclutils/function/Accumulator.java | 25 ++ .../mmclutils/function/IntObjectConsumer.java | 35 +++ .../mmclutils/function/Memoization.java | 87 +++++++ .../function/MemoizedBiFunction.java | 11 + .../mmclutils/function/MemoizedFunction.java | 9 + .../mmclutils/function/MemoizedSupplier.java | 33 +++ .../function/MemoizedTriFunction.java | 11 + .../mmclutils/persistence/FastSavedData.java | 12 +- .../mmclutils/schedule/BatchProgress.java | 40 +++ .../mmclutils/schedule/PriorityTaskQueue.java | 56 ++++ .../mmclutils/schedule/ProgressTimers.java | 37 +++ .../mmclutils/schedule/TickScheduler.java | 4 +- 24 files changed, 1618 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/modularmc/mmclutils/collection/ArrayOperations.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/CollectionCopies.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/MapIterators.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/cache/ConcurrentWeakIdentityHashMap.java create mode 100644 src/main/java/com/modularmc/mmclutils/collection/map/LongCounters.java create mode 100644 src/main/java/com/modularmc/mmclutils/concurrent/BoundedVirtualTaskQueue.java create mode 100644 src/main/java/com/modularmc/mmclutils/concurrent/PriorityTaskExecutor.java create mode 100644 src/main/java/com/modularmc/mmclutils/concurrent/ScopedOverride.java create mode 100644 src/main/java/com/modularmc/mmclutils/concurrent/ServerExecutors.java create mode 100644 src/main/java/com/modularmc/mmclutils/concurrent/SlidingWindowCounter.java create mode 100644 src/main/java/com/modularmc/mmclutils/concurrent/TaskFailures.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/Accumulator.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/IntObjectConsumer.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/Memoization.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/MemoizedBiFunction.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/MemoizedFunction.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/MemoizedSupplier.java create mode 100644 src/main/java/com/modularmc/mmclutils/function/MemoizedTriFunction.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/BatchProgress.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/PriorityTaskQueue.java create mode 100644 src/main/java/com/modularmc/mmclutils/schedule/ProgressTimers.java diff --git a/src/main/java/com/modularmc/mmclutils/collection/ArrayOperations.java b/src/main/java/com/modularmc/mmclutils/collection/ArrayOperations.java new file mode 100644 index 0000000..ea35f10 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/ArrayOperations.java @@ -0,0 +1,237 @@ +package com.modularmc.mmclutils.collection; + +import org.jetbrains.annotations.Contract; +import org.jspecify.annotations.Nullable; + +import java.lang.reflect.Array; +import java.util.Objects; + +import static org.apache.commons.lang3.ArrayUtils.*; + +@SuppressWarnings("ForLoopReplaceableByForEach") +public class ArrayOperations { + + /** + * Returns a copy of the specified array object, deeply copying multidimensional arrays. + * If the specified object is null, the return value is null. + * + *

+ * Note: if the array object has an element type which is a reference type that is not an array type, + * the elements themselves are not deeply copied. This method only copies array objects. + * + * @param array the array object to deep copy + * @param the type of the array to deep copy + * @return a copy of the specified array object, deeply copying multidimensional arrays, or null if the object is + * null + */ + @Contract(value = "!null -> !null; _ -> null", pure = true) + public static T @Nullable [] deepCopy(T @Nullable [] array) { + if (array == null) { + return null; + } + + Class componentType = array.getClass().getComponentType(); + + @SuppressWarnings("unchecked") + T[] copy = (T[]) Array.newInstance(componentType, array.length); + + if (componentType.isArray()) { + for (int i = 0; i < array.length; ++i) { + // noinspection unchecked + Array.set(copy, i, deepCopy((T[]) array[i])); + } + } else { + System.arraycopy(array, 0, copy, 0, array.length); + } + + return copy; + } + + public static boolean allMatch(boolean[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + boolean firstElement = array[0]; + if (array.length == 2) return firstElement == array[1]; + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement) { + return false; + } + } + return true; + } + + public static boolean allMatch(byte[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + byte firstElement = array[0]; + if (array.length == 2) return firstElement == array[1]; + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement) { + return false; + } + } + return true; + } + + public static boolean allMatch(char[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + char firstElement = array[0]; + if (array.length == 2) return firstElement == array[1]; + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement) { + return false; + } + } + return true; + } + + public static boolean allMatch(double[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + double firstElement = array[0]; + boolean searchNaN = Double.isNaN(firstElement); + + if (array.length == 2) return array[1] == firstElement || searchNaN && Double.isNaN(array[1]); + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement && !(searchNaN && Double.isNaN(array[i]))) { + return false; + } + } + + return false; + } + + public static boolean allMatch(double[] array, double tolerance) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + double firstElement = array[0]; + double min = firstElement - tolerance; + double max = firstElement + tolerance; + + if (array.length == 2) return array[1] >= min && array[1] <= max; + + for (int i = 0; i < array.length; ++i) { + if (array[i] < min || array[i] > max) { + return false; + } + } + return true; + } + + public static boolean allMatch(float[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + float firstElement = array[0]; + boolean searchNaN = Float.isNaN(firstElement); + + if (array.length == 2) return array[1] == firstElement || searchNaN && Float.isNaN(array[1]); + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement && !(searchNaN && Float.isNaN(array[i]))) { + return false; + } + } + + return false; + } + + public static boolean allMatch(float[] array, float tolerance) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + float firstElement = array[0]; + float min = firstElement - tolerance; + float max = firstElement + tolerance; + + if (array.length == 2) return array[1] >= min && array[1] <= max; + + for (int i = 0; i < array.length; ++i) { + if (array[i] < min && array[i] > max) { + return false; + } + } + return true; + } + + public static boolean allMatch(int[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + int firstElement = array[0]; + if (array.length == 2) return firstElement == array[1]; + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement) { + return false; + } + } + return true; + } + + public static boolean allMatch(long[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + long firstElement = array[0]; + if (array.length == 2) return firstElement == array[1]; + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement) { + return false; + } + } + return true; + } + + public static boolean allMatch(Object[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + Object firstElement = array[0]; + if (array.length == 2) return Objects.equals(array[1], firstElement); + + for (int i = 0; i < array.length; ++i) { + if (!Objects.equals(array[i], firstElement)) { + return false; + } + } + return true; + } + + public static boolean allMatch(short[] array) { + if (isEmpty(array) || array.length == 1) { + return true; + } + + short firstElement = array[0]; + if (array.length == 2) return firstElement == array[1]; + + for (int i = 0; i < array.length; ++i) { + if (array[i] != firstElement) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/CollectionCopies.java b/src/main/java/com/modularmc/mmclutils/collection/CollectionCopies.java new file mode 100644 index 0000000..a6a4e1e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/CollectionCopies.java @@ -0,0 +1,127 @@ +package com.modularmc.mmclutils.collection; + +import com.mojang.serialization.Codec; +import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +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; +import java.util.Map; + +/** 复制为不可变集合,或直接构造键值数量较小的映射。 */ +public final class CollectionCopies { + + private CollectionCopies() {} + + 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 Codec> objectListCodec(Codec elementCodec) { + return elementCodec.listOf().xmap( + values -> new ObjectArrayList<>(values), + values -> values); + } + + 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)); + } + + public static Object2ObjectMap immutableMap(Map source) { + if (source.isEmpty()) return Object2ObjectMaps.emptyMap(); + if (source instanceof ImmutableMapCopy) { + // 后备映射为该副本独有,可直接复用。 + @SuppressWarnings("unchecked") + Object2ObjectMap immutable = (Object2ObjectMap) source; + return immutable; + } + Object2ObjectMap copied = source.size() <= 8 ? new Object2ObjectArrayMap<>(source) : + new Object2ObjectLinkedOpenHashMap<>(source); + return new ImmutableMapCopy<>(copied); + } + + public static Object2ObjectMap mapOf() { + return Object2ObjectMaps.emptyMap(); + } + + public static Object2ObjectMap mapOf(K key, V value) { + return Object2ObjectMaps.singleton(key, value); + } + + public static Object2ObjectMap mapOf(K key1, V value1, K key2, V value2) { + return mapOfEntries(key1, value1, key2, value2); + } + + public static Object2ObjectMap mapOf( + K key1, V value1, + K key2, V value2, + K key3, V value3) { + return mapOfEntries(key1, value1, key2, value2, key3, value3); + } + + public static Object2ObjectMap mapOf( + K key1, V value1, + K key2, V value2, + K key3, V value3, + K key4, V value4) { + return mapOfEntries(key1, value1, key2, value2, key3, value3, key4, value4); + } + + /** 从四对以上的交替键值参数创建不可变映射。 */ + public static Object2ObjectMap mapOf(Object... entries) { + return mapOfEntries(entries); + } + + private static Object2ObjectMap mapOfEntries(Object... entries) { + if ((entries.length & 1) != 0) { + throw new IllegalArgumentException("Collection map entries must be key/value pairs"); + } + Object2ObjectLinkedOpenHashMap result = new Object2ObjectLinkedOpenHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + @SuppressWarnings("unchecked") + K key = (K) entries[index]; + @SuppressWarnings("unchecked") + V value = (V) entries[index + 1]; + if (result.containsKey(key)) { + throw new IllegalArgumentException("Duplicate collection map key: " + key); + } + result.put(key, value); + } + return new ImmutableMapCopy<>(result); + } + + private static final class ImmutableMapCopy extends Object2ObjectMaps.UnmodifiableMap { + + private ImmutableMapCopy(Object2ObjectMap owned) { + super(owned); + } + } + + private static final class ImmutableSetCopy extends ObjectSets.UnmodifiableSet { + + private ImmutableSetCopy(ObjectSet owned) { + super(owned); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/MapIterators.java b/src/main/java/com/modularmc/mmclutils/collection/MapIterators.java new file mode 100644 index 0000000..db0dd95 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/MapIterators.java @@ -0,0 +1,36 @@ +package com.modularmc.mmclutils.collection; + +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; +import it.unimi.dsi.fastutil.objects.Reference2ObjectMaps; + +import java.util.Iterator; +import java.util.Map; + +/** fastutil 条目的快速迭代入口。调用方需要立即读取可能复用的条目。 */ +public final class MapIterators { + + private MapIterators() {} + + public static ObjectIterator> fast(Object2ObjectMap map) { + return Object2ObjectMaps.fastIterator(map); + } + + public static ObjectIterator> fast(Reference2ObjectMap map) { + return Reference2ObjectMaps.fastIterator(map); + } + + /** 兼容标准 Map,识别 fastutil 映射并选择相应的快速迭代器。 */ + @SuppressWarnings("unchecked") + public static Iterator> fastIterator(Map map) { + if (map instanceof Object2ObjectMap objectMap) { + return (Iterator>) (Iterator) fast(objectMap); + } + if (map instanceof Reference2ObjectMap referenceMap) { + return (Iterator>) (Iterator) fast(referenceMap); + } + return map.entrySet().iterator(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/cache/ConcurrentWeakIdentityHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/cache/ConcurrentWeakIdentityHashMap.java new file mode 100644 index 0000000..ca628ff --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/cache/ConcurrentWeakIdentityHashMap.java @@ -0,0 +1,241 @@ +package com.modularmc.mmclutils.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; + +import javax.annotation.ParametersAreNonnullByDefault; + +@ParametersAreNonnullByDefault +@NullMarked +public class ConcurrentWeakIdentityHashMap extends AbstractMap implements ConcurrentMap { + + private final ConcurrentMap, V> map; + private final ReferenceQueue queue = new ReferenceQueue<>(); + private transient @Nullable Set> entrySet; + + 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 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) { + return obj == this || obj instanceof Key key && key.get() == this.get(); + } + + @Override + public int hashCode() { + return hash; + } + } + + private class Iter implements Iterator> { + + private final Iterator, V>> it; + private Map.@Nullable Entry nextValue; + + 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.@Nullable Entry next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + Map.Entry entry = nextValue; + nextValue = null; + return entry; + } + + @Override + public void remove() { + it.remove(); + nextValue = 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 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/collection/map/LongCounters.java b/src/main/java/com/modularmc/mmclutils/collection/map/LongCounters.java new file mode 100644 index 0000000..be3fbc2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/collection/map/LongCounters.java @@ -0,0 +1,117 @@ +package com.modularmc.mmclutils.collection.map; + +import com.modularmc.mmclutils.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/collection/map/hash/Object2LongOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java index db72312..d0e9e4a 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java @@ -174,6 +174,11 @@ public long addTo(final K k, final long incr) { return defRetValue; } + /** 只清零存储值,保留键、容量及默认返回值。 */ + public void resetValues() { + Arrays.fill(value, 0); + } + @Override public long removeLong(final Object k) { if (k == null) { diff --git a/src/main/java/com/modularmc/mmclutils/concurrent/BoundedVirtualTaskQueue.java b/src/main/java/com/modularmc/mmclutils/concurrent/BoundedVirtualTaskQueue.java new file mode 100644 index 0000000..90ea61a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/concurrent/BoundedVirtualTaskQueue.java @@ -0,0 +1,232 @@ +package com.modularmc.mmclutils.concurrent; + +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; + +/** + * Single-owner task admission with bounded, streamed results from virtual threads. The owner alone submits, + * polls and cancels; workers only use their Work context. Emitted values transfer ownership to the queue, + * then to the polling caller. Invalidated values are released on the emitting or owner thread, so release + * must be thread-safe and must not require a GPU context. No Minecraft world or renderer is retained here. + */ +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; + + /** Creates a queue with positive concurrency/capacity limits; thread names identify the owning subsystem. */ + 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()); + } + + /** Owner-thread admission check; completed but unconsumed tasks retain their slot to bound memory. */ + public boolean hasCapacity() { + return !closed && tasks.size() < parallelism && workers.availablePermits() > 0; + } + + /** Reports whether the owner still has a current task for this primitive key. */ + public boolean contains(long key) { + return tasks.containsKey(key); + } + + /** Starts one current task. The caller must have capacity and must cancel an older task with the same key. */ + 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; + } + } + + /** + * Polls without waiting. Nonterminal values belong to the caller, who must release them after use. + * Terminal results contain no value and may contain a worker failure; cancelled generations are discarded. + */ + 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; + } + + /** Invalidates a key and interrupts its worker without waiting. Unpolled values are released immediately. */ + 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; + }); + } + } + + /** Advances the lifecycle generation, cancels every task and releases queued values without joining workers. */ + public void clear() { + generation++; + for (long key : tasks.keySet().toLongArray()) cancel(key); + } + + /** Permanently closes admission and interrupts workers; never blocks the owner waiting for termination. */ + @Override + public void close() { + clear(); + closed = true; + executor.shutdownNow(); + } + + /** A worker's immutable task key and its privately owned cancellation/handoff context. */ + 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; + } + + /** Cooperative cancellation predicate for bounded loops; has no side effects. */ + public boolean cancelled() { + return ticket.cancelled.get() || Thread.currentThread().isInterrupted(); + } + + /** Throws CancellationException when a task revision was invalidated or its thread was interrupted. */ + public void checkCancelled() { + if (cancelled()) throw new CancellationException(); + } + + /** + * Transfers a nonnull value, waiting interruptibly for result capacity. On cancellation or rejection, + * this method releases the supplied value before throwing; the worker must never release it again. + */ + 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(); + } + } + } + + /** Owner-thread delivery; value is present only for data, failure only for terminal failure. */ + 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/concurrent/PriorityTaskExecutor.java b/src/main/java/com/modularmc/mmclutils/concurrent/PriorityTaskExecutor.java new file mode 100644 index 0000000..90560d6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/concurrent/PriorityTaskExecutor.java @@ -0,0 +1,54 @@ +package com.modularmc.mmclutils.concurrent; + +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/concurrent/ScopedOverride.java b/src/main/java/com/modularmc/mmclutils/concurrent/ScopedOverride.java new file mode 100644 index 0000000..4d825ef --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/concurrent/ScopedOverride.java @@ -0,0 +1,86 @@ +package com.modularmc.mmclutils.concurrent; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.jspecify.annotations.Nullable; + +/** + * "recreations" of Java 25 scoped values using {@link AutoCloseable AutoCloseables}. + */ +public abstract class ScopedOverride implements AutoCloseable { + + /** + * Scoped object value. Resets to {@code null} when exiting scope. + * + * @param The type of the object. + */ + @RequiredArgsConstructor + public static final class Object extends ScopedOverride { + + private final @Nullable T initialValue; + + /** + * Current value in this scope + */ + @Getter + private @Nullable T value; + + public Object() { + this(null); + } + + /** + * Set {@code current} to {@code value} within this scope. + * + * @return this + */ + public Object with(T value) { + this.value = value; + return this; + } + + @Override + public void close() { + this.value = this.initialValue; + } + } + + /** + * Scoped boolean value. Resets to {@link #initialValue} when exiting scope. + */ + @RequiredArgsConstructor + public static final class Boolean extends ScopedOverride { + + private final boolean initialValue; + + /** + * Current value in this scope + */ + @Getter + private boolean active; + + /** + * Set {@code current} to {@code value} within this scope. + * + * @return this + */ + public Boolean with(boolean value) { + this.active = value; + return this; + } + + /** + * Shortcut method that sets {@code current} to {@code !initial} + * + * @return this + */ + public Boolean active() { + return with(!this.initialValue); + } + + @Override + public void close() { + this.active = this.initialValue; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/concurrent/ServerExecutors.java b/src/main/java/com/modularmc/mmclutils/concurrent/ServerExecutors.java new file mode 100644 index 0000000..aa06ba6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/concurrent/ServerExecutors.java @@ -0,0 +1,37 @@ +package com.modularmc.mmclutils.concurrent; + +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/concurrent/SlidingWindowCounter.java b/src/main/java/com/modularmc/mmclutils/concurrent/SlidingWindowCounter.java new file mode 100644 index 0000000..3a5c8ba --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/concurrent/SlidingWindowCounter.java @@ -0,0 +1,60 @@ +package com.modularmc.mmclutils.concurrent; + +import java.util.Arrays; +import java.util.function.LongSupplier; + +/** + * Limits a rate/throughput across a certain amount of time, without needing an active tick subscription + */ +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/concurrent/TaskFailures.java b/src/main/java/com/modularmc/mmclutils/concurrent/TaskFailures.java new file mode 100644 index 0000000..5a23de1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/concurrent/TaskFailures.java @@ -0,0 +1,34 @@ +package com.modularmc.mmclutils.concurrent; + +/** + * Defines the process-level boundary between recoverable third-party failures and fatal JVM failures. + * + *

+ * Integration code uses this utility after catching {@link Throwable}. Recoverable failures remain available to the + * caller for logging, rollback, or endpoint isolation, while failures that must terminate the current execution are + * rethrown unchanged. + */ +public final class TaskFailures { + + private TaskFailures() {} + + /** + * Rethrows fatal JVM failures and preserves interruption before a recoverable failure is handled. + * + *

+ * {@link VirtualMachineError} is never an integration failure and therefore must retain its original identity and + * propagation semantics. A sneaky {@link InterruptedException} is recoverable at the integration boundary, but + * its thread interruption signal must not be lost. + * + * @param throwable failure caught while invoking third-party code + * @throws VirtualMachineError when {@code throwable} is a fatal JVM failure + */ + 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/function/Accumulator.java b/src/main/java/com/modularmc/mmclutils/function/Accumulator.java new file mode 100644 index 0000000..e9d3e0e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/Accumulator.java @@ -0,0 +1,25 @@ +package com.modularmc.mmclutils.function; + +import java.util.function.BiFunction; +import java.util.function.Consumer; + +/** 按接收顺序将输入累积到一个值中,可用作顺序流的消费端。 */ +public final class Accumulator implements Consumer { + + private final BiFunction accumulate; + 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); + } + + public T getValue() { + return value; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/function/IntObjectConsumer.java b/src/main/java/com/modularmc/mmclutils/function/IntObjectConsumer.java new file mode 100644 index 0000000..3fc32d7 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/IntObjectConsumer.java @@ -0,0 +1,35 @@ +package com.modularmc.mmclutils.function; + +import java.util.function.BiConsumer; +import java.util.function.BinaryOperator; + +/** + * A type-specific {@link BinaryOperator}; provides methods operating both on objects and on + * primitives. + * + * @see BinaryOperator + * @since 8.5.0 + */ +@FunctionalInterface +public interface IntObjectConsumer extends BiConsumer { + + /** + * Computes the operator on the given inputs. + * + * @param t the first input. + * @param u the second input. + * @return the output of the operator on the given inputs. + */ + void accept(int t, T u); + + /** + * {@inheritDoc} + * + * @deprecated Please use the corresponding type-specific method instead. + */ + @Deprecated + @Override + default void accept(Integer integer, T u) { + accept((int) integer, u); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/function/Memoization.java b/src/main/java/com/modularmc/mmclutils/function/Memoization.java new file mode 100644 index 0000000..e250fcc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/Memoization.java @@ -0,0 +1,87 @@ +package com.modularmc.mmclutils.function; + +import com.modularmc.mmclutils.collection.cache.ConcurrentWeakIdentityHashMap; + +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 java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; + +public class Memoization { + + /** + * This method doesn't return a thread-safe memoization of the delegate, if you need thread-safety you should use + * {@link com.google.common.base.Suppliers#memoize(com.google.common.base.Supplier) memoize} + * + * @param delegate the supplier to memoize + * @return memoized supplier for the delegate + */ + public static MemoizedSupplier memoize(Supplier delegate) { + return new MemoizedSupplier<>(delegate); + } + + 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() + "]"; + } + }; + } + + public static MemoizedBiFunction memoizeFunctionWeakIdent(final BiFunction memoBiFunction) { + return new MemoizedBiFunction<>() { + + @Getter + private final Map, R> cache = new ConcurrentWeakIdentityHashMap<>(); + + @Override + public R apply(T key1, U key2) { + return this.cache.computeIfAbsent(Pair.of(key1, key2), (key) -> { + return memoBiFunction.apply(key.getLeft(), key.getRight()); + }); + } + + @Override + public String toString() { + return "memoizeFunctionWeakIdent/2[function=" + memoBiFunction + ", size=" + this.cache.size() + "]"; + } + }; + } + + 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() + "]"; + } + }; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/function/MemoizedBiFunction.java b/src/main/java/com/modularmc/mmclutils/function/MemoizedBiFunction.java new file mode 100644 index 0000000..b1ac63a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/MemoizedBiFunction.java @@ -0,0 +1,11 @@ +package com.modularmc.mmclutils.function; + +import org.apache.commons.lang3.tuple.Pair; + +import java.util.Map; +import java.util.function.BiFunction; + +public interface MemoizedBiFunction extends BiFunction { + + Map, R> getCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/function/MemoizedFunction.java b/src/main/java/com/modularmc/mmclutils/function/MemoizedFunction.java new file mode 100644 index 0000000..abb0abb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/MemoizedFunction.java @@ -0,0 +1,9 @@ +package com.modularmc.mmclutils.function; + +import java.util.Map; +import java.util.function.Function; + +public interface MemoizedFunction extends Function { + + Map getCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/function/MemoizedSupplier.java b/src/main/java/com/modularmc/mmclutils/function/MemoizedSupplier.java new file mode 100644 index 0000000..782289d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/MemoizedSupplier.java @@ -0,0 +1,33 @@ +package com.modularmc.mmclutils.function; + +import java.util.function.Supplier; + +public class MemoizedSupplier implements Supplier { + + protected T value = null; + protected boolean initialized = false; + protected final Supplier delegate; + + protected MemoizedSupplier(Supplier delegate) { + this.delegate = delegate; + } + + @Override + public T get() { + if (!initialized) { + value = delegate.get(); + initialized = true; + } + return value; + } + + 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/function/MemoizedTriFunction.java b/src/main/java/com/modularmc/mmclutils/function/MemoizedTriFunction.java new file mode 100644 index 0000000..b3e62c2 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/function/MemoizedTriFunction.java @@ -0,0 +1,11 @@ +package com.modularmc.mmclutils.function; + +import org.apache.commons.lang3.function.TriFunction; +import org.apache.commons.lang3.tuple.Triple; + +import java.util.Map; + +public interface MemoizedTriFunction extends TriFunction { + + Map, R> getCache(); +} diff --git a/src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java b/src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java index 82ad2d2..132bd63 100644 --- a/src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java +++ b/src/main/java/com/modularmc/mmclutils/persistence/FastSavedData.java @@ -118,10 +118,10 @@ private static void saveLevel(ServerLevel level, boolean wait) { private void save(boolean wait) { long revision = changes.revision(); if (changes.isDirty() && (submitted != revision || pending.isCompletedExceptionally())) { - T snapshot = type.snapshot().apply(value); + T valueToWrite = type.copyForWrite().apply(value); submitted = revision; pending = executor.submit(() -> { - BinaryFiles.writeAtomically(path, snapshot, type.writer()); + BinaryFiles.writeAtomically(path, valueToWrite, type.writer()); changes.persisted(revision); return null; }); @@ -149,14 +149,14 @@ private static void checkOwner(ServerLevel level) { if (!level.getServer().isSameThread()) throw new IllegalStateException("存档须在所属服务器线程访问"); } - /** snapshot 应当返回可由写盘线程独立读取的值。读取失败时保留原有的存档文件。 */ - public record Type(Identifier id, Supplier factory, UnaryOperator snapshot, + /** copyForWrite 由世界线程调用,返回写盘线程可以独立读取的值。 */ + public record Type(Identifier id, Supplier factory, UnaryOperator copyForWrite, BinaryFiles.Reader reader, BinaryFiles.Writer writer, @Nullable LegacyFile legacy) { - public Type(Identifier id, Supplier factory, UnaryOperator snapshot, + public Type(Identifier id, Supplier factory, UnaryOperator copyForWrite, BinaryFiles.Reader reader, BinaryFiles.Writer writer) { - this(id, factory, snapshot, reader, writer, null); + this(id, factory, copyForWrite, reader, writer, null); } } diff --git a/src/main/java/com/modularmc/mmclutils/schedule/BatchProgress.java b/src/main/java/com/modularmc/mmclutils/schedule/BatchProgress.java new file mode 100644 index 0000000..34d22d3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/BatchProgress.java @@ -0,0 +1,40 @@ +package com.modularmc.mmclutils.schedule; + +/** + * Computes the largest constant-state progress segment before a machine reaches its next work boundary. + */ +public final class BatchProgress { + + private BatchProgress() {} + + /** + * Advances progress to either the end of the available tick budget or the next completion boundary. + * + * @param progress current progress in {@code [0, duration)} + * @param duration positive ticks required for one completion + * @param availableTicks positive ticks available in the current batch + * @return elapsed ticks, next progress, and whether a completion boundary was reached + */ + 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); + } + + /** + * One constant-state progression segment. + */ + public record Segment(int elapsedTicks, int progress, boolean reachedBoundary) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/schedule/PriorityTaskQueue.java b/src/main/java/com/modularmc/mmclutils/schedule/PriorityTaskQueue.java new file mode 100644 index 0000000..816f04e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/PriorityTaskQueue.java @@ -0,0 +1,56 @@ +package com.modularmc.mmclutils.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/schedule/ProgressTimers.java b/src/main/java/com/modularmc/mmclutils/schedule/ProgressTimers.java new file mode 100644 index 0000000..aa3292e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/schedule/ProgressTimers.java @@ -0,0 +1,37 @@ +package com.modularmc.mmclutils.schedule; + +import java.util.function.DoubleSupplier; + +public class ProgressTimers implements DoubleSupplier { + + private final int msPerCycle; + private final int maxValue; + private final boolean countDown; + private long startTime; + + public ProgressTimers(int ticksPerCycle, int maxValue, boolean countDown) { + this.msPerCycle = 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/schedule/TickScheduler.java b/src/main/java/com/modularmc/mmclutils/schedule/TickScheduler.java index f680865..891b8be 100644 --- a/src/main/java/com/modularmc/mmclutils/schedule/TickScheduler.java +++ b/src/main/java/com/modularmc/mmclutils/schedule/TickScheduler.java @@ -291,8 +291,8 @@ void claim(Thread thread) { } public void forEachScope(Consumer action) { - Scope[] snapshot = Arrays.copyOf(roots, rootCount); - for (Scope root : snapshot) action.accept(root); + Scope[] rootsToVisit = Arrays.copyOf(roots, rootCount); + for (Scope root : rootsToVisit) action.accept(root); } int linkedCount() { From 5f3d81806a260a076d881a13af797cf9704d214c Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 02:19:48 +0800 Subject: [PATCH 09/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E7=89=A9=E5=93=81?= =?UTF-8?q?=E6=B5=81=E4=BD=93=E4=B8=8E=E5=BA=93=E5=AD=98=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AdjacentBlockCapabilityCache.java | 103 ++++++ .../mmclutils/fluid/FluidContainers.java | 29 ++ .../mmclutils/fluid/FluidStackStrategies.java | 113 +++++++ .../mmclutils/fluid/FluidStacks.java | 30 ++ .../mmclutils/fluid/FluidTransfers.java | 20 ++ .../mmclutils/inventory/InventoryQueries.java | 72 ++++ .../mmclutils/inventory/InventorySorting.java | 48 +++ .../inventory/InventoryTransfers.java | 41 +++ .../inventory/ResourceTransferSimulation.java | 77 +++++ .../item/CountedItemRequirement.java | 24 ++ .../mmclutils/item/IngredientMatching.java | 314 ++++++++++++++++++ .../mmclutils/item/ItemStackStrategies.java | 121 +++++++ .../modularmc/mmclutils/item/ItemStacks.java | 35 ++ .../mmclutils/item/ShapedRecipePatterns.java | 36 ++ 14 files changed, 1063 insertions(+) create mode 100644 src/main/java/com/modularmc/mmclutils/capability/AdjacentBlockCapabilityCache.java create mode 100644 src/main/java/com/modularmc/mmclutils/fluid/FluidContainers.java create mode 100644 src/main/java/com/modularmc/mmclutils/fluid/FluidStackStrategies.java create mode 100644 src/main/java/com/modularmc/mmclutils/fluid/FluidStacks.java create mode 100644 src/main/java/com/modularmc/mmclutils/fluid/FluidTransfers.java create mode 100644 src/main/java/com/modularmc/mmclutils/inventory/InventoryQueries.java create mode 100644 src/main/java/com/modularmc/mmclutils/inventory/InventorySorting.java create mode 100644 src/main/java/com/modularmc/mmclutils/inventory/InventoryTransfers.java create mode 100644 src/main/java/com/modularmc/mmclutils/inventory/ResourceTransferSimulation.java create mode 100644 src/main/java/com/modularmc/mmclutils/item/CountedItemRequirement.java create mode 100644 src/main/java/com/modularmc/mmclutils/item/IngredientMatching.java create mode 100644 src/main/java/com/modularmc/mmclutils/item/ItemStackStrategies.java create mode 100644 src/main/java/com/modularmc/mmclutils/item/ItemStacks.java create mode 100644 src/main/java/com/modularmc/mmclutils/item/ShapedRecipePatterns.java diff --git a/src/main/java/com/modularmc/mmclutils/capability/AdjacentBlockCapabilityCache.java b/src/main/java/com/modularmc/mmclutils/capability/AdjacentBlockCapabilityCache.java new file mode 100644 index 0000000..68a09eb --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/capability/AdjacentBlockCapabilityCache.java @@ -0,0 +1,103 @@ +package com.modularmc.mmclutils.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; + +/** + * Retains NeoForge capability caches for the six blocks adjacent to one fixed origin. + * + * @param capability value type + */ +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); + + /** + * Creates a lazily populated cache set whose listeners live only while the owning machine is valid. + * + * @param capability capability queried on adjacent blocks + * @param level server level that owns the target blocks + * @param origin fixed position of the querying machine + * @param isValid listener lifetime supplied by the owning machine + */ + public AdjacentBlockCapabilityCache( + BlockCapability capability, + ServerLevel level, + BlockPos origin, + BooleanSupplier isValid) { + this.capability = capability; + this.level = level; + this.origin = origin.immutable(); + this.isValid = isValid; + } + + /** + * Resolves the capability exposed toward the origin on one adjacent side. + * + * @param side direction from the origin to the target block + * @return current capability, or {@code null} when the target does not expose it + */ + @Nullable + public T get(Direction side) { + return this.caches.computeIfAbsent(side, this::createCache).getCapability(); + } + + /** + * Resolves all capabilities on the requested sides while preserving side iteration order. + * + * @param sides enabled target sides + * @return immutable list of currently exposed capabilities + */ + 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); + } + + /** + * Resolves capabilities together with their stable direction keys. + * + * @param sides enabled target 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/fluid/FluidContainers.java b/src/main/java/com/modularmc/mmclutils/fluid/FluidContainers.java new file mode 100644 index 0000000..b5e200c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/fluid/FluidContainers.java @@ -0,0 +1,29 @@ +package com.modularmc.mmclutils.fluid; + +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.transfer.ResourceHandler; +import net.neoforged.neoforge.transfer.access.ItemAccess; +import net.neoforged.neoforge.transfer.fluid.FluidResource; +import net.neoforged.neoforge.transfer.transaction.TransactionContext; + +import org.jspecify.annotations.Nullable; + +/** 通过 NeoForge 的物品访问修改容器,流体与原物品的替换在同一个事务中完成。 */ +public final class FluidContainers { + + private FluidContainers() {} + + public static int fill(ItemAccess item, ResourceHandler source, int tank, int maximum, + @Nullable TransactionContext parent) { + var access = item.oneByOne(); + var target = access.getCapability(Capabilities.Fluid.ITEM); + return target == null ? 0 : FluidTransfers.move(source, tank, target, maximum, parent); + } + + public static int drain(ItemAccess item, int tank, ResourceHandler target, int maximum, + @Nullable TransactionContext parent) { + var access = item.oneByOne(); + var source = access.getCapability(Capabilities.Fluid.ITEM); + return source == null ? 0 : FluidTransfers.move(source, tank, target, maximum, parent); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/fluid/FluidStackStrategies.java b/src/main/java/com/modularmc/mmclutils/fluid/FluidStackStrategies.java new file mode 100644 index 0000000..5103af9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/fluid/FluidStackStrategies.java @@ -0,0 +1,113 @@ +package com.modularmc.mmclutils.fluid; + +import net.neoforged.neoforge.fluids.FluidStack; + +import it.unimi.dsi.fastutil.Hash; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; + +/** + * A configurable generator of hashing strategies, allowing for consideration of select properties of FluidStacks when + * considering equality. + */ +public interface FluidStackStrategies extends Hash.Strategy { + + /** + * @return a builder object for producing a custom FluidStackStrategies. + */ + static FluidStackStrategies.FluidStackHashStrategyBuilder builder() { + return new FluidStackStrategies.FluidStackHashStrategyBuilder(); + } + + /** + * Generates an FluidStackHash configured to compare every aspect of FluidStacks. + * + * @return the FluidStackStrategies as described above. + */ + static FluidStackStrategies comparingAll() { + return builder().compareFluid(true) + .compareCount(true) + .compareComponents(true) + .build(); + } + + /** + * Generates an FluidStackHash configured to compare every aspect of FluidStacks except the amount + * of fluid in the stack. + * + * @return the FluidStackStrategies as described above. + */ + static FluidStackStrategies comparingAllButAmount() { + return builder().compareFluid(true) + .compareComponents(true) + .build(); + } + + /** + * Builder pattern class for generating customized FluidStackStrategies + */ + class FluidStackHashStrategyBuilder { + + private boolean fluid, amount, components; + + /** + * Defines whether the Fluid type should be considered for equality. + * + * @param choice {@code true} to consider this property, {@code false} to ignore it. + * @return {@code this} + */ + public FluidStackStrategies.FluidStackHashStrategyBuilder compareFluid(boolean choice) { + fluid = choice; + return this; + } + + /** + * Defines whether stack amount should be considered for equality. + * + * @param choice {@code true} to consider this property, {@code false} to ignore it. + * @return {@code this} + */ + public FluidStackStrategies.FluidStackHashStrategyBuilder compareCount(boolean choice) { + amount = choice; + return this; + } + + /** + * Defines whether Data Components should be considered for equality. + * + * @param choice {@code true} to consider this property, {@code false} to ignore it. + * @return {@code this} + */ + public FluidStackStrategies.FluidStackHashStrategyBuilder compareComponents(boolean choice) { + components = choice; + return this; + } + + /** + * @return the FluidStackStrategies as configured by "compare" methods. + */ + public FluidStackStrategies build() { + return new FluidStackStrategies() { + + @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/fluid/FluidStacks.java b/src/main/java/com/modularmc/mmclutils/fluid/FluidStacks.java new file mode 100644 index 0000000..ec78b89 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/fluid/FluidStacks.java @@ -0,0 +1,30 @@ +package com.modularmc.mmclutils.fluid; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.neoforged.neoforge.fluids.FluidStack; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; + +/** 根据注册表查询流体标识,或将总量拆成可由单个流体栈表示的数量。 */ +public final class FluidStacks { + + private FluidStacks() {} + + public static Identifier id(FluidStack stack) { + return BuiltInRegistries.FLUID.getKey(stack.getFluid()); + } + + public static List split(FluidStack stack, long amount) { + var result = new ObjectArrayList(); + if (stack.isEmpty()) return result; + while (amount > 0) { + int size = (int) Math.min(amount, Integer.MAX_VALUE); + result.add(stack.copyWithAmount(size)); + amount -= size; + } + return result; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/fluid/FluidTransfers.java b/src/main/java/com/modularmc/mmclutils/fluid/FluidTransfers.java new file mode 100644 index 0000000..fd00cd9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/fluid/FluidTransfers.java @@ -0,0 +1,20 @@ +package com.modularmc.mmclutils.fluid; + +import com.modularmc.mmclutils.inventory.InventoryTransfers; + +import net.neoforged.neoforge.transfer.ResourceHandler; +import net.neoforged.neoforge.transfer.fluid.FluidResource; +import net.neoforged.neoforge.transfer.transaction.TransactionContext; + +import org.jspecify.annotations.Nullable; + +/** 以相同事务转移流体及其组件。 */ +public final class FluidTransfers { + + private FluidTransfers() {} + + public static int move(ResourceHandler source, int tank, ResourceHandler target, + int maximum, @Nullable TransactionContext parent) { + return InventoryTransfers.move(source, tank, target, maximum, parent); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/inventory/InventoryQueries.java b/src/main/java/com/modularmc/mmclutils/inventory/InventoryQueries.java new file mode 100644 index 0000000..e21e5f6 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/inventory/InventoryQueries.java @@ -0,0 +1,72 @@ +package com.modularmc.mmclutils.inventory; + +import com.modularmc.mmclutils.fluid.FluidStackStrategies; +import com.modularmc.mmclutils.item.ItemStackStrategies; + +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.transfer.ResourceHandler; +import net.neoforged.neoforge.transfer.resource.Resource; + +import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenCustomHashMap; +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenCustomHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; + +/** 按资源及其组件汇总库存和栈集合。 */ +public final class InventoryQueries { + + private InventoryQueries() {} + + /** 按槽位顺序统计资源总量,保留各类资源首次出现的顺序。 */ + public static Object2LongMap count(ResourceHandler storage) { + return count(storage, true); + } + + public static Object2LongMap count(ResourceHandler storage, boolean ordered) { + Object2LongMap counts = ordered ? new Object2LongLinkedOpenHashMap<>() : new Object2LongOpenHashMap<>(); + for (int i = 0, slots = storage.size(); i < slots; i++) { + long amount = storage.getAmountAsLong(i); + if (amount == 0) continue; + R resource = storage.getResource(i); + counts.put(resource, Math.addExact(counts.getLong(resource), amount)); + } + return counts; + } + + public static Object2IntMap fromItemStackCollection(Iterable inputs) { + return fromItemStackCollection(inputs, false); + } + + public static Object2IntMap fromItemStackCollection(Iterable inputs, boolean linked) { + var counts = createItemStackMap(linked); + for (ItemStack stack : inputs) { + if (!stack.isEmpty()) counts.mergeInt(stack.copyWithCount(1), stack.getCount(), Math::addExact); + } + return counts; + } + + public static Object2IntMap createItemStackMap(boolean linked) { + ItemStackStrategies strategy = ItemStackStrategies.comparingAllButCount(); + return linked ? new Object2IntLinkedOpenCustomHashMap<>(strategy) : new Object2IntOpenCustomHashMap<>(strategy); + } + + public static Object2IntMap fromFluidCollection(Iterable inputs) { + return fromFluidCollection(inputs, true); + } + + public static Object2IntMap fromFluidCollection(Iterable inputs, boolean linked) { + var counts = createFluidStackMap(linked); + for (FluidStack stack : inputs) { + if (!stack.isEmpty()) counts.mergeInt(stack.copyWithAmount(1), stack.getAmount(), Math::addExact); + } + return counts; + } + + public static Object2IntMap createFluidStackMap(boolean linked) { + FluidStackStrategies strategy = FluidStackStrategies.comparingAllButAmount(); + return linked ? new Object2IntLinkedOpenCustomHashMap<>(strategy) : new Object2IntOpenCustomHashMap<>(strategy); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/inventory/InventorySorting.java b/src/main/java/com/modularmc/mmclutils/inventory/InventorySorting.java new file mode 100644 index 0000000..68b3948 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/inventory/InventorySorting.java @@ -0,0 +1,48 @@ +package com.modularmc.mmclutils.inventory; + +import net.neoforged.neoforge.transfer.ResourceHandler; +import net.neoforged.neoforge.transfer.item.ItemResource; +import net.neoforged.neoforge.transfer.transaction.Transaction; +import net.neoforged.neoforge.transfer.transaction.TransactionContext; + +import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jspecify.annotations.Nullable; + +import java.util.Comparator; + +/** 汇总同类物品并按调用方给定的顺序重排。任何槽位操作失败时回滚。 */ +public final class InventorySorting { + + private InventorySorting() {} + + public static boolean sort(ResourceHandler inventory, Comparator order, + @Nullable TransactionContext parent) { + var amounts = new Object2LongLinkedOpenHashMap(); + try (Transaction transaction = Transaction.open(parent)) { + for (int slot = 0; slot < inventory.size(); slot++) { + ItemResource resource = inventory.getResource(slot); + long remaining = inventory.getAmountAsLong(slot); + if (resource.isEmpty() || remaining == 0) continue; + amounts.addTo(resource, remaining); + while (remaining > 0) { + int amount = (int) Math.min(Integer.MAX_VALUE, remaining); + if (inventory.extract(slot, resource, amount, transaction) != amount) return false; + remaining -= amount; + } + } + var resources = new ObjectArrayList<>(amounts.keySet()); + resources.sort(order); + for (ItemResource resource : resources) { + long remaining = amounts.getLong(resource); + for (int slot = 0; slot < inventory.size() && remaining > 0; slot++) { + int inserted = inventory.insert(slot, resource, (int) Math.min(Integer.MAX_VALUE, remaining), transaction); + remaining -= inserted; + } + if (remaining != 0) return false; + } + transaction.commit(); + return true; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/inventory/InventoryTransfers.java b/src/main/java/com/modularmc/mmclutils/inventory/InventoryTransfers.java new file mode 100644 index 0000000..1589118 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/inventory/InventoryTransfers.java @@ -0,0 +1,41 @@ +package com.modularmc.mmclutils.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; + +/** 在同一事务内转移资源,目标接收失败时恢复源槽位。 */ +public final class InventoryTransfers { + + private InventoryTransfers() {} + + public static int move(ResourceHandler source, int sourceSlot, ResourceHandler target, + int maximum, @Nullable TransactionContext parent) { + if (maximum < 0) throw new IllegalArgumentException("转移数量应为非负数"); + if (source == target || maximum == 0) return 0; + R resource = source.getResource(sourceSlot); + if (resource.isEmpty()) return 0; + try (Transaction transaction = Transaction.open(parent)) { + int removed; + int accepted; + try (Transaction attempt = Transaction.open(transaction)) { + removed = source.extract(sourceSlot, resource, maximum, attempt); + if (removed == 0) return 0; + accepted = target.insert(resource, removed, attempt); + if (accepted == removed) { + attempt.commit(); + } + } + if (accepted == 0) return 0; + if (accepted < removed) { + if (source.extract(sourceSlot, resource, accepted, transaction) != accepted) return 0; + if (target.insert(resource, accepted, transaction) != accepted) return 0; + } + transaction.commit(); + return accepted; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/inventory/ResourceTransferSimulation.java b/src/main/java/com/modularmc/mmclutils/inventory/ResourceTransferSimulation.java new file mode 100644 index 0000000..a138c2a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/inventory/ResourceTransferSimulation.java @@ -0,0 +1,77 @@ +package com.modularmc.mmclutils.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 限定作用范围。 + */ +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); + } + + /** 按存储的插入顺序尝试插入,返回成功量。 */ + 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/item/CountedItemRequirement.java b/src/main/java/com/modularmc/mmclutils/item/CountedItemRequirement.java new file mode 100644 index 0000000..c83de2a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/item/CountedItemRequirement.java @@ -0,0 +1,24 @@ +package com.modularmc.mmclutils.item; + +import net.minecraft.world.item.crafting.Ingredient; + +/** + * Describes one item ingredient and the number of matching items consumed by a recipe. + * + *

+ * Implementations own their validation and persistence format. This contract only supplies the common matching + * view used by recipe machines; it does not define a physical slot or a reservation lifetime. + *

+ */ +public interface CountedItemRequirement { + + /** + * Returns the ingredient predicate applied to an aggregated item stack. + */ + Ingredient ingredient(); + + /** + * Returns the positive number of items consumed for this requirement. + */ + int count(); +} diff --git a/src/main/java/com/modularmc/mmclutils/item/IngredientMatching.java b/src/main/java/com/modularmc/mmclutils/item/IngredientMatching.java new file mode 100644 index 0000000..280b986 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/item/IngredientMatching.java @@ -0,0 +1,314 @@ +package com.modularmc.mmclutils.item; + +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; + +/** + * Matches counted item requirements against physical input slots. + * + *

+ * This item-only matcher aggregates stacks with the same item and data components before matching. Fluid and AE key + * resources are matched by their own resource-key aggregation in the recipe implementations. The matcher keeps the + * physical slot amounts in its result so a caller can reserve or consume the exact source slots after the logical + * match succeeds. Every non-empty item input must still be accepted by at least one requirement; an accepted extra + * stack may remain in the machine when the logical requirement was already satisfied by another stack. + *

+ */ +public final class IngredientMatching { + + private IngredientMatching() {} + + /** + * Matches all counted requirements and returns the physical amounts consumed from each input slot. + * + * @return a non-empty assignment for a successful non-empty recipe, an empty assignment when both sides have no + * item inputs, or {@code null} when the requirements cannot be satisfied without an unrecognized input + */ + public static @Nullable ObjectList match( + Iterable requirements, + ObjectList inputs) { + ObjectList normalized = new ObjectArrayList<>(); + for (CountedItemRequirement 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++) { + CountedItemRequirement 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); + } + + /** + * Matches one ingredient whose required amount may be split across several physical slots. + */ + public static @Nullable ObjectList match(Ingredient ingredient, int count, + ObjectList inputs) { + return match(ObjectLists.singleton(new Requirement(ingredient, count)), inputs); + } + + /** Maps physical assignments to a recipe-specific slot type without copying the assignment list twice. */ + 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 (CountedItemRequirement requirement : requirements) { + if (requirement.ingredient().test(stack)) { + return true; + } + } + return false; + } + + /** + * One ingredient and the total number of items required for it. + */ + public record Requirement(Ingredient ingredient, int count) implements CountedItemRequirement { + + 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); + } + } + } + + /** + * One physical input slot and the amount consumed from it. + */ + 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/item/ItemStackStrategies.java b/src/main/java/com/modularmc/mmclutils/item/ItemStackStrategies.java new file mode 100644 index 0000000..b9d2628 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/item/ItemStackStrategies.java @@ -0,0 +1,121 @@ +package com.modularmc.mmclutils.item; + +import net.minecraft.world.item.ItemStack; + +import it.unimi.dsi.fastutil.Hash; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; + +/** + * A configurable generator of hashing strategies, allowing for consideration of select properties of ItemStacks when + * considering equality. + */ +public interface ItemStackStrategies extends Hash.Strategy { + + /** + * @return a builder object for producing a custom ItemStackStrategies. + */ + static ItemStackHashStrategyBuilder builder() { + return new ItemStackHashStrategyBuilder(); + } + + /** + * Generates an ItemStackHash configured to compare every aspect of ItemStacks. + * + * @return the ItemStackStrategies as described above. + */ + static ItemStackStrategies comparingAll() { + return ItemStackHashStrategyBuilder.ALL; + } + + /** + * Generates an ItemStackHash configured to compare every aspect of ItemStacks except the number + * of items in the stack. + * + * @return the ItemStackStrategies as described above. + */ + static ItemStackStrategies comparingAllButCount() { + return ItemStackHashStrategyBuilder.ITEM_AND_TAG; + } + + static ItemStackStrategies comparingItem() { + return ItemStackHashStrategyBuilder.ITEM; + } + + /** + * Builder pattern class for generating customized ItemStackStrategies + */ + class ItemStackHashStrategyBuilder { + + private static final ItemStackStrategies ALL = builder().compareItem(true) + .compareCount(true) + .compareComponents(true) + .build(); + private static final ItemStackStrategies ITEM_AND_TAG = builder().compareItem(true) + .compareComponents(true) + .build(); + private static final ItemStackStrategies ITEM = builder().compareItem(true).build(); + + private boolean item, count, components; + + /** + * Defines whether the Item type should be considered for equality. + * + * @param choice {@code true} to consider this property, {@code false} to ignore it. + * @return {@code this} + */ + public ItemStackHashStrategyBuilder compareItem(boolean choice) { + item = choice; + return this; + } + + /** + * Defines whether stack size should be considered for equality. + * + * @param choice {@code true} to consider this property, {@code false} to ignore it. + * @return {@code this} + */ + public ItemStackHashStrategyBuilder compareCount(boolean choice) { + count = choice; + return this; + } + + /** + * Defines whether Data Components should be considered for equality. + * + * @param choice {@code true} to consider this property, {@code false} to ignore it. + * @return {@code this} + */ + public ItemStackHashStrategyBuilder compareComponents(boolean choice) { + components = choice; + return this; + } + + /** + * @return the ItemStackStrategies as configured by "compare" methods. + */ + public ItemStackStrategies build() { + return new ItemStackStrategies() { + + @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/item/ItemStacks.java b/src/main/java/com/modularmc/mmclutils/item/ItemStacks.java new file mode 100644 index 0000000..05e334f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/item/ItemStacks.java @@ -0,0 +1,35 @@ +package com.modularmc.mmclutils.item; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.ItemStack; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; + +/** 比较和拆分物品栈,保留物品组件。 */ +public final class ItemStacks { + + private ItemStacks() {} + + public static Identifier id(ItemStack stack) { + return BuiltInRegistries.ITEM.getKey(stack.getItem()); + } + + public static List split(ItemStack stack, long amount) { + var result = new ObjectArrayList(); + if (stack.isEmpty()) return result; + int maximum = stack.getMaxStackSize(); + while (amount > 0) { + int size = (int) Math.min(amount, maximum); + result.add(stack.copyWithCount(size)); + amount -= size; + } + return result; + } + + public static boolean matches(ItemStack first, ItemStack second) { + return first.getCount() == second.getCount() && ItemStack.isSameItemSameComponents(first, second); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/item/ShapedRecipePatterns.java b/src/main/java/com/modularmc/mmclutils/item/ShapedRecipePatterns.java new file mode 100644 index 0000000..b398154 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/item/ShapedRecipePatterns.java @@ -0,0 +1,36 @@ +package com.modularmc.mmclutils.item; + +import net.minecraft.world.item.crafting.Ingredient; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** 将原版有序材料表转换为带稳定字符键的配方图案。 */ +public final class ShapedRecipePatterns { + + private ShapedRecipePatterns() {} + + public static Pattern of(List> ingredients, int width, int height) { + if (width <= 0 || height <= 0 || (long) width * height != ingredients.size()) { + throw new IllegalArgumentException("配方尺寸与材料数量不匹配"); + } + Map keys = new LinkedHashMap<>(); + List rows = new ArrayList<>(height); + for (int y = 0; y < height; y++) { + var line = new StringBuilder(width); + for (int x = 0; x < width; x++) { + var input = ingredients.get(y * width + x); + line.append(input.isEmpty() ? ' ' : keys.computeIfAbsent(input.orElseThrow(), ignored -> (char) ('A' + keys.size()))); + } + rows.add(line.toString()); + } + Map keyMap = new LinkedHashMap<>(); + keys.forEach((ingredient, key) -> keyMap.put(key, ingredient)); + return new Pattern(List.copyOf(rows), Map.copyOf(keyMap)); + } + + public record Pattern(List rows, Map keys) {} +} From ff2d29d005642c101f2b4cd723b4a664f4605c77 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 02:21:01 +0800 Subject: [PATCH 10/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E4=B8=96=E7=95=8C?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E4=B8=8E=E5=9F=BA=E7=A1=80=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../modularmc/mmclutils/color/ColorMath.java | 61 ++++ .../mmclutils/config/PatternRules.java | 87 +++++ .../mmclutils/entity/EntityEquipment.java | 30 ++ .../mmclutils/entity/EntityQueries.java | 23 ++ .../mmclutils/entity/EntityTeleports.java | 19 ++ .../com/modularmc/mmclutils/io/Digests.java | 18 + .../mmclutils/level/AreaBlockActions.java | 134 ++++++++ .../mmclutils/level/BlockEnvironment.java | 43 +++ .../mmclutils/level/LevelQueries.java | 19 ++ .../mmclutils/math/NumberExpressions.java | 203 ++++++++++++ .../modularmc/mmclutils/math/NumberMath.java | 157 +++++++++ .../mmclutils/math/RandomSampling.java | 22 ++ .../mmclutils/math/WeightedSelection.java | 48 +++ .../mixin/spatial/VoxelShapeAccessor.java | 20 ++ .../mmclutils/redstone/RedstoneSignals.java | 87 +++++ .../mmclutils/registry/RegistryEntries.java | 20 ++ .../mmclutils/registry/TagExpression.java | 312 ++++++++++++++++++ .../modularmc/mmclutils/registry/TagKeys.java | 26 ++ .../mmclutils/registry/TriState.java | 102 ++++++ .../mmclutils/resource/ResourcePaths.java | 23 ++ .../mmclutils/serialization/BinaryCodecs.java | 63 ++++ .../mmclutils/serialization/Codecs.java | 27 ++ .../serialization/CollectionCodecs.java | 46 +++ .../mmclutils/serialization/StackCodecs.java | 33 ++ .../mmclutils/serialization/StreamCodecs.java | 222 +++++++++++++ .../mmclutils/serialization/TypeTokens.java | 30 ++ .../mmclutils/spatial/BlockDirections.java | 25 ++ .../mmclutils/spatial/BlockSearch.java | 139 ++++++++ .../mmclutils/spatial/GlobalPositions.java | 17 + .../mmclutils/spatial/VoxelContours.java | 94 ++++++ .../mmclutils/spatial/VoxelContoursShape.java | 52 +++ .../mmclutils/spatial/VoxelShapes.java | 104 ++++++ .../modularmc/mmclutils/text/Components.java | 34 ++ .../mmclutils/text/NumberFormats.java | 170 ++++++++++ .../modularmc/mmclutils/text/TextFormats.java | 31 ++ .../modularmc/mmclutils/text/TextSearch.java | 51 +++ src/main/resources/mmclutils.mixins.json | 3 +- 37 files changed, 2594 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/modularmc/mmclutils/color/ColorMath.java create mode 100644 src/main/java/com/modularmc/mmclutils/config/PatternRules.java create mode 100644 src/main/java/com/modularmc/mmclutils/entity/EntityEquipment.java create mode 100644 src/main/java/com/modularmc/mmclutils/entity/EntityQueries.java create mode 100644 src/main/java/com/modularmc/mmclutils/entity/EntityTeleports.java create mode 100644 src/main/java/com/modularmc/mmclutils/io/Digests.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/AreaBlockActions.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/BlockEnvironment.java create mode 100644 src/main/java/com/modularmc/mmclutils/level/LevelQueries.java create mode 100644 src/main/java/com/modularmc/mmclutils/math/NumberExpressions.java create mode 100644 src/main/java/com/modularmc/mmclutils/math/NumberMath.java create mode 100644 src/main/java/com/modularmc/mmclutils/math/RandomSampling.java create mode 100644 src/main/java/com/modularmc/mmclutils/math/WeightedSelection.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/spatial/VoxelShapeAccessor.java create mode 100644 src/main/java/com/modularmc/mmclutils/redstone/RedstoneSignals.java create mode 100644 src/main/java/com/modularmc/mmclutils/registry/RegistryEntries.java create mode 100644 src/main/java/com/modularmc/mmclutils/registry/TagExpression.java create mode 100644 src/main/java/com/modularmc/mmclutils/registry/TagKeys.java create mode 100644 src/main/java/com/modularmc/mmclutils/registry/TriState.java create mode 100644 src/main/java/com/modularmc/mmclutils/resource/ResourcePaths.java create mode 100644 src/main/java/com/modularmc/mmclutils/serialization/BinaryCodecs.java create mode 100644 src/main/java/com/modularmc/mmclutils/serialization/Codecs.java create mode 100644 src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java create mode 100644 src/main/java/com/modularmc/mmclutils/serialization/StackCodecs.java create mode 100644 src/main/java/com/modularmc/mmclutils/serialization/StreamCodecs.java create mode 100644 src/main/java/com/modularmc/mmclutils/serialization/TypeTokens.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/BlockSearch.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/GlobalPositions.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/VoxelShapes.java create mode 100644 src/main/java/com/modularmc/mmclutils/text/Components.java create mode 100644 src/main/java/com/modularmc/mmclutils/text/NumberFormats.java create mode 100644 src/main/java/com/modularmc/mmclutils/text/TextFormats.java create mode 100644 src/main/java/com/modularmc/mmclutils/text/TextSearch.java diff --git a/src/main/java/com/modularmc/mmclutils/color/ColorMath.java b/src/main/java/com/modularmc/mmclutils/color/ColorMath.java new file mode 100644 index 0000000..cc3d5d5 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/color/ColorMath.java @@ -0,0 +1,61 @@ +package com.modularmc.mmclutils.color; + +import net.minecraft.util.ARGB; +import net.minecraft.util.Mth; + +/** 颜色分量、颜色空间和分段渐变。颜色按 ARGB 打包。 */ +public final class ColorMath { + + private ColorMath() {} + + public static int withAlpha(int rgb, int alpha) { + return ARGB.color(alpha, rgb); + } + + 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.color(ARGB.alpha(argb), ARGB.blue(argb), ARGB.green(argb), ARGB.red(argb)); + } + + 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); + } + + 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)); + } + + 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)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/config/PatternRules.java b/src/main/java/com/modularmc/mmclutils/config/PatternRules.java new file mode 100644 index 0000000..19614d9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/config/PatternRules.java @@ -0,0 +1,87 @@ +package com.modularmc.mmclutils.config; + +import com.modularmc.mmclutils.math.NumberExpressions; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; +import java.util.regex.Pattern; + +/** Parses and evaluates reusable regular-expression configuration rules. */ +public final class PatternRules { + + private PatternRules() {} + + 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("Data Ripper blacklist regex must not be blank"); + } + patterns.add(Pattern.compile(entry)); + } + return List.copyOf(patterns); + } + + 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("Data Ripper multiplier must use pattern=value: " + entry); + } + String patternText = entry.substring(0, separator).trim(); + String valueText = entry.substring(separator + 1).trim(); + if (patternText.isEmpty()) { + throw new IllegalArgumentException("Data Ripper multiplier regex must not be blank: " + entry); + } + double value = NumberExpressions.parseDouble(valueText) + .orElseThrow(() -> new IllegalArgumentException("Invalid Data Ripper multiplier: " + entry)); + if (value <= 0.0D) { + throw new IllegalArgumentException("Data Ripper multiplier must be finite and positive: " + 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("Data Ripper multiplier patterns and values must have equal lengths"); + } + 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("Data Ripper multiplier pattern must not be blank"); + } + double value = values[index]; + if (!Double.isFinite(value) || value <= 0.0D) { + throw new IllegalArgumentException("Data Ripper multiplier must be finite and positive"); + } + 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/entity/EntityEquipment.java b/src/main/java/com/modularmc/mmclutils/entity/EntityEquipment.java new file mode 100644 index 0000000..52d5144 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/entity/EntityEquipment.java @@ -0,0 +1,30 @@ +package com.modularmc.mmclutils.entity; + +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; + +import java.util.function.Predicate; + +/** 按原版装备槽判断一个实体佩戴的物品。 */ +public final class EntityEquipment { + + private static final EquipmentSlot[] ARMOR = { + EquipmentSlot.HEAD, EquipmentSlot.CHEST, EquipmentSlot.LEGS, EquipmentSlot.FEET + }; + + private EntityEquipment() {} + + public static boolean armorMatches(LivingEntity entity, Predicate condition) { + for (EquipmentSlot slot : ARMOR) { + if (!condition.test(entity.getItemBySlot(slot))) return false; + } + return true; + } + + public static int matchingArmorPieces(LivingEntity entity, Predicate condition) { + int count = 0; + for (EquipmentSlot slot : ARMOR) if (condition.test(entity.getItemBySlot(slot))) count++; + return count; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/entity/EntityQueries.java b/src/main/java/com/modularmc/mmclutils/entity/EntityQueries.java new file mode 100644 index 0000000..6fcadf7 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/entity/EntityQueries.java @@ -0,0 +1,23 @@ +package com.modularmc.mmclutils.entity; + +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.util.List; +import java.util.function.Predicate; + +/** 使用原版空间索引查询实体,可用半径进一步限制结果。 */ +public final class EntityQueries { + + private EntityQueries() {} + + public static List within(Level level, Class type, Vec3 center, double radius, + Predicate condition) { + if (!(radius >= 0)) throw new IllegalArgumentException("半径须为非负数"); + double limit = radius * radius; + return level.getEntitiesOfClass(type, AABB.ofSize(center, radius * 2, radius * 2, radius * 2), + entity -> entity.distanceToSqr(center) <= limit && condition.test(entity)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/entity/EntityTeleports.java b/src/main/java/com/modularmc/mmclutils/entity/EntityTeleports.java new file mode 100644 index 0000000..367d355 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/entity/EntityTeleports.java @@ -0,0 +1,19 @@ +package com.modularmc.mmclutils.entity; + +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.portal.TeleportTransition; +import net.minecraft.world.phys.Vec3; + +import org.jspecify.annotations.Nullable; + +/** 通过原版传送流程更换实体所在的维度和坐标。 */ +public final class EntityTeleports { + + private EntityTeleports() {} + + public static @Nullable Entity teleport(Entity entity, ServerLevel level, Vec3 position) { + return entity.teleport(new TeleportTransition(level, position, entity.getDeltaMovement(), entity.getYRot(), + entity.getXRot(), TeleportTransition.DO_NOTHING)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/io/Digests.java b/src/main/java/com/modularmc/mmclutils/io/Digests.java new file mode 100644 index 0000000..5481c1c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/io/Digests.java @@ -0,0 +1,18 @@ +package com.modularmc.mmclutils.io; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Creates stable SHA-256 identifiers without exposing server addresses or filesystem paths in client config. */ +public final class Digests { + + private Digests() {} + + /** Hashes the exact UTF-8 value and prefixes the lower-case digest with its algorithm. */ + public static String sha256(String value) throws NoSuchAlgorithmException { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return "sha256:" + HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/level/AreaBlockActions.java b/src/main/java/com/modularmc/mmclutils/level/AreaBlockActions.java new file mode 100644 index 0000000..dddb774 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/AreaBlockActions.java @@ -0,0 +1,134 @@ +package com.modularmc.mmclutils.level; + +import com.modularmc.mmclutils.schedule.Cadence; +import com.modularmc.mmclutils.schedule.Schedulers; +import com.modularmc.mmclutils.schedule.Task; +import com.modularmc.mmclutils.spatial.BlockSearch; + +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/level/BlockEnvironment.java b/src/main/java/com/modularmc/mmclutils/level/BlockEnvironment.java new file mode 100644 index 0000000..d3a6000 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/BlockEnvironment.java @@ -0,0 +1,43 @@ +package com.modularmc.mmclutils.level; + +import net.minecraft.core.BlockPos; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.FluidTags; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +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.block.state.properties.BlockStateProperties; + +/** 根据原版材质、光源和生物群系估算相对表面温度。 */ +public final class BlockEnvironment { + + private BlockEnvironment() {} + + public static int temperature(BlockState state, Level level, BlockPos position) { + if (state.getFluidState().is(FluidTags.LAVA) || state.is(BlockTags.FIRE) || state.is(Blocks.MAGMA_BLOCK)) return 255; + if (state.is(BlockTags.ICE) || state.is(BlockTags.SNOW) || state.getFluidState().is(FluidTags.WATER)) return 12; + if (state.hasProperty(BlockStateProperties.LIT) && state.getValue(BlockStateProperties.LIT)) return 235; + int light = state.getLightEmission(level, position); + if (light > 0) return 128 + light * 7; + int ambient = ambient(level, position); + if (state.is(BlockTags.LEAVES)) return ambient - 8; + if (state.is(BlockTags.SAND)) return ambient + 6; + return ambient; + } + + public static int ambient(Level level, BlockPos position) { + return 86 + Math.round(Mth.clamp(level.getBiome(position).value().getBaseTemperature(), -0.5f, 2) * 22); + } + + public static int temperature(Entity entity) { + return entity.isOnFire() ? 255 : entity instanceof LivingEntity ? 218 : ambient(entity.level(), entity.blockPosition()); + } + + /** 判断实体本身是否作为热源。 */ + public static boolean hasHeat(Entity entity) { + return entity instanceof LivingEntity || entity.isOnFire(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/level/LevelQueries.java b/src/main/java/com/modularmc/mmclutils/level/LevelQueries.java new file mode 100644 index 0000000..a16a768 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/level/LevelQueries.java @@ -0,0 +1,19 @@ +package com.modularmc.mmclutils.level; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; + +/** 与世界、维度和天气有关的只读计算。 */ +public final class LevelQueries { + + private LevelQueries() {} + + public static boolean canSeeSunClearly(Level level, BlockPos pos) { + return level.dimensionType().hasSkyLight() && level.canSeeSky(pos) && !level.isRaining() && !level.isThundering(); + } + + public static double sunIntensity(long dayTime) { + long time = Math.floorMod(dayTime, 24000); + return time < 12000 ? Math.sin(Math.PI * time / 12000) : 0; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/math/NumberExpressions.java b/src/main/java/com/modularmc/mmclutils/math/NumberExpressions.java new file mode 100644 index 0000000..047a826 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/math/NumberExpressions.java @@ -0,0 +1,203 @@ +package com.modularmc.mmclutils.math; + +import org.jspecify.annotations.NullMarked; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.util.Locale; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; + +/** Shared numeric-input parser; integer quantities remain exact while decimal settings use DECIMAL128 division. */ +@NullMarked +public final class NumberExpressions { + + private NumberExpressions() {} + + /** Accepts a positive integral amount, including unit suffixes and arithmetic; invalid input returns empty. */ + public static OptionalLong parse(String input) { + return parseLong(input, 1, Long.MAX_VALUE); + } + + /** Accepts any positive exact integral quantity without narrowing it to a primitive numeric type. */ + public static Optional parseUnboundedPositiveInteger(String input) { + var result = evaluate(input, MathContext.UNLIMITED); + if (result.isEmpty()) return Optional.empty(); + BigDecimal value = result.get().stripTrailingZeros(); + if (value.signum() <= 0 || value.scale() > 0) return Optional.empty(); + try { + return Optional.of(value.toBigIntegerExact()); + } catch (ArithmeticException invalidInteger) { + return Optional.empty(); + } + } + + /** + * Stock settings allow zero for clearing and retain fractional resource units only when they represent whole base + * units. The unit size must be positive; invalid input returns empty. + */ + public static OptionalLong parseStockAmount(String input, long amountPerUnit) { + if (amountPerUnit <= 0) throw new IllegalArgumentException("Amount per unit must be positive"); + var result = evaluate(input, MathContext.UNLIMITED); + return result.map(bigDecimal -> boundedLong(bigDecimal.multiply(BigDecimal.valueOf(amountPerUnit)), 0, Long.MAX_VALUE)).orElseGet(OptionalLong::empty); + } + + /** Evaluates a signed integral expression within inclusive bounds; reversed bounds are a caller error. */ + public static OptionalLong parseLong(String input, long minimum, long maximum) { + if (minimum > maximum) throw new IllegalArgumentException("Minimum amount exceeds maximum"); + var result = evaluate(input, MathContext.UNLIMITED); + return result.map(bigDecimal -> boundedLong(bigDecimal, minimum, maximum)).orElseGet(OptionalLong::empty); + } + + /** Evaluates a signed integral expression within the caller's inclusive int bounds. */ + public static OptionalInt parseInt(String input, int minimum, int maximum) { + var value = parseLong(input, minimum, maximum); + return value.isPresent() ? OptionalInt.of((int) value.getAsLong()) : OptionalInt.empty(); + } + + /** Evaluates a decimal expression and rejects non-finite double results. */ + public static OptionalDouble parseDouble(String input) { + var result = evaluate(input, MathContext.DECIMAL128); + if (result.isEmpty()) return OptionalDouble.empty(); + double value = result.get().doubleValue(); + return Double.isFinite(value) ? OptionalDouble.of(value) : OptionalDouble.empty(); + } + + /** Evaluates a decimal expression within the finite float range. */ + public static Optional parseFloat(String input) { + var result = evaluate(input, MathContext.DECIMAL128); + if (result.isEmpty()) return Optional.empty(); + float value = result.get().floatValue(); + return Float.isFinite(value) ? Optional.of(value) : Optional.empty(); + } + + private static Optional evaluate(String input, MathContext divisionContext) { + try { + return Optional.of(new Parser(input, divisionContext).parse()); + } catch (IllegalArgumentException | ArithmeticException invalidExpression) { + return Optional.empty(); + } + } + + private static OptionalLong boundedLong(BigDecimal value, long minimum, long maximum) { + if (value.compareTo(BigDecimal.valueOf(minimum)) < 0 || value.compareTo(BigDecimal.valueOf(maximum)) > 0 || + value.stripTrailingZeros().scale() > 0) + return OptionalLong.empty(); + return OptionalLong.of(value.longValueExact()); + } + + private static final class Parser { + + private final String s; + private final MathContext divisionContext; + private int p; + + Parser(String input, MathContext divisionContext) { + this.divisionContext = divisionContext; + var normalized = input.trim(); + if (normalized.startsWith("=")) { + normalized = normalized.substring(1); + } + s = normalized.replace(" ", "").toLowerCase(Locale.ROOT); + } + + BigDecimal parse() { + BigDecimal v = expression(); + if (p != s.length()) throw new IllegalArgumentException(); + return v; + } + + BigDecimal expression() { + BigDecimal v = term(); + while (p < s.length()) { + char c = s.charAt(p); + if (c == '+') { + p++; + v = v.add(term()); + } else if (c == '-') { + p++; + v = v.subtract(term()); + } else break; + } + return v; + } + + BigDecimal term() { + BigDecimal v = unary(); + while (p < s.length()) { + char c = s.charAt(p); + if (c == '*') { + p++; + v = v.multiply(unary()); + } else if (c == '/') { + p++; + BigDecimal d = unary(); + if (d.signum() == 0) throw new ArithmeticException(); + v = v.divide(d, divisionContext); + } else if (c == '(' || Character.isDigit(c) || c == '.') { + v = v.multiply(unary()); + } else break; + } + return v; + } + + BigDecimal unary() { + if (p < s.length() && (s.charAt(p) == '+' || s.charAt(p) == '-')) { + boolean negative = s.charAt(p++) == '-'; + BigDecimal value = unary(); + return negative ? value.negate() : value; + } + return power(); + } + + BigDecimal power() { + BigDecimal v = primary(); + if (p < s.length() && s.charAt(p) == '^') { + p++; + int n = unary().intValueExact(); + v = v.pow(n); + } + return v; + } + + BigDecimal primary() { + if (p < s.length() && s.charAt(p) == '(') { + p++; + BigDecimal v = expression(); + if (p >= s.length() || s.charAt(p++) != ')') throw new IllegalArgumentException(); + return v; + } + int st = p; + while (p < s.length() && (Character.isDigit(s.charAt(p)) || s.charAt(p) == '.')) p++; + if (st == p) throw new IllegalArgumentException(); + if (p < s.length() && s.charAt(p) == 'e' && p + 1 < s.length() && (Character.isDigit(s.charAt(p + 1)) || s.charAt(p + 1) == '+' || s.charAt(p + 1) == '-')) { + p++; + if (p < s.length() && (s.charAt(p) == '+' || s.charAt(p) == '-')) p++; + int es = p; + while (p < s.length() && Character.isDigit(s.charAt(p))) p++; + if (es == p) throw new IllegalArgumentException(); + } + BigDecimal v = new BigDecimal(s.substring(st, p)); + if (p < s.length()) { + char u = s.charAt(p); + long m = switch (u) { + case 'k' -> 1_000L; + case 'm' -> 1_000_000L; + case 'g' -> 1_000_000_000L; + case 't' -> 1_000_000_000_000L; + case 'p' -> 1_000_000_000_000_000L; + case 'e' -> 1_000_000_000_000_000_000L; + default -> 0L; + }; + if (m != 0) { + p++; + v = v.multiply(BigDecimal.valueOf(m)); + } + } + return v; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/math/NumberMath.java b/src/main/java/com/modularmc/mmclutils/math/NumberMath.java new file mode 100644 index 0000000..f38a28b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/math/NumberMath.java @@ -0,0 +1,157 @@ +package com.modularmc.mmclutils.math; + +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.fluids.FluidStack; + +import com.mojang.datafixers.util.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.NotNull; +import org.joml.Vector3f; +import org.jspecify.annotations.Nullable; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class NumberMath { + + public static long clamp(long value, long min, long max) { + return Math.max(min, Math.min(max, value)); + } + + public static int lerpInt(double delta, int start, int end) { + return start + Mth.floor(delta * (end - start)); + } + + public static List splitStacks(ItemStack stack, long amount) { + int fullStacks = (int) (amount / Integer.MAX_VALUE); + int rem = (int) (amount % Integer.MAX_VALUE); + List stacks = new ObjectArrayList<>(fullStacks + 1); + if (fullStacks > 0) stacks.addAll(Collections.nCopies(fullStacks, stack.copyWithCount(Integer.MAX_VALUE))); + if (rem > 0) stacks.add(stack.copyWithCount(rem)); + return stacks; + } + + public static List splitFluidStacks(FluidStack stack, long amount) { + int fullStacks = (int) (amount / Integer.MAX_VALUE); + int rem = (int) (amount % Integer.MAX_VALUE); + List stacks = new ObjectArrayList<>(fullStacks + 1); + if (fullStacks > 0) { + var copy = stack.copy(); + copy.setAmount(Integer.MAX_VALUE); + stacks.addAll(Collections.nCopies(fullStacks, copy)); + } + if (rem > 0) { + var copy = stack.copy(); + copy.setAmount(rem); + stacks.add(copy); + } + return stacks; + } + + public static int[] split(long value) { + IntArrayList result = new IntArrayList(); + while (value > 0) { + int intValue = (int) Math.min(value, Integer.MAX_VALUE); + result.add(intValue); + value -= intValue; + } + return result.toIntArray(); + } + + public static int saturatedCast(long value) { + if (value > 2147483647L) { + return Integer.MAX_VALUE; + } else { + return value < -2147483648L ? Integer.MIN_VALUE : (int) value; + } + } + + public static int hashInts(int... vals) { + return Arrays.hashCode(vals); + } + + public static int hashLongs(long... vals) { + return Arrays.hashCode(vals); + } + + public static float ratio(BigInteger a, BigInteger b) { + return new BigDecimal(a).divide(new BigDecimal(b), MathContext.DECIMAL32).floatValue(); + } + + public static int ceilDiv(int x, int y) { + final int q = x / y; + // if the signs are the same and modulo not zero, round up + if ((x ^ y) >= 0 && (q * y != x)) { + return q + 1; + } + return q; + } + + public static float min(float @NotNull... values) { + // noinspection ConstantValue + if (values == null || values.length == 0) throw new IllegalArgumentException(); + if (values.length == 1) return values[0]; + if (values.length == 2) return Math.min(values[0], values[1]); + float min = Float.MAX_VALUE; + for (float i : values) { + if (i < min) { + min = i; + } + } + return min; + } + + public static float max(float @NotNull... values) { + // noinspection ConstantValue + if (values == null || values.length == 0) throw new IllegalArgumentException(); + if (values.length == 1) return values[0]; + if (values.length == 2) return Math.max(values[0], values[1]); + float max = -Float.MAX_VALUE; + for (float i : values) { + if (i > max) { + max = i; + } + } + return max; + } + + public static Pair getCoordinates(@Nullable Direction dir, float min, float max) { + float x1 = min, y1 = min, z1 = min, x2 = max, y2 = max, z2 = max; + if (dir != null) { + switch (dir) { + case DOWN -> { + y1 = 0; + y2 = min; + } + case UP -> { + y1 = max; + y2 = 16; + } + case NORTH -> { + z1 = 0; + z2 = min; + } + case SOUTH -> { + z1 = max; + z2 = 16; + } + case WEST -> { + x1 = 0; + x2 = min; + } + case EAST -> { + x1 = max; + x2 = 16; + } + } + } + return Pair.of(new Vector3f(x1, y1, z1), new Vector3f(x2, y2, z2)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/math/RandomSampling.java b/src/main/java/com/modularmc/mmclutils/math/RandomSampling.java new file mode 100644 index 0000000..196d31c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/math/RandomSampling.java @@ -0,0 +1,22 @@ +package com.modularmc.mmclutils.math; + +import net.minecraft.util.RandomSource; + +/** 使用调用者提供的随机源,便于重放抽样结果。 */ +public final class RandomSampling { + + private RandomSampling() {} + + public static boolean chance(RandomSource random, double probability) { + if (!(probability >= 0 && probability <= 1)) throw new IllegalArgumentException("概率应在零与一之间"); + return probability == 1 || probability > 0 && random.nextDouble() < probability; + } + + public static int occurrences(RandomSource random, int trials, double probability) { + if (trials < 0 || !(probability >= 0 && probability <= 1)) throw new IllegalArgumentException("试验次数或概率无效"); + if (probability == 0 || probability == 1) return probability == 0 ? 0 : trials; + int successes = 0; + for (int trial = 0; trial < trials; trial++) if (random.nextDouble() < probability) successes++; + return successes; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/math/WeightedSelection.java b/src/main/java/com/modularmc/mmclutils/math/WeightedSelection.java new file mode 100644 index 0000000..617589c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/math/WeightedSelection.java @@ -0,0 +1,48 @@ +package com.modularmc.mmclutils.math; + +import net.minecraft.util.RandomSource; + +import org.jspecify.annotations.Nullable; + +import java.util.List; +import java.util.function.ToLongFunction; + +/** 根据非负权重抽取条目。无正权重条目时返回空值。 */ +public final class WeightedSelection { + + private WeightedSelection() {} + + public static @Nullable T choose(RandomSource random, List entries, ToLongFunction weight) { + long[] weights = new long[entries.size()]; + long total = 0; + for (int index = 0; index < entries.size(); index++) { + long current = weight.applyAsLong(entries.get(index)); + if (current < 0) throw new IllegalArgumentException("权重应为非负数"); + weights[index] = current; + total = Math.addExact(total, current); + } + if (total == 0) return null; + long draw = boundedLong(random, total); + for (int index = 0; index < weights.length; index++) { + draw -= weights[index]; + if (draw < 0) return entries.get(index); + } + throw new IllegalStateException("权重数量发生变化"); + } + + private static long boundedLong(RandomSource random, long bound) { + long mask = bound - 1; + long bits = random.nextLong() >>> 1; + if ((bound & mask) == 0) return bits & mask; + long value; + for (; bits - (value = bits % bound) + mask < 0; bits = random.nextLong() >>> 1) {} + return value; + } + + public record Entry(T value, long weight) { + + public Entry { + if (weight < 0) throw new IllegalArgumentException("权重应为非负数"); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/spatial/VoxelShapeAccessor.java b/src/main/java/com/modularmc/mmclutils/mixin/spatial/VoxelShapeAccessor.java new file mode 100644 index 0000000..257d8f8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/spatial/VoxelShapeAccessor.java @@ -0,0 +1,20 @@ +package com.modularmc.mmclutils.mixin.spatial; + +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/redstone/RedstoneSignals.java b/src/main/java/com/modularmc/mmclutils/redstone/RedstoneSignals.java new file mode 100644 index 0000000..9197505 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/redstone/RedstoneSignals.java @@ -0,0 +1,87 @@ +package com.modularmc.mmclutils.redstone; + +import com.modularmc.mmclutils.math.NumberMath; + +import java.math.BigInteger; + +public class RedstoneSignals { + + /** + * Compares a value against a min and max, with an option to invert the logic + * + * @param value value to be compared + * @param maxValue the max that the value can be + * @param minValue the min that the value can be + * @param isInverted whether to invert the logic of this method + * @return an int from 0 (value <= min) to 15 (value >= max) normally, with a ratio when the value is between min + * and max + */ + + public static int computeRedstoneBetweenValues(float value, float maxValue, float minValue, boolean isInverted) { + if (value >= maxValue) return isInverted ? 0 : 15; + else if (value <= minValue) return isInverted ? 15 : 0; + + float ratio; + if (isInverted) ratio = 15 * (maxValue - value) / (maxValue - minValue); + else ratio = 15 * (value - minValue) / (maxValue - minValue); + + return Math.round(ratio); + } + + public static int computeRedstoneBetweenValues(BigInteger value, BigInteger maxValue, BigInteger minValue, + boolean isInverted) { + if (value.compareTo(maxValue) >= 0) return isInverted ? 0 : 15; + else if (value.compareTo(maxValue) <= 0) return isInverted ? 15 : 0; + + float ratio; + if (isInverted) ratio = 15 * NumberMath.ratio(maxValue.subtract(value), maxValue.subtract(minValue)); + else ratio = 15 * NumberMath.ratio(value.subtract(minValue), maxValue.subtract(minValue)); + + return Math.round(ratio); + } + + /** + * Compares a value against a min and max, with an option to invert the logic. Has latching functionality. + * + * @param value value to be compared + * @param maxValue the max that the value can be + * @param minValue the min that the value can be + * @param output the output value the function modifies + * @return returns the modified output value + */ + public static int computeLatchedRedstoneBetweenValues(float value, float maxValue, float minValue, + boolean isInverted, int output) { + if (value >= maxValue) output = isInverted ? 15 : 0; // value above maxValue should normally be 0, otherwise 15 + else if (value <= minValue) output = isInverted ? 0 : 15; // value below minValue should normally be 15, + // otherwise 0 + return output; + } + + public static int computeLatchedRedstoneBetweenValues(BigInteger value, BigInteger maxValue, BigInteger minValue, + boolean isInverted, int output) { + if (value.compareTo(maxValue) >= 0) output = isInverted ? 15 : 0; + else if (value.compareTo(minValue) <= 0) output = isInverted ? 0 : 15; + return output; + } + + /** + * Compares a current against max, with an option to invert the logic. + * + * @param current value to be compared + * @param max the max that value can be + * @param isInverted whether to invert the logic of this method + * @return value 0 to 15; A value of at least 1 is returned if current > 0 + * @throws ArithmeticException when max is 0 + */ + public static int computeRedstoneValue(long current, long max, boolean isInverted) throws ArithmeticException { + var output = (int) (14f * current / max) + (current > 0 ? 1 : 0); + return isInverted ? 15 - output : output; + } + + public static int computeRedstoneValue(BigInteger current, BigInteger max, + boolean isInverted) throws ArithmeticException { + var isNotEmpty = current.compareTo(BigInteger.ZERO) > 0; + var output = (int) (14f * NumberMath.ratio(current, max)) + (isNotEmpty ? 1 : 0); + return isInverted ? 15 - output : output; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/registry/RegistryEntries.java b/src/main/java/com/modularmc/mmclutils/registry/RegistryEntries.java new file mode 100644 index 0000000..ca5ea84 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/registry/RegistryEntries.java @@ -0,0 +1,20 @@ +package com.modularmc.mmclutils.registry; + +import net.minecraft.core.Registry; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; + +import java.util.Arrays; +import java.util.List; + +public class RegistryEntries { + + private RegistryEntries() {} + + public static List> resolveResourceKeys(ResourceKey> registryKey, + String... locations) { + return Arrays.stream(locations) + .map(location -> ResourceKey.create(registryKey, Identifier.parse(location))) + .toList(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/registry/TagExpression.java b/src/main/java/com/modularmc/mmclutils/registry/TagExpression.java new file mode 100644 index 0000000..837b589 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/registry/TagExpression.java @@ -0,0 +1,312 @@ +package com.modularmc.mmclutils.registry; + +import net.minecraft.resources.Identifier; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.fluids.FluidStack; + +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class TagExpression { + + public static class TagExprParser { + + public enum TokenType { + LParen, + RParen, + And, + Or, + Not, + Xor, + String + } + + public static class Token { + + @Nullable + public String lexeme; + public TokenType type; + + public Token(TokenType type) { + this.type = type; + } + + public Token(TokenType type, String lexeme) { + this.lexeme = lexeme; + this.type = type; + } + } + + public static abstract class MatchExpr { + + public abstract boolean matches(Set input); + } + + private static class BinExpr extends MatchExpr { + + @Nullable + MatchExpr left, right; + Token op; + + public BinExpr(Token op, @Nullable MatchExpr left, @Nullable MatchExpr right) { + this.op = op; + this.left = left; + this.right = right; + } + + @Override + public boolean matches(Set input) { + if (left == null || right == null) { + return false; + } + return switch (op.type) { + case And -> left.matches(input) && right.matches(input); + case Or -> left.matches(input) || right.matches(input); + case Xor -> left.matches(input) ^ right.matches(input); + default -> false; + }; + } + } + + private static class UnaryExpr extends MatchExpr { + + Token token; + @Nullable + MatchExpr expr; + + public UnaryExpr(Token token, @Nullable MatchExpr expr) { + this.token = token; + this.expr = expr; + } + + @Override + public boolean matches(Set input) { + if (token.type == TokenType.Not) { + return expr != null && !expr.matches(input); + } + + return false; + } + } + + private static class StringExpr extends MatchExpr { + + @Nullable + String value; + + public StringExpr(@Nullable String value) { + this.value = value; + } + + @Override + public boolean matches(Set input) { + if (value == null || value.isEmpty()) return false; + if (value.equals("$") && input.isEmpty()) return true; + if (!value.contains(":") && !value.startsWith("*")) { + value = "c:" + value; + } + + String val = quote(value); + return input.stream().anyMatch(inp -> Pattern.matches(val, inp)); + } + + private String quote(String str) { + if (str.contains("*")) { + var idx = str.indexOf("*"); + if (idx == str.length() - 1) { + return quote(str.substring(0, idx)) + ".*"; + } else { + return quote(str.substring(0, idx)) + ".*" + quote(str.substring(idx + 1)); + } + } + + return Pattern.quote(str); + } + } + + private static class GroupingExpr extends MatchExpr { + + @Nullable + MatchExpr inner; + + public GroupingExpr(@Nullable MatchExpr inner) { + this.inner = inner; + } + + @Override + public boolean matches(Set input) { + return inner != null && inner.matches(input); + } + } + + List tokens = Collections.emptyList(); + int idx = 0; + @Nullable + Token prev = null; + + @Nullable + public MatchExpr parse(String expr) { + tokens = tokenize(expr); + + return expression(); + } + + private boolean match(TokenType tt) { + if (idx >= tokens.size()) { + return false; + } + + if (tokens.get(idx).type == tt) { + prev = tokens.get(idx); + idx++; + return true; + } + + return false; + } + + @Nullable + private MatchExpr expression() { + return term(); + } + + @Nullable + private MatchExpr term() { + MatchExpr lhs = unary(); + + BinExpr result = null; + while (match(TokenType.And) || match(TokenType.Or) || match(TokenType.Xor)) { + if (result == null) { + // noinspection DataFlowIssue can't. + result = new BinExpr(prev, lhs, unary()); + } else { + result = new BinExpr(prev, result, unary()); + } + } + + if (result != null) { + return result; + } + + return lhs; + } + + @Nullable + private MatchExpr unary() { + if (match(TokenType.Not)) { + // noinspection DataFlowIssue it gets set in match() + return new UnaryExpr(prev, id()); + } + + return id(); + } + + @Nullable + private MatchExpr id() { + if (match(TokenType.LParen)) { + MatchExpr inner = expression(); + match(TokenType.RParen); + + return new GroupingExpr(inner); + } + + if (match(TokenType.String)) { + // noinspection DataFlowIssue it gets set in match() + return new StringExpr(prev.lexeme); + } + + return null; + } + + private List tokenize(String expr) { + List result = new ArrayList<>(); + + int idx = 0; + while (idx < expr.length()) { + char cur = expr.charAt(idx); + + if (Character.isWhitespace(cur)) { + idx++; + continue; + } + + // Parse strings + { + int stringLen = 0; + while (cur != '(' && cur != ')' && cur != '!' && cur != '&' && cur != '|' && cur != '^' && + cur != ' ') { + stringLen++; + + if (stringLen + idx == expr.length()) { + break; + } + + cur = expr.charAt(idx + stringLen); + } + + if (stringLen > 0) { + result.add(new Token(TokenType.String, expr.substring(idx, idx + stringLen))); + idx += stringLen; + continue; + } + } + + // Parse operators + switch (cur) { + case '!' -> result.add(new Token(TokenType.Not)); + case '&' -> result.add(new Token(TokenType.And)); + case '|' -> result.add(new Token(TokenType.Or)); + case '^' -> result.add(new Token(TokenType.Xor)); + case '(' -> result.add(new Token(TokenType.LParen)); + case ')' -> result.add(new Token(TokenType.RParen)); + } + + idx++; + } + + return result; + } + } + + /** + * Parses the given expression and puts them into the given list. + * + * @param expression expr to parse + * @return The parsed expression tree + */ + public static TagExprParser.@Nullable MatchExpr parseExpression(String expression) { + return new TagExprParser().parse(expression); + } + + /** + * Matches the given item against a list of rules + * + * @param expr to check against + * @param stack item to check + * @return if any of the item's tags matches the rules + */ + public static boolean tagsMatch(TagExprParser.@Nullable MatchExpr expr, ItemStack stack) { + Set tags = stack.typeHolder().tags() + .map(TagKey::location) + .map(Identifier::toString) + .collect(Collectors.toSet()); + + return expr != null && expr.matches(tags); + } + + public static boolean tagsMatch(TagExprParser.@Nullable MatchExpr expr, FluidStack stack) { + Set tags = stack.getFluid().builtInRegistryHolder().tags() + .map(TagKey::location) + .map(Identifier::toString) + .collect(Collectors.toSet()); + + return expr != null && expr.matches(tags); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/registry/TagKeys.java b/src/main/java/com/modularmc/mmclutils/registry/TagKeys.java new file mode 100644 index 0000000..0a926cc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/registry/TagKeys.java @@ -0,0 +1,26 @@ +package com.modularmc.mmclutils.registry; + +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.material.Fluid; + +/** 通过原版注册表构造类型安全的标签键。 */ +public final class TagKeys { + + private TagKeys() {} + + public static TagKey block(Identifier id) { + return TagKey.create(Registries.BLOCK, id); + } + + public static TagKey item(Identifier id) { + return TagKey.create(Registries.ITEM, id); + } + + public static TagKey fluid(Identifier id) { + return TagKey.create(Registries.FLUID, id); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/registry/TriState.java b/src/main/java/com/modularmc/mmclutils/registry/TriState.java new file mode 100644 index 0000000..116a7d4 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/registry/TriState.java @@ -0,0 +1,102 @@ +package com.modularmc.mmclutils.registry; + +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.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +import java.util.Locale; +import java.util.function.BooleanSupplier; +import java.util.function.Function; + +/** + * Represents a boolean value that can be {@code true}, {@code false} or refer to a default value. + */ +public enum TriState implements StringRepresentable { + + /** + * Represents the boolean value {@code true}. + */ + TRUE, + /** + * Represents a "default" value, often used as a fallback. + */ + DEFAULT, + /** + * Represents the boolean value {@code false}. + */ + 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)); + + // Helper methods + + 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; + } + + public static TriState of(@Nullable Boolean value) { + return value == null ? DEFAULT : of((boolean) value); + } + + public static TriState of(DataResult value) { + if (value.result().isPresent()) return of(value.result().get()); + // throw out parsing errors and return default + else return DEFAULT; + } + + public @Nullable Boolean toBoolean() { + return switch (this) { + case TRUE -> Boolean.TRUE; + case FALSE -> Boolean.FALSE; + default -> null; + }; + } + + 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 @NotNull BooleanSupplier supplier) { + return switch (this) { + case TRUE -> true; + case FALSE -> false; + default -> supplier.getAsBoolean(); + }; + } + + @Override + public @NotNull String getSerializedName() { + return this.name().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/resource/ResourcePaths.java b/src/main/java/com/modularmc/mmclutils/resource/ResourcePaths.java new file mode 100644 index 0000000..cbc67d9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/resource/ResourcePaths.java @@ -0,0 +1,23 @@ +package com.modularmc.mmclutils.resource; + +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.PackType; +import net.minecraft.util.FileUtil; + +import java.nio.file.Path; + +/** 将原版资源标识定位到资源包根路径下,遵循原版路径分段校验。 */ +public final class ResourcePaths { + + private ResourcePaths() {} + + public static Path resolve(Path root, PackType type, Identifier id) { + return FileUtil.decomposePath(id.getPath()) + .map(parts -> FileUtil.resolvePath(root.resolve(type.getDirectory()).resolve(id.getNamespace()), parts)) + .getOrThrow(); + } + + public static Path resolve(Path root, Identifier id) { + return id.resolveAgainst(root); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/serialization/BinaryCodecs.java b/src/main/java/com/modularmc/mmclutils/serialization/BinaryCodecs.java new file mode 100644 index 0000000..82b933c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/serialization/BinaryCodecs.java @@ -0,0 +1,63 @@ +package com.modularmc.mmclutils.serialization; + +import com.modularmc.mmclutils.io.BinaryFiles; + +import net.minecraft.resources.Identifier; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.util.UUID; + +/** 原始二进制字段的读取器和写入器。变长字段由调用方设置长度上限。 */ +public final class BinaryCodecs { + + public static final BinaryCodec UTF = new BinaryCodec<>(input -> input.readUTF(), DataOutputStream::writeUTF); + public static final BinaryCodec BOOLEAN = new BinaryCodec<>(DataInputStream::readBoolean, DataOutputStream::writeBoolean); + public static final BinaryCodec UUID_TEXT = new BinaryCodec<>(input -> UUID.fromString(input.readUTF()), + (output, value) -> output.writeUTF(value.toString())); + public static final BinaryCodec IDENTIFIER = new BinaryCodec<>(input -> Identifier.parse(input.readUTF()), + (output, value) -> output.writeUTF(value.toString())); + + private BinaryCodecs() {} + + public static BinaryCodec bytes(int maximumLength) { + if (maximumLength < 0) throw new IllegalArgumentException("最大长度应为非负数"); + return new BinaryCodec<>(input -> { + int length = input.readInt(); + if (length < 0 || length > maximumLength) throw new IOException("无效的二进制字段长度:" + length); + byte[] bytes = new byte[length]; + input.readFully(bytes); + return bytes; + }, (output, bytes) -> { + if (bytes.length > maximumLength) throw new IOException("二进制字段超出长度上限"); + output.writeInt(bytes.length); + output.write(bytes); + }); + } + + public static BinaryCodec bigInteger(int maximumLength) { + BinaryCodec bytes = bytes(maximumLength); + return new BinaryCodec<>(input -> { + byte[] value = bytes.read(input); + if (value.length == 0) throw new IOException("整数二进制字段为空"); + return new BigInteger(value); + }, (output, value) -> bytes.write(output, value.toByteArray())); + } + + /** 同一值的两个编解码方向共享约定的字节布局。 */ + public record BinaryCodec(BinaryFiles.Reader reader, BinaryFiles.Writer writer) + implements BinaryFiles.Reader, BinaryFiles.Writer { + + @Override + public T read(DataInputStream input) throws IOException { + return reader.read(input); + } + + @Override + public void write(DataOutputStream output, T value) throws IOException { + writer.write(output, value); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/serialization/Codecs.java b/src/main/java/com/modularmc/mmclutils/serialization/Codecs.java new file mode 100644 index 0000000..ed0934c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/serialization/Codecs.java @@ -0,0 +1,27 @@ +package com.modularmc.mmclutils.serialization; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.MapCodec; + +import java.util.function.Function; + +public class Codecs { + + 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); + + public static Codec longRangeWithMessage(long min, long max, Function errorMessage) { + return Codec.LONG + .validate( + value -> value.compareTo(min) >= 0 && value.compareTo(max) <= 0 ? DataResult.success(value) : + DataResult.error(() -> errorMessage.apply(value))); + } + + public static DataResult encodeMap(T value, MapCodec codec, DynamicOps ops) { + return codec.encode(value, ops, ops.mapBuilder()).build(ops.empty()); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java b/src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java new file mode 100644 index 0000000..4254ec9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java @@ -0,0 +1,46 @@ +package com.modularmc.mmclutils.serialization; + +import com.mojang.serialization.Codec; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; + +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** 用原版 Codec 读写集合,并在解码时选用适合用途的容器。 */ +public final class CollectionCodecs { + + private CollectionCodecs() {} + + 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); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/serialization/StackCodecs.java b/src/main/java/com/modularmc/mmclutils/serialization/StackCodecs.java new file mode 100644 index 0000000..65b2b72 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/serialization/StackCodecs.java @@ -0,0 +1,33 @@ +package com.modularmc.mmclutils.serialization; + +import com.modularmc.mmclutils.item.ItemStacks; +import com.modularmc.mmclutils.serialization.BinaryCodecs.BinaryCodec; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.fluids.FluidStack; + +import com.mojang.serialization.Codec; + +import java.io.IOException; + +/** 通过原版编解码器保存组件,并提供旧的标识和数量布局读取器。 */ +public final class StackCodecs { + + public static final Codec ITEM = ItemStack.OPTIONAL_CODEC; + public static final Codec FLUID = FluidStack.OPTIONAL_CODEC; + + public static final BinaryCodec LEGACY_ITEM = new BinaryCodec<>(input -> { + var id = BinaryCodecs.IDENTIFIER.read(input); + int count = input.readInt(); + if (count < 0) throw new IOException("无效的物品数量:" + count); + if (count == 0) return ItemStack.EMPTY; + var item = BuiltInRegistries.ITEM.getOptional(id).orElseThrow(() -> new IOException("找不到物品:" + id)); + return new ItemStack(item, count); + }, (output, stack) -> { + BinaryCodecs.IDENTIFIER.write(output, ItemStacks.id(stack)); + output.writeInt(stack.getCount()); + }); + + private StackCodecs() {} +} diff --git a/src/main/java/com/modularmc/mmclutils/serialization/StreamCodecs.java b/src/main/java/com/modularmc/mmclutils/serialization/StreamCodecs.java new file mode 100644 index 0000000..609a4cd --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/serialization/StreamCodecs.java @@ -0,0 +1,222 @@ +package com.modularmc.mmclutils.serialization; + +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 { + + 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; + } + }; + } + + 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 p_331335_) { + 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 p_331335_.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)); + } + }; + } + + 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)); + } + }; + } + + 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/serialization/TypeTokens.java b/src/main/java/com/modularmc/mmclutils/serialization/TypeTokens.java new file mode 100644 index 0000000..cbb9902 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/serialization/TypeTokens.java @@ -0,0 +1,30 @@ +package com.modularmc.mmclutils.serialization; + +import com.google.common.reflect.TypeToken; + +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Optional; + +/** 在序列化注册时查询类型信息。 */ +public final class TypeTokens { + + private TypeTokens() {} + + public static Class raw(Type type) { + return TypeToken.of(type).getRawType(); + } + + public static Optional parameter(Type type, int index) { + if (!(type instanceof ParameterizedType parameterized)) return Optional.empty(); + Type[] parameters = parameterized.getActualTypeArguments(); + return index < 0 || index >= parameters.length ? Optional.empty() : Optional.of(parameters[index]); + } + + public static Optional component(Type type) { + if (type instanceof GenericArrayType array) return Optional.of(array.getGenericComponentType()); + if (type instanceof Class clazz && clazz.isArray()) return Optional.of(clazz.getComponentType()); + return Optional.empty(); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java new file mode 100644 index 0000000..2356ec9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java @@ -0,0 +1,25 @@ +package com.modularmc.mmclutils.spatial; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.phys.Vec3; + +/** 将局部方向、点击位置与打包坐标映射到原版方块面。 */ +public final class BlockDirections { + + private BlockDirections() {} + + public static long offset(long packedPosition, Direction side) { + return BlockPos.offset(packedPosition, side); + } + + public static Direction nearestSide(Vec3 point, BlockPos position) { + return Direction.getApproximateNearest(point.x - position.getX() - .5, + point.y - position.getY() - .5, point.z - position.getZ() - .5); + } + + public static Direction rotateHorizontal(Direction direction, int quarterTurns) { + if (direction.getAxis().isVertical()) return direction; + return Direction.from2DDataValue(Math.floorMod(direction.get2DDataValue() + quarterTurns, 4)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/BlockSearch.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockSearch.java new file mode 100644 index 0000000..42ba502 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockSearch.java @@ -0,0 +1,139 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.level.LoadedChunks; + +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 org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BiPredicate; +import java.util.function.LongPredicate; +import java.util.function.Predicate; + +/** 在六个相邻面上进行有界的广度优先搜索,结果按发现顺序返回。 */ +public final class BlockSearch { + + private static final Direction[] SIDES = Direction.values(); + + private BlockSearch() {} + + /** 经过未命中的位置,找到匹配位置时停止从该位置继续扩展。 */ + 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; + } + + 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 ArrayList(SIDES.length); + for (Direction side : SIDES) result.add(pos.relative(side)); + return result; + } + + /** 每次可按到达的边筛选。被拒绝的位置仍可经其他路径访问。 */ + 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)); + } + + public static Set conditionalBlockEntitySearch(Class type, T start, + TriPredicate filter, + int resultLimit, int visitLimit) { + Level level = start.getLevel(); + if (level == null) return Set.of(); + var accepted = new LinkedHashSet(); + var pending = new ObjectArrayFIFOQueue>(); + pending.enqueue(new Step<>(null, start, null)); + int visits = 0; + var cursor = new BlockPos.MutableBlockPos(); + 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); + BlockPos center = step.target.getBlockPos(); + for (Direction side : SIDES) { + cursor.setWithOffset(center, side); + BlockEntity neighbor = LoadedChunks.blockEntity(level, cursor); + if (type.isInstance(neighbor) && !accepted.contains(neighbor)) { + pending.enqueue(new Step<>(step.target, type.cast(neighbor), side)); + } + } + } + return accepted; + } + + private static Set unpack(LongSet positions) { + var result = new LinkedHashSet(positions.size()); + for (var iterator = positions.iterator(); iterator.hasNext();) result.add(BlockPos.of(iterator.nextLong())); + return result; + } + + /** 根位置的 root 为真,其他位置提供打包后的父坐标与目标坐标。 */ + @FunctionalInterface + public interface EdgeFilter { + + 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/spatial/GlobalPositions.java b/src/main/java/com/modularmc/mmclutils/spatial/GlobalPositions.java new file mode 100644 index 0000000..cd7281c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/GlobalPositions.java @@ -0,0 +1,17 @@ +package com.modularmc.mmclutils.spatial; + +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; + +/** 用维度标识和打包的方块坐标构造全局位置。 */ +public final class GlobalPositions { + + private GlobalPositions() {} + + public static GlobalPos of(Identifier dimension, long packedPos) { + return GlobalPos.of(ResourceKey.create(Registries.DIMENSION, dimension), BlockPos.of(packedPos)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java new file mode 100644 index 0000000..1236a53 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java @@ -0,0 +1,94 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.client.level.SectionGeometryData; + +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +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 +@OnlyIn(Dist.CLIENT) +public final class VoxelContours { + + private static final double EPSILON = 1.0e-5; + private final SectionGeometryData geometry; + private final BooleanSupplier cancelled; + private final ObjectOpenHashSet edges = new ObjectOpenHashSet<>(); + private final DoubleArrayList cuts = new DoubleArrayList(); + + 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; + VoxelContoursShape 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); + } + + public record Edge(float x1, float y1, float z1, float x2, float y2, float z2) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java new file mode 100644 index 0000000..ffe766b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java @@ -0,0 +1,52 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.client.level.SectionOccupancy; + +import net.minecraft.core.Direction; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import java.util.Arrays; + +/** Owned coordinates and occupied runs, safely published after capture and never mutated by workers. */ +@OnlyIn(Dist.CLIENT) +public record VoxelContoursShape(double[] x, double[] y, double[] z, SectionOccupancy runs) { + + public static final VoxelContoursShape EMPTY = new VoxelContoursShape(new double[] { 0 }, new double[] { 0 }, new double[] { 0 }, new SectionOccupancy()); + public static final VoxelContoursShape UNSUPPORTED = new VoxelContoursShape(new double[] { 0 }, new double[] { 0 }, new double[] { 0 }, new SectionOccupancy()); + public static final VoxelContoursShape BLOCK = box(1); + + public static VoxelContoursShape box(double height) { + var runs = new SectionOccupancy(); + runs.append(0); + runs.append(1); + return new VoxelContoursShape(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/spatial/VoxelShapes.java b/src/main/java/com/modularmc/mmclutils/spatial/VoxelShapes.java new file mode 100644 index 0000000..e2dcdca --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/VoxelShapes.java @@ -0,0 +1,104 @@ +package com.modularmc.mmclutils.spatial; + +import com.modularmc.mmclutils.client.level.SectionOccupancy; +import com.modularmc.mmclutils.mixin.spatial.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 net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import it.unimi.dsi.fastutil.doubles.DoubleList; +import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; +import org.jspecify.annotations.Nullable; + +/** Client-thread identity cache. Both coordinate copying and grid sampling yield to the tick budget. */ +@OnlyIn(Dist.CLIENT) +public final class VoxelShapes { + + 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<>(); + + public @Nullable VoxelContoursShape capture(VoxelShape shape, long deadline) { + if (shape == Shapes.block()) return VoxelContoursShape.BLOCK; + if (shape == Shapes.empty()) return VoxelContoursShape.EMPTY; + if (!shapes.containsKey(shape)) { + shapes.put(shape, new Capture(shape)); + if (shapes.size() > MAX_CACHED_SHAPES) shapes.removeFirst(); + } + return shapes.getAndMoveToLast(shape).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 SectionOccupancy runs = new SectionOccupancy(); + private final long cells; + private int axis; + private int coordinate; + private long cell; + private long start = -1; + private @Nullable VoxelContoursShape 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 = VoxelContoursShape.UNSUPPORTED; + } else { + coordinates = new double[][] { new double[source[0].size()], new double[source[1].size()], new double[source[2].size()] }; + } + } + + private @Nullable VoxelContoursShape 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("Non-finite vision shape coordinate"); + 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 = VoxelContoursShape.EMPTY; + else if (runs.fills(cells)) result = new VoxelContoursShape(bounds(coordinates[0]), bounds(coordinates[1]), bounds(coordinates[2]), VoxelContoursShape.BLOCK.runs()); + else result = new VoxelContoursShape(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/text/Components.java b/src/main/java/com/modularmc/mmclutils/text/Components.java new file mode 100644 index 0000000..e6187ec --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/text/Components.java @@ -0,0 +1,34 @@ +package com.modularmc.mmclutils.text; + +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collector; + +/** 组合原版文本组件,保留子组件的样式和翻译信息。 */ +public final class Components { + + private Components() {} + + 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; + } + + public static Collector joining(Component separator) { + return Collector.of( + ArrayList::new, + List::add, + (left, right) -> { + left.addAll(right); + return left; + }, + parts -> join(parts, separator)); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/text/NumberFormats.java b/src/main/java/com/modularmc/mmclutils/text/NumberFormats.java new file mode 100644 index 0000000..545c495 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/text/NumberFormats.java @@ -0,0 +1,170 @@ +package com.modularmc.mmclutils.text; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; + +/** + * Formats Trinity and AE2 amounts with GregTech-MoreMachine's decimal compact-unit convention. + * + *

+ * Values advance by powers of one thousand through the same extended unit sequence used by both maintained + * GregTech-MoreMachine branches. Values beyond {@code Att} use scientific notation, so arbitrary-precision Trinity + * capacities remain representable without falling back to AE2's binary byte units. + *

+ */ +public final class NumberFormats { + + private static final BigInteger UNIT_BASE = BigInteger.valueOf(1_000L); + private static final long NANOS_PER_MILLISECOND = 1_000_000L; + private static final long NANOS_PER_SECOND = 1_000_000_000L; + private static final String[] COMPACT_UNITS = { + "", "K", "M", "G", "T", "P", "E", "Z", "Y", "B", "N", "D", "C", "S", "O", "Q", "X", "W", "V", + "U", "Tt", "Gt", "Mt", "St", "Ot", "Nt", "Dt", "Ct", "Lt", "Kt", "Jt", "It", "Ht", "Gtt", "Ett", + "Dtt", "Ctt", "Btt", "Att" + }; + private static final BigDecimal SCIENTIFIC_THRESHOLD = new BigDecimal(UNIT_BASE.pow(COMPACT_UNITS.length)); + + private NumberFormats() {} + + /** + * Formats a non-negative planning duration with a compact unit selected from microseconds, milliseconds, and + * seconds. + * + * @param nanos duration measured with {@link System#nanoTime()} + * @return duration rounded to one decimal place with a dynamically selected unit + */ + public static String formatDuration(long nanos) { + if (nanos < 0L) { + throw new IllegalArgumentException("A Trinity duration must not be negative"); + } + if (nanos < NANOS_PER_MILLISECOND) { + return formatDuration(nanos, 3, " μs"); + } + if (nanos < NANOS_PER_SECOND) { + return formatDuration(nanos, 6, " ms"); + } + return formatDuration(nanos, 9, " s"); + } + + private static String formatDuration(long nanos, int scale, String unit) { + BigDecimal rounded = BigDecimal.valueOf(nanos, scale).setScale(1, RoundingMode.HALF_EVEN); + if (nanos > 0L && rounded.signum() == 0) { + return "<0.1" + unit; + } + return rounded.stripTrailingZeros().toPlainString() + unit; + } + + /** + * Parses and formats one signed decimal integer. + * + * @param value signed decimal integer, with surrounding whitespace permitted + * @return compact display text + */ + public static String format(String value) { + if (value.isBlank()) { + return "0"; + } + return format(new BigInteger(value.trim())); + } + + /** + * Formats one signed {@code long} without converting through {@code double}. + * + * @param value amount to format + * @return compact display text + */ + public static String format(long value) { + return format(BigInteger.valueOf(value)); + } + + /** + * Formats one arbitrary-precision signed integer. + * + * @param value amount to format + * @return compact display text + */ + public static String format(BigInteger value) { + return formatParts(value).text(); + } + + /** Formats an exact amount expressed in display units, including fractional fluid units. */ + public static String format(BigDecimal value) { + return formatParts(value).text(); + } + + /** + * Formats one {@code long} while keeping the numeric and unit portions separate for AE2 tooltip coloring. + * + * @param value amount to format + * @return separated numeric text and compact unit + */ + public static FormattedAmount formatParts(long value) { + return formatParts(BigInteger.valueOf(value)); + } + + /** + * Formats one arbitrary-precision integer while keeping its suffix separate. + * + * @param value amount to format + * @return separated numeric text and compact unit + */ + public static FormattedAmount formatParts(BigInteger value) { + return formatParts(new BigDecimal(value)); + } + + private static FormattedAmount formatParts(BigDecimal value) { + if (value.signum() == 0) { + return new FormattedAmount("0", ""); + } + + BigDecimal absoluteAmount = value.abs(); + if (absoluteAmount.compareTo(SCIENTIFIC_THRESHOLD) >= 0) { + return new FormattedAmount(formatScientific(value), ""); + } + + int unitIndex = Math.max(0, (absoluteAmount.precision() - absoluteAmount.scale() - 1) / 3); + BigDecimal scaledAmount = absoluteAmount.movePointLeft(unitIndex * 3); + String digits = compactFormat().format(scaledAmount); + if (value.signum() < 0) { + digits = "-" + digits; + } + return new FormattedAmount(digits, COMPACT_UNITS[unitIndex]); + } + + private static String formatScientific(BigDecimal amount) { + DecimalFormat format = decimalFormat("0.00E00"); + return format.format(amount); + } + + private static DecimalFormat compactFormat() { + return decimalFormat("#,##0.#"); + } + + private static DecimalFormat decimalFormat(String pattern) { + DecimalFormat format = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.ROOT)); + format.setRoundingMode(RoundingMode.HALF_EVEN); + return format; + } + + /** + * One compact value split so AE2 callers can retain their separate number and unit styles. + * + * @param digits formatted numeric portion, including a sign when negative + * @param unit compact suffix, or an empty string for unscaled/scientific values + */ + public record FormattedAmount(String digits, String unit) { + + /** + * Joins the numeric portion and suffix for plain-text controls. + * + * @return complete formatted value + */ + public String text() { + return this.digits + this.unit; + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/text/TextFormats.java b/src/main/java/com/modularmc/mmclutils/text/TextFormats.java new file mode 100644 index 0000000..19e7bb1 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/text/TextFormats.java @@ -0,0 +1,31 @@ +package com.modularmc.mmclutils.text; + +import org.jspecify.annotations.Nullable; + +/** 按分隔符拆分文本,并转换十进制单字数字。 */ +public final class TextFormats { + + private static final String CHINESE_DIGITS = "零一二三四五六七八九"; + + private TextFormats() {} + + public static String chineseDigit(int digit) { + if (digit < 0 || digit >= CHINESE_DIGITS.length()) throw new IllegalArgumentException("数字须在零至九之间"); + return String.valueOf(CHINESE_DIGITS.charAt(digit)); + } + + public static Parts splitFirst(String value, char delimiter) { + return split(value, value.indexOf(delimiter)); + } + + public static Parts splitLast(String value, char delimiter) { + return split(value, value.lastIndexOf(delimiter)); + } + + private static Parts split(String value, int index) { + return index < 0 ? new Parts(value, null) : new Parts(value.substring(0, index), value.substring(index + 1)); + } + + /** 缺少分隔符时后段为空值,分隔符位于边缘时对应一段为空字符串。 */ + public record Parts(String first, @Nullable String second) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/text/TextSearch.java b/src/main/java/com/modularmc/mmclutils/text/TextSearch.java new file mode 100644 index 0000000..210949e --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/text/TextSearch.java @@ -0,0 +1,51 @@ +package com.modularmc.mmclutils.text; + +import java.lang.Character.UnicodeScript; +import java.util.regex.Pattern; + +/** 标准化搜索文本,支持子序列和调用者提供的完整正则匹配。 */ +public final class TextSearch { + + private TextSearch() {} + + public static boolean isCjk(int codePoint) { + return UnicodeScript.of(codePoint) == UnicodeScript.HAN; + } + + public static String normalize(String text) { + StringBuilder result = new StringBuilder(text.length()); + for (int i = 0; i < text.length();) { + int point = text.codePointAt(i); + if (Character.isLetterOrDigit(point) || isCjk(point)) result.appendCodePoint(Character.toLowerCase(point)); + i += Character.charCount(point); + } + return result.toString(); + } + + public static boolean matches(String text, String query) { + return !text.isEmpty() && matchesNormalized(text, normalize(query)); + } + + /** 查询词已标准化时使用,可复用于多个候选。 */ + public static boolean matchesNormalized(String text, String normalizedQuery) { + if (normalizedQuery.isEmpty()) return true; + String normalizedText = normalize(text); + int wanted = 0; + for (int i = 0; i < normalizedText.length();) { + int point = normalizedText.codePointAt(i); + if (point == normalizedQuery.codePointAt(wanted)) { + wanted += Character.charCount(point); + if (wanted == normalizedQuery.length()) return true; + } + i += Character.charCount(point); + } + return false; + } + + public static boolean matchesAny(String text, Pattern... patterns) { + for (Pattern pattern : patterns) { + if (pattern.matcher(text).matches()) return true; + } + return false; + } +} diff --git a/src/main/resources/mmclutils.mixins.json b/src/main/resources/mmclutils.mixins.json index 26c1cfb..1c0e705 100644 --- a/src/main/resources/mmclutils.mixins.json +++ b/src/main/resources/mmclutils.mixins.json @@ -14,7 +14,8 @@ "client": [ "client.level.ClientChunkCacheMixin", "client.level.ClientChunkStorageMixin", - "client.render.GlBufferAccessor" + "client.render.GlBufferAccessor", + "spatial.VoxelShapeAccessor" ], "injectors": { "defaultRequire": 1 From 487171af1a2911c1ad891a8c6581fde0aee4ea78 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 02:22:09 +0800 Subject: [PATCH 11/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E6=A8=A1=E5=9E=8B=E4=B8=8E=E5=8C=BA=E6=AE=B5=E5=87=A0?= =?UTF-8?q?=E4=BD=95=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/client/gui/GuiDrawing.java | 60 ++++++ .../mmclutils/client/gui/ListLayout.java | 30 +++ .../client/level/LoadedSectionCursor.java | 70 +++++++ .../client/level/SectionCapture.java | 110 +++++++++++ .../client/level/SectionGeometryData.java | 21 ++ .../client/level/SectionOccupancy.java | 44 +++++ .../client/model/BlockModelRotations.java | 70 +++++++ .../mmclutils/client/model/ClientModels.java | 80 ++++++++ .../render/geometry/MatrixTransforms.java | 157 +++++++++++++++ .../client/render/geometry/OrbitGeometry.java | 51 +++++ .../geometry/SectionGeometryRenderer.java | 179 ++++++++++++++++++ .../client/render/geometry/StaticMesh.java | 67 +++++++ .../client/render/geometry/VertexWriters.java | 34 ++++ .../client/render/quad/BakedQuadView.java | 42 ++++ .../client/render/quad/Interpolation.java | 120 ++++++++++++ .../client/render/quad/MutableQuadView.java | 144 ++++++++++++++ .../client/render/quad/QuadGeometry.java | 86 +++++++++ .../client/render/quad/QuadMeshes.java | 83 ++++++++ .../client/render/quad/QuadTransforms.java | 132 +++++++++++++ .../client/render/quad/QuadView.java | 50 +++++ .../client/render/texture/SpriteLookup.java | 81 ++++++++ .../render/texture/TextureCoordinates.java | 92 +++++++++ 22 files changed, 1803 insertions(+) create mode 100644 src/main/java/com/modularmc/mmclutils/client/gui/GuiDrawing.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/gui/ListLayout.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/level/SectionOccupancy.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotations.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/model/ClientModels.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/geometry/MatrixTransforms.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/geometry/OrbitGeometry.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryRenderer.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/quad/BakedQuadView.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/quad/Interpolation.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/quad/MutableQuadView.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/quad/QuadGeometry.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/quad/QuadMeshes.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/quad/QuadTransforms.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/quad/QuadView.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/texture/SpriteLookup.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/texture/TextureCoordinates.java diff --git a/src/main/java/com/modularmc/mmclutils/client/gui/GuiDrawing.java b/src/main/java/com/modularmc/mmclutils/client/gui/GuiDrawing.java new file mode 100644 index 0000000..f040158 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/gui/GuiDrawing.java @@ -0,0 +1,60 @@ +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 GuiDrawing { + + private GuiDrawing() {} + + 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); + } + + 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); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/gui/ListLayout.java b/src/main/java/com/modularmc/mmclutils/client/gui/ListLayout.java new file mode 100644 index 0000000..b20ac18 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/gui/ListLayout.java @@ -0,0 +1,30 @@ +package com.modularmc.mmclutils.client.gui; + +/** 计算列表行的进度宽度和滚动条滑块比例。 */ +public final class ListLayout { + + private static final float MIN_SCROLL_THUMB_HEIGHT = 6.0F; + + private ListLayout() {} + + public static int progressWidth(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 thumbPercent(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/level/LoadedSectionCursor.java b/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java new file mode 100644 index 0000000..f425117 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java @@ -0,0 +1,70 @@ +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 net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import lombok.Getter; +import org.jspecify.annotations.Nullable; + +/** 以中心区块为起点螺旋遍历,按高度交替访问已加载的非空区段。 */ +@OnlyIn(Dist.CLIENT) +public final class LoadedSectionCursor { + + 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 sectionCursor; + private @Nullable LevelChunk chunk; + @Getter + private boolean finished; + + public LoadedSectionCursor(int centerX, int centerY, int centerZ, int radius) { + this.centerX = centerX; + this.centerY = centerY; + this.centerZ = centerZ; + remaining = (radius * 2 + 1) * (radius * 2 + 1); + } + + /** 返回区段的打包坐标。到达时限或遍历完毕时返回 NO_SECTION。 */ + public long next(ClientLevel level, long deadline) { + while (System.nanoTime() < deadline) { + if (chunk == null) { + if (remaining == 0) { + finished = true; + return NO_SECTION; + } + chunk = level.getChunkSource().getChunk(centerX + x, centerZ + z, 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 = 0; + if (chunk == null) continue; + } + int count = chunk.getSections().length; + if (sectionCursor >= count * 2 - 1) { + chunk = null; + 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(chunk.getPos().x(), level.getSectionYFromSectionIndex(index), chunk.getPos().z()); + } + return NO_SECTION; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java b/src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java new file mode 100644 index 0000000..43637bd --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java @@ -0,0 +1,110 @@ +package com.modularmc.mmclutils.client.level; + +import com.modularmc.mmclutils.level.BlockEnvironment; +import com.modularmc.mmclutils.spatial.VoxelContoursShape; +import com.modularmc.mmclutils.spatial.VoxelShapes; + +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 net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import org.jspecify.annotations.Nullable; + +/** 在客户端线程分步读取已加载区段。单个复杂形状的读取同样受本轮时限约束。 */ +@OnlyIn(Dist.CLIENT) +public final class SectionCapture { + + 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 VoxelContoursShape[] shapes = new VoxelContoursShape[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 static final ChunkEntry UNQUERIED = new ChunkEntry(false, null); + private final ChunkEntry[] chunks = { UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED }; + private @Nullable PendingBlock pending; + private int cursor; + + public SectionCapture(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; + } + + public @Nullable SectionGeometryData advance(ClientLevel level, VoxelShapes cache, long deadline) { + 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++] = VoxelContoursShape.EMPTY; + continue; + } + BlockState state = chunk.getBlockState(position); + if (state.isAir()) { + shapes[cursor++] = VoxelContoursShape.EMPTY; + continue; + } + pending = new PendingBlock(state, state.getShape(level, position)); + } + BlockState state = pending.state(); + VoxelContoursShape shape = cache.capture(pending.shape(), deadline); + if (shape == null) return null; + pending = null; + if (shape == VoxelContoursShape.UNSUPPORTED) { + shapes[cursor++] = shape; + continue; + } + var fluid = state.getFluidState(); + if (shape.empty() && !fluid.isEmpty()) shape = VoxelContoursShape.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 & SectionGeometryData.INCLUDE_TEMPERATURE) != 0 && (visible[index] != 0 || shape != VoxelContoursShape.BLOCK)) temperatures[index] = BlockEnvironment.temperature(state, level, position); + } + return cursor == shapes.length ? new SectionGeometryData(origin, modes, shapes, temperatures, visible) : null; + } + + 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 |= 1 << direction.ordinal(); + else { + BlockState adjacent = chunk.getBlockState(neighbor); + if ((fluid.isEmpty() || !fluid.getType().isSame(adjacent.getFluidState().getType())) && Block.shouldRenderFace(level, position, state, adjacent, direction)) faces |= 1 << direction.ordinal(); + } + } + return faces; + } + + private @Nullable LevelChunk loadedChunk(ClientLevel level, int chunkX, int chunkZ) { + int chunkIndex = (chunkX - baseChunkX + 1) * 3 + chunkZ - baseChunkZ + 1; + ChunkEntry entry = chunks[chunkIndex]; + if (!entry.queried()) { + entry = new ChunkEntry(true, level.getChunkSource().getChunk(chunkX, chunkZ, false)); + chunks[chunkIndex] = entry; + } + return entry.chunk(); + } + + private record PendingBlock(BlockState state, VoxelShape shape) {} + + private record ChunkEntry(boolean queried, @Nullable LevelChunk chunk) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java b/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java new file mode 100644 index 0000000..e1b02af --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java @@ -0,0 +1,21 @@ +package com.modularmc.mmclutils.client.level; + +import com.modularmc.mmclutils.spatial.VoxelContoursShape; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +/** 区段和一格邻接范围的几何数据。采集完成后可交由后台读取。 */ +@OnlyIn(Dist.CLIENT) +public record SectionGeometryData(long origin, int modes, VoxelContoursShape[] shapes, int[] temperatures, int[] visibleFaces) { + + public static final int INCLUDE_TEMPERATURE = 1; + + public VoxelContoursShape shape(int x, int y, int z) { + return x < -1 || y < -1 || z < -1 || x > 16 || y > 16 || z > 16 ? VoxelContoursShape.EMPTY : shapes[index(x, y, z)]; + } + + 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/level/SectionOccupancy.java b/src/main/java/com/modularmc/mmclutils/client/level/SectionOccupancy.java new file mode 100644 index 0000000..878a967 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/SectionOccupancy.java @@ -0,0 +1,44 @@ +package com.modularmc.mmclutils.client.level; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +/** Fixed-size primitive pages. Ownership transfers after capture, avoiding a final whole-grid flatten/copy. */ +@OnlyIn(Dist.CLIENT) +public final class SectionOccupancy { + + 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/client/model/BlockModelRotations.java b/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotations.java new file mode 100644 index 0000000..035003f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/BlockModelRotations.java @@ -0,0 +1,70 @@ +package com.modularmc.mmclutils.client.model; + +import net.minecraft.core.Direction; + +import lombok.Getter; + +/** + * All possible rotations for a fully orientable block. + *
    - *
  • 读到的值与逐格调用 {@code Level.getBlockState} 相同,未加载的区块也和它一样按需取:高度范围外与空区块整段是虚空空气,全空气区段整段是空气, + *
  • 默认只读已加载的区块。未加载、高度范围外与空区块整段是虚空空气,全空气区段整段是空气, * 其余区段用调色板判断能否跳过,调试世界退回逐格读取
  • *
  • {@link #betweenClosed}/{@link #inRange}/{@link #withinManhattan}:对某维度直接做 {@link SectionScan} 的三种扫描,betweenClosed * 的角点顺序随意, @@ -44,7 +44,7 @@ public enum Unloaded { private int baseX, baseY, baseZ; public LevelSections(Level level) { - this(level, Unloaded.LOAD); + this(level, Unloaded.SKIP); } public LevelSections(Level level, Unloaded unloaded) { @@ -54,12 +54,12 @@ public LevelSections(Level level, Unloaded unloaded) { } public static int betweenClosed(Level level, BlockPos a, BlockPos b, Predicate match, int limit, Collection out) { - return betweenClosed(level, Unloaded.LOAD, a, b, match, (state, pos) -> true, limit, 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.LOAD, a, b, palette, test, limit, 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, @@ -74,12 +74,12 @@ public static int betweenClosed(Level level, Unloaded unloaded, BlockPos a, Bloc } public static int inRange(Level level, BlockPos center, BlockRange range, Predicate match, int limit, Collection out) { - return inRange(level, Unloaded.LOAD, center, range, match, (state, pos) -> true, limit, 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.LOAD, center, range, palette, test, limit, 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, @@ -94,12 +94,12 @@ public static int inRange(Level level, Unloaded unloaded, BlockPos center, Block public static int withinManhattan(Level level, BlockPos center, int rx, int ry, int rz, Predicate match, int limit, Collection out) { - return withinManhattan(level, Unloaded.LOAD, center, rx, ry, rz, match, (state, pos) -> true, limit, 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.LOAD, center, rx, ry, rz, palette, test, limit, 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, diff --git a/src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java index 1236a53..d56dea0 100644 --- a/src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java +++ b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContours.java @@ -4,8 +4,6 @@ import net.minecraft.core.Direction; import net.minecraft.util.Mth; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleComparators; @@ -18,7 +16,6 @@ /** 从区段几何数据计算并集轮廓,可在后台线程中执行。 */ @RequiredArgsConstructor -@OnlyIn(Dist.CLIENT) public final class VoxelContours { private static final double EPSILON = 1.0e-5; diff --git a/src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java index ffe766b..1871d51 100644 --- a/src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java +++ b/src/main/java/com/modularmc/mmclutils/spatial/VoxelContoursShape.java @@ -3,13 +3,10 @@ import com.modularmc.mmclutils.client.level.SectionOccupancy; import net.minecraft.core.Direction; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; import java.util.Arrays; -/** Owned coordinates and occupied runs, safely published after capture and never mutated by workers. */ -@OnlyIn(Dist.CLIENT) +/** 构造时接管坐标和占用区间。读取方共享同一份数据,交付后各方均只读。 */ public record VoxelContoursShape(double[] x, double[] y, double[] z, SectionOccupancy runs) { public static final VoxelContoursShape EMPTY = new VoxelContoursShape(new double[] { 0 }, new double[] { 0 }, new double[] { 0 }, new SectionOccupancy()); diff --git a/src/main/java/com/modularmc/mmclutils/spatial/VoxelShapes.java b/src/main/java/com/modularmc/mmclutils/spatial/VoxelShapes.java index e2dcdca..be0150a 100644 --- a/src/main/java/com/modularmc/mmclutils/spatial/VoxelShapes.java +++ b/src/main/java/com/modularmc/mmclutils/spatial/VoxelShapes.java @@ -7,15 +7,12 @@ import net.minecraft.world.phys.shapes.DiscreteVoxelShape; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; import it.unimi.dsi.fastutil.doubles.DoubleList; import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; import org.jspecify.annotations.Nullable; -/** Client-thread identity cache. Both coordinate copying and grid sampling yield to the tick budget. */ -@OnlyIn(Dist.CLIENT) +/** 在所属线程按形状实例缓存采样结果。坐标复制和网格读取均按时限分步进行。 */ public final class VoxelShapes { private static final long MAX_CELLS = 65_536; @@ -26,11 +23,13 @@ public final class VoxelShapes { public @Nullable VoxelContoursShape capture(VoxelShape shape, long deadline) { if (shape == Shapes.block()) return VoxelContoursShape.BLOCK; if (shape == Shapes.empty()) return VoxelContoursShape.EMPTY; - if (!shapes.containsKey(shape)) { - shapes.put(shape, new Capture(shape)); + 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 shapes.getAndMoveToLast(shape).advance(deadline); + return capture.advance(deadline); } public void clear() { @@ -67,7 +66,7 @@ private Capture(VoxelShape shape) { while (axis < 3) { if (System.nanoTime() >= deadline) return null; double value = source[axis].getDouble(coordinate); - if (!Double.isFinite(value)) throw new IllegalArgumentException("Non-finite vision shape coordinate"); + if (!Double.isFinite(value)) throw new IllegalArgumentException("体素形状包含非有限坐标"); coordinates[axis][coordinate++] = value; if (coordinate == coordinates[axis].length) { coordinate = 0; From a06db7c89a6ff7a200bdbbb7374293fc74e030e0 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 12:34:58 +0800 Subject: [PATCH 18/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E6=A8=A1=E5=9E=8B=E7=BB=84=E5=90=88=E5=92=8C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E7=BA=B9=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/client/model/BlockTintView.java | 61 ++++++++++++ .../mmclutils/client/model/ClientModels.java | 95 +++++++++++++++++++ .../client/model/ConnectedModels.java | 65 +++++++++++++ .../mmclutils/client/model/ItemModelData.java | 39 ++++++++ .../render/texture/TextureMetadata.java | 29 ++++++ 5 files changed, 289 insertions(+) create mode 100644 src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/model/ConnectedModels.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/model/ItemModelData.java create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/texture/TextureMetadata.java 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..67baad8 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/BlockTintView.java @@ -0,0 +1,61 @@ +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/ClientModels.java b/src/main/java/com/modularmc/mmclutils/client/model/ClientModels.java index 4c1d81a..5353dd1 100644 --- a/src/main/java/com/modularmc/mmclutils/client/model/ClientModels.java +++ b/src/main/java/com/modularmc/mmclutils/client/model/ClientModels.java @@ -4,12 +4,17 @@ 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; @@ -18,6 +23,7 @@ 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; @@ -26,6 +32,8 @@ import it.unimi.dsi.fastutil.objects.ObjectList; import org.jspecify.annotations.Nullable; +import java.util.List; + /** 通过当前资源版本的原版模型解析器和提交器操作模型。 */ public final class ClientModels { @@ -68,6 +76,18 @@ public static void submitBlock(BlockState block, BlockDisplayContext context, Po 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 QuadMeshes.Face(quad, null)); @@ -77,4 +97,79 @@ public static ObjectList quads(BlockStateModel model, RandomSou } 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/ConnectedModels.java b/src/main/java/com/modularmc/mmclutils/client/model/ConnectedModels.java new file mode 100644 index 0000000..63a4d2c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/ConnectedModels.java @@ -0,0 +1,65 @@ +package com.modularmc.mmclutils.client.model; + +import com.modularmc.mmclutils.client.render.quad.MutableQuadView; +import com.modularmc.mmclutils.client.render.quad.QuadGeometry; +import com.modularmc.mmclutils.client.render.quad.QuadMeshes; +import com.modularmc.mmclutils.client.render.quad.QuadView; + +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; + +import it.unimi.dsi.fastutil.objects.ObjectList; +import org.joml.Vector3f; + +/** 切分四边形并为子面指定贴图。连接条件和材质由调用方决定。 */ +public final class ConnectedModels { + + private ConnectedModels() {} + + /** 四份材质按从左到右、从上到下排列。每个子面映射整个新贴图。 */ + public static ObjectList quadrants(QuadMeshes.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 QuadMeshes.Face patch(QuadMeshes.Face input, float u0, float v0, float u1, float v1, MaterialInfo material) { + if (!(u0 >= 0 && u1 <= 1 && u0 < u1 && v0 >= 0 && v1 <= 1 && v0 < v1)) { + throw new IllegalArgumentException("子面范围须在零至一之间"); + } + QuadView source = QuadView.of(input.quad(), input.cullFace()); + var output = new MutableQuadView(source); + var a = new Vector3f(); + var b = new Vector3f(); + var scratch = new Vector3f(); + boolean normals = (source.packedNormal(0) | source.packedNormal(1) | source.packedNormal(2) | source.packedNormal(3)) != 0; + 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)); + if (normals) { + QuadGeometry.vertexNormal(source, 0, a).lerp(QuadGeometry.vertexNormal(source, 3, scratch), u); + QuadGeometry.vertexNormal(source, 1, b).lerp(QuadGeometry.vertexNormal(source, 2, scratch), u); + a.lerp(b, v); + if (a.lengthSquared() > 0) output.normal(vertex, a.normalize()); + else output.packedNormal(vertex, 0); + } + } + QuadGeometry.interpolate(source, output, source.lightFace().getAxis()); + output.material(material); + var sprite = material.sprite(); + output.uv(0, sprite.getU0(), sprite.getV0()).uv(1, sprite.getU0(), sprite.getV1()) + .uv(2, sprite.getU1(), sprite.getV1()).uv(3, sprite.getU1(), sprite.getV0()); + return new QuadMeshes.Face(output.bake(), output.cullFace()); + } + + /** 两条相邻边及夹角按三个位存储,可作为材质数组索引。 */ + public static int connectionMask(boolean horizontal, boolean vertical, boolean diagonal) { + return (horizontal ? 1 : 0) | (vertical ? 2 : 0) | (horizontal && vertical && diagonal ? 4 : 0); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ItemModelData.java b/src/main/java/com/modularmc/mmclutils/client/model/ItemModelData.java new file mode 100644 index 0000000..af6fe8d --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/ItemModelData.java @@ -0,0 +1,39 @@ +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 ItemModelData { + + private ItemModelData() {} + + 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/render/texture/TextureMetadata.java b/src/main/java/com/modularmc/mmclutils/client/render/texture/TextureMetadata.java new file mode 100644 index 0000000..1aecf65 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/texture/TextureMetadata.java @@ -0,0 +1,29 @@ +package com.modularmc.mmclutils.client.render.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() {} + + 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); + } + + 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(); + } +} From df43163c1da1bdba6086860ba69fff4e9ae1a12a Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 12:34:58 +0800 Subject: [PATCH 19/79] =?UTF-8?q?=E6=8E=A5=E5=85=A5=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=B4=B4=E5=9B=BE=E5=92=8C=E5=9B=BE=E7=89=87=E5=88=86=E5=9D=97?= =?UTF-8?q?=E7=BB=84=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../client/render/texture/ImageTextures.java | 239 ++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 src/main/java/com/modularmc/mmclutils/client/render/texture/ImageTextures.java diff --git a/src/main/java/com/modularmc/mmclutils/client/render/texture/ImageTextures.java b/src/main/java/com/modularmc/mmclutils/client/render/texture/ImageTextures.java new file mode 100644 index 0000000..8ccb9ad --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/texture/ImageTextures.java @@ -0,0 +1,239 @@ +package com.modularmc.mmclutils.client.render.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); + } + + 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; + } + + 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) {} +} From ef112bbf2c0eb9f5adca1fbc527cd0e6cbe574fe Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 12:34:59 +0800 Subject: [PATCH 20/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E9=80=9A=E7=94=A8?= =?UTF-8?q?=E5=9B=BE=E8=B7=AF=E7=94=B1=E4=B8=8E=E8=A1=A5=E5=85=85=E9=9B=86?= =?UTF-8?q?=E5=90=88=E7=BC=96=E8=A7=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../serialization/CollectionCodecs.java | 31 ++++ .../mmclutils/spatial/GraphRouting.java | 171 ++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 src/main/java/com/modularmc/mmclutils/spatial/GraphRouting.java diff --git a/src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java b/src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java index 4254ec9..daf559d 100644 --- a/src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java +++ b/src/main/java/com/modularmc/mmclutils/serialization/CollectionCodecs.java @@ -1,15 +1,19 @@ package com.modularmc.mmclutils.serialization; +import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +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.Supplier; /** 用原版 Codec 读写集合,并在解码时选用适合用途的容器。 */ public final class CollectionCodecs { @@ -43,4 +47,31 @@ public static , V> Codec> enumMap(Class type, Cod 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(); + } } diff --git a/src/main/java/com/modularmc/mmclutils/spatial/GraphRouting.java b/src/main/java/com/modularmc/mmclutils/spatial/GraphRouting.java new file mode 100644 index 0000000..8bfa723 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/spatial/GraphRouting.java @@ -0,0 +1,171 @@ +package com.modularmc.mmclutils.spatial; + +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectHeapPriorityQueue; +import it.unimi.dsi.fastutil.objects.ObjectList; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.concurrent.CancellationException; + +/** 为节点布置层级,并在二维矩形之间计算可复用的水平及竖直折线。 */ +public final class GraphRouting { + + private GraphRouting() {} + + /** 按边方向将有向无环图分层。节点编号须在零到 nodeCount 之间,含环的图应先提供其分组。 */ + public static ObjectList layers(int nodeCount, Iterable edges) { + var outgoing = new IntArrayList[nodeCount]; + var pending = new IntArrayFIFOQueue(); + var degree = new int[nodeCount]; + var ranks = new int[nodeCount]; + for (Edge edge : edges) { + int from = edge.from(), to = edge.to(); + if (outgoing[from] == null) outgoing[from] = new IntArrayList(); + outgoing[from].add(to); + degree[to]++; + } + for (int node = 0; node < nodeCount; node++) if (degree[node] == 0) pending.enqueue(node); + var layers = new ObjectArrayList(); + int visited = 0; + while (!pending.isEmpty()) { + int node = pending.dequeueInt(); + int rank = ranks[node]; + if (layers.size() == rank) layers.add(new IntArrayList()); + layers.get(rank).add(node); + visited++; + IntArrayList next = outgoing[node]; + if (next == null) continue; + for (int index = 0; index < next.size(); index++) { + int child = next.getInt(index); + ranks[child] = Math.max(ranks[child], rank + 1); + if (--degree[child] == 0) pending.enqueue(child); + } + } + if (visited != nodeCount) throw new IllegalArgumentException("图中存在未分组的环"); + var result = new ObjectArrayList(layers.size()); + for (IntArrayList layer : layers) result.add(IntList.of(layer.toIntArray())); + return ObjectList.of(result.toArray(IntList[]::new)); + } + + /** 避开矩形内部的最短正交折线。允许沿边界经过。无路径时返回空列表。 */ + public static ObjectList route(Point start, Point end, Collection obstacles) { + if (start.equals(end)) return ObjectList.of(start); + int length = Math.addExact(2, Math.multiplyExact(obstacles.size(), 2)); + double[] xs = new double[length], ys = new double[length]; + xs[0] = start.x(); + xs[1] = end.x(); + ys[0] = start.y(); + ys[1] = end.y(); + int index = 2; + for (Bounds obstacle : obstacles) { + if (obstacle.containsInterior(start) || obstacle.containsInterior(end)) return ObjectList.of(); + xs[index] = obstacle.left(); + ys[index++] = obstacle.top(); + xs[index] = obstacle.right(); + ys[index++] = obstacle.bottom(); + } + xs = Arrays.stream(xs).distinct().sorted().toArray(); + ys = Arrays.stream(ys).distinct().sorted().toArray(); + return new Grid(xs, ys, obstacles).route(start, end); + } + + public record Edge(int from, int to) {} + + public record Point(double x, double y) { + + public Point { + if (!Double.isFinite(x) || !Double.isFinite(y)) throw new IllegalArgumentException("折线坐标须为有限值"); + } + } + + public record Bounds(double left, double top, double right, double bottom) { + + public Bounds { + if (!(left < right && top < bottom) || !Double.isFinite(left) || !Double.isFinite(top) || !Double.isFinite(right) || !Double.isFinite(bottom)) { + throw new IllegalArgumentException("折线路由的阻挡矩形无效"); + } + } + + public boolean containsInterior(Point point) { + return point.x() > left && point.x() < right && point.y() > top && point.y() < bottom; + } + } + + private record Step(int index, double length) {} + + private static final class Grid { + + private final double[] xs; + private final double[] ys; + private final Collection obstacles; + private final double[] distances; + private final Int2IntOpenHashMap parents = new Int2IntOpenHashMap(); + private final ObjectHeapPriorityQueue pending = new ObjectHeapPriorityQueue<>( + Comparator.comparingDouble(Step::length).thenComparingInt(Step::index)); + + private Grid(double[] xs, double[] ys, Collection obstacles) { + this.xs = xs; + this.ys = ys; + this.obstacles = obstacles; + distances = new double[Math.multiplyExact(xs.length, ys.length)]; + Arrays.fill(distances, Double.POSITIVE_INFINITY); + parents.defaultReturnValue(-1); + } + + private ObjectList route(Point start, Point end) { + int from = node(start), to = node(end); + distances[from] = 0; + pending.enqueue(new Step(from, 0)); + while (!pending.isEmpty()) { + if (Thread.currentThread().isInterrupted()) throw new CancellationException(); + Step step = pending.dequeue(); + if (step.length() != distances[step.index()]) continue; + if (step.index() == to) return path(to); + int x = step.index() % xs.length, y = step.index() / xs.length; + if (x > 0) visit(step, x, y, x - 1, y); + if (x + 1 < xs.length) visit(step, x, y, x + 1, y); + if (y > 0) visit(step, x, y, x, y - 1); + if (y + 1 < ys.length) visit(step, x, y, x, y + 1); + } + return ObjectList.of(); + } + + private int node(Point point) { + return Arrays.binarySearch(ys, point.y()) * xs.length + Arrays.binarySearch(xs, point.x()); + } + + private void visit(Step from, int x, int y, int tx, int ty) { + double x0 = xs[x], y0 = ys[y], x1 = xs[tx], y1 = ys[ty]; + int node = ty * xs.length + tx; + double length = from.length() + Math.abs(x1 - x0) + Math.abs(y1 - y0); + if (length >= distances[node]) return; + for (Bounds obstacle : obstacles) { + if (Math.max(x0, x1) > obstacle.left() && Math.min(x0, x1) < obstacle.right() && Math.max(y0, y1) > obstacle.top() && Math.min(y0, y1) < obstacle.bottom()) return; + } + distances[node] = length; + parents.put(node, from.index()); + pending.enqueue(new Step(node, length)); + } + + private ObjectList path(int node) { + var path = new ObjectArrayList(); + while (node >= 0) { + var point = new Point(xs[node % xs.length], ys[node / xs.length]); + int size = path.size(); + if (size > 1) { + Point previous = path.get(size - 1), before = path.get(size - 2); + if ((before.x() == previous.x() && previous.x() == point.x()) || (before.y() == previous.y() && previous.y() == point.y())) path.removeLast(); + } + path.add(point); + node = parents.get(node); + } + return ObjectList.of(path.reversed().toArray(Point[]::new)); + } + } +} From f491f7c7c8f21732af07b91d427bd1b44c656c3c Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 12:34:59 +0800 Subject: [PATCH 21/79] =?UTF-8?q?=E8=A1=A5=E5=85=85=E8=B5=84=E6=BA=90?= =?UTF-8?q?=E5=8C=85=E5=92=8C=E6=8F=90=E7=A4=BA=E6=96=87=E6=9C=AC=E5=B7=A5?= =?UTF-8?q?=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/client/gui/Tooltips.java | 41 +++++++++++++++++++ .../mmclutils/resource/ResourcePacks.java | 33 +++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 src/main/java/com/modularmc/mmclutils/client/gui/Tooltips.java create mode 100644 src/main/java/com/modularmc/mmclutils/resource/ResourcePacks.java diff --git a/src/main/java/com/modularmc/mmclutils/client/gui/Tooltips.java b/src/main/java/com/modularmc/mmclutils/client/gui/Tooltips.java new file mode 100644 index 0000000..a52dec0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/gui/Tooltips.java @@ -0,0 +1,41 @@ +package com.modularmc.mmclutils.client.gui; + +import com.modularmc.mmclutils.color.ColorMath; + +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; + +import java.util.function.UnaryOperator; + +/** 生成提示文本的渐变和周期颜色。时间由绘制调用方传入,可与界面动画复用同一时钟。 */ +public final class Tooltips { + + private Tooltips() {} + + public static UnaryOperator

+ * This code is from + * Applied + * Energistics 2, + * licensed as LGPL 3.0. + */ +public enum BlockModelRotations { + + // DUNSWE -> SWNE + 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), // Default + 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 BlockModelRotations[] VALUES = values(); + + @Getter + private final int angleX; + @Getter + private final int angleY; + @Getter + private final int angleZ; + + BlockModelRotations(int angleX, int angleY, int angleZ) { + this.angleX = angleX; + this.angleY = angleY; + this.angleZ = angleZ; + } + + /** + * Gets the block orientation in which the block's front and top are facing the specified directions. + */ + public static BlockModelRotations get(Direction frontFacing, Direction upwardsFacing) { + return VALUES[frontFacing.get3DDataValue() * 4 + upwardsFacing.get2DDataValue()]; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/model/ClientModels.java b/src/main/java/com/modularmc/mmclutils/client/model/ClientModels.java new file mode 100644 index 0000000..4c1d81a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/model/ClientModels.java @@ -0,0 +1,80 @@ +package com.modularmc.mmclutils.client.model; + +import com.modularmc.mmclutils.client.render.quad.QuadMeshes; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.SubmitNodeCollector; +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.model.BlockDisplayContext; +import net.minecraft.client.renderer.item.ItemModel; +import net.minecraft.client.renderer.item.ItemStackRenderState; +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.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; + +/** 通过当前资源版本的原版模型解析器和提交器操作模型。 */ +public final class ClientModels { + + private static final Direction[] DIRECTIONS = Direction.values(); + + private ClientModels() {} + + 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); + var result = new ObjectArrayList(); + for (BlockStateModelPart part : parts) { + for (var quad : part.getQuads(null)) result.add(new QuadMeshes.Face(quad, null)); + for (Direction direction : DIRECTIONS) { + for (var quad : part.getQuads(direction)) result.add(new QuadMeshes.Face(quad, direction)); + } + } + return new ObjectImmutableList<>(result); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/MatrixTransforms.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/MatrixTransforms.java new file mode 100644 index 0000000..bb9b5dc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/MatrixTransforms.java @@ -0,0 +1,157 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.minecraft.util.Util; + +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; +import com.google.common.collect.Tables; +import org.jetbrains.annotations.Contract; +import org.joml.*; + +import java.lang.Math; +import java.security.InvalidParameterException; +import java.util.EnumMap; +import java.util.Map; + +public class MatrixTransforms { + + private static final Map directionAxes = Util.make(new EnumMap<>(Direction.class), map -> { + for (Direction dir : Direction.values()) { + map.put(dir, dir.step()); + } + }); + private static final Table rotations = Tables + .synchronizedTable(HashBasedTable.create()); + + /** + * @param from the original vector + * @param to the wanted vector + * @return the angle of rotation to make {@code from} point in the direction of {@code to} + */ + @Contract(pure = true) + public static float getRotationAngle(final Vector3fc from, final Vector3fc to) { + return (float) Math.acos(from.dot(to)); + } + + /** + * This method isn't pure, {@code from} will be modified! + * + * @param from the original vector + * @param to the wanted vector + * @return the axis of rotation to make {@code from} point in the direction of {@code to} + */ + public static Vector3f getRotationAxis(Vector3f from, final Vector3fc to) { + return getRotationAxis(from, to, from); + } + + /** + * @param from the original vector + * @param to the wanted vector + * @param dest the vector to save the result to + * @return {@code dest} + */ + public static Vector3f getRotationAxis(final Vector3fc from, final Vector3fc to, Vector3f dest) { + return from.cross(to, dest).normalize(); + } + + /** + * @param from the original vector + * @param to the wanted vector + * @return the quaternion to make {@code from} point in the direction of {@code to} + */ + @Contract(pure = true) + public static Quaternionf getRotation(final Vector3fc from, final Vector3fc to) { + return from.rotationTo(to, new Quaternionf()); + } + + /** + * @param from the original direction + * @param to the wanted direction + * @return the quaternion to make a vector based on {@code from} point towards {@code to} + */ + @Contract(pure = true) + public static Quaternionf getRotation(final Direction from, final Direction to) { + return getRotation(getDirectionAxis(from), getDirectionAxis(to)); + } + + /** + * Transforms the {@code matrix} and all {@code additional} vectors such that the {@code from} vector will be on the + * {@code to} vector's axis + * + * @param matrix the matrix to transform + * @param from the original vector + * @param to the destination vector + * @param additional additional vectors to transform + */ + public static void rotateMatrix(Matrix4f matrix, Vector3f from, Vector3fc to, Vector3f... additional) { + if (from.equals(to)) { + return; + } + if (-from.x() == to.x() && -from.y() == to.y() && -from.z() == to.z()) { + rotateMatrix(matrix, Mth.PI, getDirectionAxis(Direction.UP), additional); + } else { + var angle = getRotationAngle(from, to); + getRotationAxis(from, to); + rotateMatrix(matrix, angle, from, additional); + } + } + + /** + * @param matrix the matrix to transform + * @param angle the angle of rotation (radians) + * @param axis axis of rotation + * @param additional additional vectors to transform + */ + public static void rotateMatrix(Matrix4f matrix, float angle, Vector3fc axis, Vector3f... additional) { + matrix.rotate(angle, axis); + for (var vec : additional) { + vec.rotateAxis(angle, axis.x(), axis.y(), axis.z()); + } + } + + /** + * @param upward the {@code upwardFacing} of the machine + * @return the angle of rotation (in radians) along the front face axis to get the correct orientation + */ + public static float upwardFacingAngle(Direction upward) { + return switch (upward) { + case NORTH -> 0; + case SOUTH -> 2; + case WEST -> 3; + case EAST -> 1; + default -> throw new InvalidParameterException("Upward facing can't be up/down"); + } * Mth.HALF_PI; + } + + public static Vector3f rotateMatrixToFront(Matrix4f matrix, Direction frontFace) { + // rotate frontFacing to correct cardinal direction + var front = frontFace.step(); + rotateMatrix(matrix, Direction.NORTH.step(), getDirectionAxis(frontFace), front); + return front; + } + + public static void rotateMatrixToUp(Matrix4f matrix, Vector3f front, Direction upwardsFace) { + // rotate upwards face to the correct orientation + rotateMatrix(matrix, upwardFacingAngle(upwardsFace), front); + } + + public static Matrix4fc createRotationState(Direction frontFace, Direction upwardFace) { + if (rotations.contains(frontFace, upwardFace)) { + var rotation = rotations.get(frontFace, upwardFace); + assert rotation != null; + return rotation; + } + var matrix = new Matrix4f(); + var front = rotateMatrixToFront(matrix, frontFace); + front.absolute(); + rotateMatrixToUp(matrix, front, upwardFace); + rotations.put(frontFace, upwardFace, matrix); + return matrix; + } + + public static Vector3fc getDirectionAxis(Direction dir) { + return directionAxes.get(dir); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/geometry/OrbitGeometry.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/OrbitGeometry.java new file mode 100644 index 0000000..28e3062 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/OrbitGeometry.java @@ -0,0 +1,51 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +/** 在水平面上计算沿圆周扫过的径向线段。角度以弧度表示。 */ +public final class OrbitGeometry { + + private OrbitGeometry() {} + + public static AABB bounds(Vec3 center, Sweep sweep) { + AABB bounds = segmentBounds(center, sweep, sweep.startAngle()); + for (int i = 1; i <= sweep.steps(); i++) bounds = bounds.minmax(segmentBounds(center, sweep, sweep.angle(i))); + return bounds.inflate(sweep.halfWidth(), sweep.halfHeight(), sweep.halfWidth()); + } + + public static boolean intersects(AABB target, Vec3 center, Sweep sweep) { + AABB expanded = target.inflate(sweep.halfWidth(), sweep.halfHeight(), sweep.halfWidth()); + for (int i = 0; i <= sweep.steps(); i++) { + double angle = sweep.angle(i); + Vec3 start = point(center, angle, sweep.innerRadius()); + Vec3 end = point(center, angle, sweep.outerRadius()); + if (expanded.contains(start) || expanded.contains(end) || expanded.clip(start, end).isPresent()) return true; + } + return false; + } + + private static AABB segmentBounds(Vec3 center, Sweep sweep, double angle) { + return new AABB(point(center, angle, sweep.innerRadius()), point(center, angle, sweep.outerRadius())); + } + + public static Vec3 point(Vec3 center, double angle, double radius) { + return center.add(Math.cos(angle) * radius, 0, -Math.sin(angle) * radius); + } + + /** 起止角度、径向端点以及水平和垂直扩张。交集和包围盒使用相同的采样点。 */ + public record Sweep(double startAngle, double endAngle, double innerRadius, double outerRadius, + double halfWidth, double halfHeight, int steps) { + + public Sweep { + if (!Double.isFinite(startAngle) || !Double.isFinite(endAngle) || !Double.isFinite(innerRadius) || !Double.isFinite(outerRadius) || !Double.isFinite(halfWidth) || !Double.isFinite(halfHeight) || innerRadius < 0 || innerRadius > outerRadius || halfWidth < 0 || halfHeight < 0 || steps < 1) { + throw new IllegalArgumentException("轨道几何参数超出范围"); + } + } + + public double angle(int step) { + double fraction = (double) step / steps; + return (1 - fraction) * startAngle + fraction * endAngle; + } + } +} 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..d7e2b8c --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/SectionGeometryRenderer.java @@ -0,0 +1,179 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.modularmc.mmclutils.client.level.SectionGeometryData; +import com.modularmc.mmclutils.concurrent.BoundedVirtualTaskQueue; +import com.modularmc.mmclutils.spatial.VoxelContours; +import com.modularmc.mmclutils.spatial.VoxelContoursShape; + +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() {} + + 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, SectionGeometryData data, Style style) { + queue.submit(key, work -> build(data, style, work::cancelled, work::emit)); + } + + /** 每个已交付批次的关闭责任转交给回调。色值的透明分量为零时跳过对应图元。 */ + public static void build(SectionGeometryData 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, VoxelContoursShape 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) { + + public Style(int surfaceColor, int outlineColor) { + this(ignored -> surfaceColor, outlineColor); + } + } + + /** 一批顶点和区段原点的打包坐标。可在任意线程关闭,在渲染线程上传。 */ + public record Batch(long origin, MeshData mesh, ByteBufferBuilder memory) implements AutoCloseable { + + 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/StaticMesh.java b/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java new file mode 100644 index 0000000..604b65f --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/StaticMesh.java @@ -0,0 +1,67 @@ +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..333921a --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/geometry/VertexWriters.java @@ -0,0 +1,34 @@ +package com.modularmc.mmclutils.client.render.geometry; + +import com.modularmc.mmclutils.client.render.quad.QuadGeometry; +import com.modularmc.mmclutils.client.render.quad.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() {} + + 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), QuadGeometry.vertexNormal(quad, index, normal)); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/quad/BakedQuadView.java b/src/main/java/com/modularmc/mmclutils/client/render/quad/BakedQuadView.java new file mode 100644 index 0000000..57cd519 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/quad/BakedQuadView.java @@ -0,0 +1,42 @@ +package com.modularmc.mmclutils.client.render.quad; + +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 record BakedQuadView(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/quad/Interpolation.java b/src/main/java/com/modularmc/mmclutils/client/render/quad/Interpolation.java new file mode 100644 index 0000000..2cfd8fa --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/quad/Interpolation.java @@ -0,0 +1,120 @@ +/* + * 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.render.quad; + +import net.minecraft.util.Mth; + +/** + * @author covers1624 + */ +public class Interpolation { + + 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; + + /** + * Resets the interpolation helper with the given quad. Does not care what order the vertices are in. + */ + 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; + } + + /** + * Call when you are ready to use the interpolation helper. + */ + public void setup() { + this.p00 = 0; // Bottom Left is always first. + 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) { + // Bottom right. + this.p10 = i; + this.x1 = x; + } else if (this.x0 == x) { + // Top left. + this.p01 = i; + this.y1 = y; + } else { + // Top right. + this.p11 = i; + } + } + } + + /** + * Computes the coefficients for the interpolation. + * + * @param x X interpolation location. + * @param y Y interpolation location. + */ + 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); + } + + /** + * Interpolates using the already computed coefficients. + * + * @param q0 Value at dx0 dy0 + * @param q1 Value at dx1 dy1 + * @param q2 Value at dx2 dy2 + * @param q3 Value at dx3 dy3 + * @return The result. + */ + 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/render/quad/MutableQuadView.java b/src/main/java/com/modularmc/mmclutils/client/render/quad/MutableQuadView.java new file mode 100644 index 0000000..7d203f3 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/quad/MutableQuadView.java @@ -0,0 +1,144 @@ +package com.modularmc.mmclutils.client.render.quad; + +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) { + this.material = material; + Arrays.fill(colors, -1); + } + + 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; + } + + @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]; + } + + public MutableQuadView packedUv(int vertex, long packedUv) { + uv[vertex] = packedUv; + return this; + } + + 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]; + } + + 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)); + } + + @Override + public int color(int vertex) { + return colors[vertex]; + } + + public MutableQuadView color(int vertex, int argb) { + colors[vertex] = argb; + return this; + } + + 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; + } + + 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/render/quad/QuadGeometry.java b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadGeometry.java new file mode 100644 index 0000000..7d59d17 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadGeometry.java @@ -0,0 +1,86 @@ +package com.modularmc.mmclutils.client.render.quad; + +import net.minecraft.core.Direction; +import net.minecraft.util.ARGB; +import net.neoforged.neoforge.client.model.quad.BakedNormals; + +import org.joml.Vector3f; +import org.joml.Vector3fc; + +/** 计算四边形的法线、光照面和对齐情况。 */ +public final class QuadGeometry { + + private QuadGeometry() {} + + 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; + 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)) { + sample(source, target, i, point.get(x), point.get(y), x, y, 2, 3, true); + } + } + } + + private static boolean sample(QuadView source, MutableQuadView target, int index, float px, float py, + int axisX, int axisY, int b, int c, boolean extend) { + 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))); + 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); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadMeshes.java b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadMeshes.java new file mode 100644 index 0000000..ebc94a9 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadMeshes.java @@ -0,0 +1,83 @@ +package com.modularmc.mmclutils.client.render.quad; + +import com.modularmc.mmclutils.client.render.texture.TextureCoordinates; + +import net.minecraft.client.resources.model.geometry.BakedQuad; +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.core.Direction; +import net.minecraft.world.phys.AABB; + +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; + +/** 按原版剔除方向组织烘焙面,并提供可复用的批量变换入口。 */ +public final class QuadMeshes { + + private QuadMeshes() {} + + 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 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; + } + }; + TextureCoordinates.bake(TextureCoordinates.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) {} +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadTransforms.java b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadTransforms.java new file mode 100644 index 0000000..1e36643 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadTransforms.java @@ -0,0 +1,132 @@ +package com.modularmc.mmclutils.client.render.quad; + +import com.modularmc.mmclutils.client.render.texture.TextureCoordinates; + +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.core.Direction; +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 QuadTransforms() {} + + 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(QuadGeometry.lightFace(QuadGeometry.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; + }; + } + + 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 -> { + TextureCoordinates.replace(quad, replacement); + return true; + }; + } + + public static Transform lockUv(Direction face) { + return quad -> { + TextureCoordinates.bake(TextureCoordinates.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 (!QuadGeometry.isParallel(quad, axis, 0.00001f)) return clamp.apply(quad); + var source = new MutableQuadView(quad); + clamp.apply(quad); + QuadGeometry.interpolate(source, quad, axis); + return true; + }; + } + + 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/render/quad/QuadView.java b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadView.java new file mode 100644 index 0000000..dd089f0 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/quad/QuadView.java @@ -0,0 +1,50 @@ +package com.modularmc.mmclutils.client.render.quad; + +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)); + } + + /** 包装原版烘焙四边形。传入该面所在的剔除分组,通用面传空值。 */ + static QuadView of(BakedQuad quad, @Nullable Direction cullFace) { + return new BakedQuadView(quad, cullFace); + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/render/texture/SpriteLookup.java b/src/main/java/com/modularmc/mmclutils/client/render/texture/SpriteLookup.java new file mode 100644 index 0000000..868b827 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/texture/SpriteLookup.java @@ -0,0 +1,81 @@ +package com.modularmc.mmclutils.client.render.texture; + +import com.modularmc.mmclutils.client.render.quad.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); + } + + 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/render/texture/TextureCoordinates.java b/src/main/java/com/modularmc/mmclutils/client/render/texture/TextureCoordinates.java new file mode 100644 index 0000000..3b2f336 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/render/texture/TextureCoordinates.java @@ -0,0 +1,92 @@ +package com.modularmc.mmclutils.client.render.texture; + +import com.modularmc.mmclutils.client.render.quad.MutableQuadView; +import com.modularmc.mmclutils.client.render.quad.QuadView; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.geometry.BakedQuad.MaterialInfo; +import net.minecraft.core.Direction; + +import org.joml.Vector3fc; + +/** 处理局部 UV、图集 UV 和按方块朝向锁定的 UV。局部范围为零至一。 */ +public final class TextureCoordinates { + + private TextureCoordinates() {} + + 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()); + } + + 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; + } + + 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; + } + + 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); + } + + 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; + } +} From 3158e666dc2c8b58b08e9543f760f3979950d43a Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 02:36:42 +0800 Subject: [PATCH 12/79] =?UTF-8?q?=E6=8E=A5=E5=85=A5=E7=BB=84=E5=90=88?= =?UTF-8?q?=E9=94=AE=E9=85=8D=E7=BD=AE=E4=B8=8E=E5=B1=8F=E5=B9=95=E7=9B=91?= =?UTF-8?q?=E5=90=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/client/input/ClientInput.java | 9 ++ .../client/input/ClientKeyBindings.java | 60 ++++++++- .../client/input/KeyChordMapping.java | 121 ++++++++++++++++++ .../client/input/KeyBindsScreenMixin.java | 63 +++++++++ .../mixin/client/input/OptionsMixin.java | 26 ++++ src/main/resources/mmclutils.mixins.json | 2 + 6 files changed, 276 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/client/input/KeyBindsScreenMixin.java create mode 100644 src/main/java/com/modularmc/mmclutils/mixin/client/input/OptionsMixin.java diff --git a/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java b/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java index 22847a5..19c065e 100644 --- a/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientInput.java @@ -17,6 +17,7 @@ public final class ClientInput { public static final int SHIFT = 2; public static final int ALT = 4; public static final int COMMAND = 8; + public static final int ALL_MODIFIERS = CONTROL | SHIFT | ALT | COMMAND; private ClientInput() {} @@ -34,6 +35,14 @@ public static int modifierBit(KeyModifier modifier) { }; } + 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; diff --git a/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java b/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java index 58bf0f4..641aa61 100644 --- a/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java +++ b/src/main/java/com/modularmc/mmclutils/client/input/ClientKeyBindings.java @@ -6,6 +6,8 @@ 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; @@ -16,7 +18,7 @@ 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.settings.KeyModifier; +import net.neoforged.neoforge.client.event.ScreenEvent; import com.mojang.blaze3d.platform.InputConstants; import it.unimi.dsi.fastutil.objects.Object2BooleanLinkedOpenHashMap; @@ -82,6 +84,36 @@ private static void sampleMouse(InputEvent.MouseButton.Post event) { sample(InputConstants.Type.MOUSE.getOrCreate(event.getButton()), event.getAction() == GLFW.GLFW_PRESS); } + @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(); @@ -144,6 +176,7 @@ public static final class Binding { private final Supplier factory; private final boolean configurable; private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); + private final CopyOnWriteArrayList screenListeners = new CopyOnWriteArrayList<>(); private @Nullable KeyMapping mapping; private int extraModifiers; private boolean down; @@ -165,7 +198,7 @@ public boolean isDown() { /** 增加组合键条件。控制设置中的主键和原版修饰键仍由原版存储。 */ public Binding withModifiers(int modifiers) { - if ((modifiers & ~(ClientInput.CONTROL | ClientInput.SHIFT | ClientInput.ALT | ClientInput.COMMAND)) != 0) { + if ((modifiers & ~ClientInput.ALL_MODIFIERS) != 0) { throw new IllegalArgumentException("不支持的修饰键组合 " + modifiers); } extraModifiers = modifiers; @@ -180,15 +213,24 @@ public void removeListener(Listener listener) { listeners.remove(listener); } - private KeyMapping mapping() { + 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.modifierBit(KeyModifier.getKeyModifier(mapping.getKey())); - int expected = (extraModifiers | ClientInput.modifierBit(mapping.getKeyModifier())) & ~mainModifier; + int mainModifier = ClientInput.keyModifierBit(mapping.getKey()); + int mappingModifiers = mapping instanceof KeyChordMapping chord ? chord.modifiers() : ClientInput.modifierBit(mapping.getKeyModifier()); + int expected = (extraModifiers | mappingModifiers) & ~mainModifier; return mapping.getKeyConflictContext().isActive() && (modifiers & ~mainModifier) == expected; } @@ -204,4 +246,12 @@ public interface Listener { /** 在本地绑定状态已经更新时调用。失焦与断开连接都会产生释放。 */ void changed(Binding binding, boolean down); } + + /** 在客户端线程处理屏幕按键。只向当前屏幕派发,且不会发送游戏内按键状态。 */ + @FunctionalInterface + public interface ScreenListener { + + /** 鼠标位置使用屏幕坐标。返回真时消费这次输入。 */ + 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..98c93bc --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/input/KeyChordMapping.java @@ -0,0 +1,121 @@ +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; + +/** 可在控制设置中编辑和保存的组合键。只在客户端线程读写。 */ +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; + private int modifiers; + + 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 int modifiers() { + return modifiers; + } + + /** 更换主键及完整修饰键。清除旧绑定积累的点击。 */ + public void setChord(InputConstants.Key key, int modifiers) { + this.modifiers = normalize(key, modifiers); + super.setKeyModifierAndCode(primary(this.modifiers), key); + setDown(false); + while (consumeClick()) { + // 旧绑定的点击不能触发新的组合键。 + } + } + + @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 主修饰键匹配的组合。 */ + public void processOptions(Options.FieldAccess access) { + String prefix = getKey().getName() + ":" + getKeyModifier().name() + ":"; + String current = prefix + modifiers; + String saved = access.process("mmclutils_chord_" + getName(), current); + if (!saved.startsWith(prefix) || saved.equals(current)) 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; + } +} diff --git a/src/main/java/com/modularmc/mmclutils/mixin/client/input/KeyBindsScreenMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/client/input/KeyBindsScreenMixin.java new file mode 100644 index 0000000..f3cc04b --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/client/input/KeyBindsScreenMixin.java @@ -0,0 +1,63 @@ +package com.modularmc.mmclutils.mixin.client.input; + +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/client/input/OptionsMixin.java b/src/main/java/com/modularmc/mmclutils/mixin/client/input/OptionsMixin.java new file mode 100644 index 0000000..ba8bbf4 --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/mixin/client/input/OptionsMixin.java @@ -0,0 +1,26 @@ +package com.modularmc.mmclutils.mixin.client.input; + +import com.modularmc.mmclutils.client.input.KeyChordMapping; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Options; + +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); + } + } +} diff --git a/src/main/resources/mmclutils.mixins.json b/src/main/resources/mmclutils.mixins.json index 1c0e705..82117b3 100644 --- a/src/main/resources/mmclutils.mixins.json +++ b/src/main/resources/mmclutils.mixins.json @@ -12,6 +12,8 @@ "spatial.LevelChunkMixin" ], "client": [ + "client.input.KeyBindsScreenMixin", + "client.input.OptionsMixin", "client.level.ClientChunkCacheMixin", "client.level.ClientChunkStorageMixin", "client.render.GlBufferAccessor", From 886fec80a574cf8d1a09e9d1232b780744e9592e Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 02:53:49 +0800 Subject: [PATCH 13/79] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E6=9F=A5=E8=AF=A2=E5=B9=B6=E8=BF=81=E5=85=A5?= =?UTF-8?q?=E7=94=9F=E6=88=90=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/gen_cache_maps.ps1 | 270 ++++++++++++++++++ .../hash/Object2BooleanOpenCachedHashMap.java | 2 +- ...Object2BooleanOpenCustomCachedHashMap.java | 2 +- .../hash/Object2ByteOpenCachedHashMap.java | 2 +- .../Object2ByteOpenCustomCachedHashMap.java | 2 +- .../hash/Object2CharOpenCachedHashMap.java | 2 +- .../Object2CharOpenCustomCachedHashMap.java | 2 +- .../hash/Object2DoubleOpenCachedHashMap.java | 2 +- .../Object2DoubleOpenCustomCachedHashMap.java | 2 +- .../hash/Object2FloatOpenCachedHashMap.java | 2 +- .../Object2FloatOpenCustomCachedHashMap.java | 2 +- .../map/hash/Object2IntOpenCachedHashMap.java | 2 +- .../Object2IntOpenCustomCachedHashMap.java | 2 +- .../hash/Object2LongOpenCachedHashMap.java | 2 +- .../Object2LongOpenCustomCachedHashMap.java | 2 +- .../hash/Object2ShortOpenCachedHashMap.java | 2 +- .../Object2ShortOpenCustomCachedHashMap.java | 2 +- 17 files changed, 286 insertions(+), 16 deletions(-) create mode 100644 scripts/gen_cache_maps.ps1 diff --git a/scripts/gen_cache_maps.ps1 b/scripts/gen_cache_maps.ps1 new file mode 100644 index 0000000..8f030f7 --- /dev/null +++ b/scripts/gen_cache_maps.ps1 @@ -0,0 +1,270 @@ +# 以普通和自定义策略的 Int 缓存 Map 为模板,重建六组原始类型容器。 +# 先用 -OutputDirectory 输出到临时目录,可检查差异后再写回生产目录。 +param([string]$OutputDirectory) + +$ErrorActionPreference = 'Stop' +$srcDir = Join-Path (Resolve-Path (Join-Path $PSScriptRoot '..')).Path 'src\main\java\com\modularmc\mmclutils\collection\map\hash' + +if (-not $outputDirectory) { + $outputDirectory = $srcDir +} else { + $outputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputDirectory) + [IO.Directory]::CreateDirectory($outputDirectory) | Out-Null +} + +function Read-Template($name) { + Get-Content -LiteralPath (Join-Path $srcDir "$name.java") -Raw -Encoding UTF8 +} + +function Write-File($path, $content) { + $utf8 = [System.Text.UTF8Encoding]::new($false) + [System.IO.File]::WriteAllText($path, $content, $utf8) +} + +# 各原始类型的值、装箱类型和运算接口。 +$types = @( + @{ Code = 'Z'; Name = 'Boolean'; Pkg = 'booleans'; Value = 'boolean'; Wrapper = 'Boolean'; Prim = 'boolean'; Consumer = 'BooleanConsumer'; Operator = $null }, + @{ Code = 'B'; Name = 'Byte'; Pkg = 'bytes'; Value = 'byte'; Wrapper = 'Byte'; Prim = 'byte'; Consumer = 'ByteConsumer'; Operator = 'it.unimi.dsi.fastutil.bytes.ByteBinaryOperator' }, + @{ Code = 'S'; Name = 'Short'; Pkg = 'shorts'; Value = 'short'; Wrapper = 'Short'; Prim = 'short'; Consumer = 'ShortConsumer'; Operator = 'it.unimi.dsi.fastutil.shorts.ShortBinaryOperator' }, + @{ Code = 'D'; Name = 'Double'; Pkg = 'doubles'; Value = 'double'; Wrapper = 'Double'; Prim = 'double'; Consumer = 'java.util.function.DoubleConsumer'; Operator = 'java.util.function.DoubleBinaryOperator' }, + @{ Code = 'F'; Name = 'Float'; Pkg = 'floats'; Value = 'float'; Wrapper = 'Float'; Prim = 'float'; Consumer = 'FloatConsumer'; Operator = 'it.unimi.dsi.fastutil.floats.FloatBinaryOperator' }, + @{ Code = 'C'; Name = 'Char'; Pkg = 'chars'; Value = 'char'; Wrapper = 'Character'; Prim = 'char'; Consumer = 'CharConsumer'; Operator = 'it.unimi.dsi.fastutil.chars.CharBinaryOperator' } +) + +function Transform($content, $t, $isCustom) { + # 统一模板换行,使固定方法体可以准确匹配。 + $content = $content -replace "`r`n", "`n" + $code = $t.Code; $name = $t.Name; $pkg = $t.Pkg; $value = $t.Value + $wrapper = $t.Wrapper; $prim = $t.Prim; $consumer = $t.Consumer; $op = $t.Operator + $className = "Object2${name}Open$(if ($isCustom) { 'Custom' })CachedHashMap" + $hashLine = if ($isCustom) { ' h = strategy.hashCode(k);' } else { ' h = k.hashCode();' } + + # 改写基本类型的映射接口、参数和返回值。 + + # 先调整接收 JDK 函数的 computeIfAbsent。 + $toIntBlock = @" + @Override + public int computeIfAbsent(final K k, final ToIntFunction mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { +$hashLine + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final int newValue = mappingFunction.applyAsInt(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } +"@ + $repl = $null + if ($code -eq 'Z') { + $repl = @" + @Override + public boolean computeIfAbsent(final K k, final Predicate mappingFunction) { + int pos, h = 0; + if (k == null) { + pos = containsNullKey ? n : -(n + 1); + } else { +$hashLine + pos = find(k, h); + } + if (pos >= 0) return value[pos]; + final boolean newValue = mappingFunction.test(k); + insert(-pos - 1, k, newValue, h); + return newValue; + } +"@ + } elseif ($code -eq 'D') { + $repl = $toIntBlock.Replace('public int computeIfAbsent(final K k, final ToIntFunction mappingFunction) {', 'public double computeIfAbsent(final K k, final ToDoubleFunction mappingFunction) {') + $repl = $repl.Replace('final int newValue = mappingFunction.applyAsInt(k);', 'final double newValue = mappingFunction.applyAsDouble(k);') + } elseif ($code -eq 'F') { + $repl = $toIntBlock.Replace('public int computeIfAbsent(final K k, final ToIntFunction mappingFunction) {', 'public float computeIfAbsent(final K k, final ToDoubleFunction mappingFunction) {') + $repl = $repl.Replace('final int newValue = mappingFunction.applyAsInt(k);', 'final float newValue = SafeMath.safeDoubleToFloat(mappingFunction.applyAsDouble(k));') + } else { + # byte、short 和 char 保留 ToIntFunction。 + $repl = $toIntBlock.Replace('public int computeIfAbsent(final K k, final ToIntFunction mappingFunction) {', "public ${value} computeIfAbsent(final K k, final ToIntFunction mappingFunction) {") + if ($code -eq 'B') { + $repl = $repl.Replace('final int newValue = mappingFunction.applyAsInt(k);', 'final byte newValue = SafeMath.safeIntToByte(mappingFunction.applyAsInt(k));') + } elseif ($code -eq 'S') { + $repl = $repl.Replace('final int newValue = mappingFunction.applyAsInt(k);', 'final short newValue = SafeMath.safeIntToShort(mappingFunction.applyAsInt(k));') + } elseif ($code -eq 'C') { + $repl = $repl.Replace('final int newValue = mappingFunction.applyAsInt(k);', 'final char newValue = SafeMath.safeIntToChar(mappingFunction.applyAsInt(k));') + } + } + if ($content.IndexOf($toIntBlock, [StringComparison]::Ordinal) -lt 0) { + throw "找不到 $className 生成模板中的 computeIfAbsent" + } + $content = $content.Replace($toIntBlock, $repl) + + # 布尔映射没有加法和数值 merge 重载。 + if ($code -eq 'Z') { + # 移除私有加值方法。 + $content = [regex]::Replace($content, '(?m)^ private int addToValue\(final int pos, final int incr\) \{\r?\n(.*\r?\n)*? \}\r?\n', '') + # 移除按键加值方法。 + $content = [regex]::Replace($content, '(?m)^ @Override\r?\n public int addTo\(final K k, final int incr\) \{\r?\n(.*\r?\n)*? \}\r?\n', '') + # 移除基本类型合并方法。 + $content = [regex]::Replace($content, '(?m)^(?: /\*\* \{@inheritDoc\} \*/\r?\n)? @Override\r?\n public \w+ merge\w+\(final K k, final \w+ v, [\w.]+BinaryOperator remappingFunction\) \{\r?\n(.*\r?\n)*? \}\r?\n', '') + } + + # 调整类名、父类和导入。 + $content = $content.Replace('Object2IntOpenCachedHashMap', $className) + $content = $content.Replace('Object2IntOpenCustomCachedHashMap', $className) + if ($isCustom) { + $content = $content.Replace("class ${className} extends Object2IntOpenCustomHashMap", "class ${className} extends Object2${name}OpenCustomHashMap") + } else { + $content = $content.Replace("class ${className} extends Object2IntOpenHashMap", "class ${className} extends Object2${name}OpenHashMap") + } + # 装箱类型只出现在值的位置。 + # 先处理下界参数。 + # 上界参数独立处理。 + $content = $content.Replace('? super Integer', "? super ${wrapper}") + $content = $content.Replace('? extends Integer', "? extends ${wrapper}") + $content = $content.Replace('Map.Entry', "Map.Entry") + $content = $content.Replace('it.unimi.dsi.fastutil.ints.*', "it.unimi.dsi.fastutil.${pkg}.*") + $content = $content.Replace('Object2IntMap', "Object2${name}Map") + $content = $content.Replace('Object2IntFunction', "Object2${name}Function") + $content = $content.Replace('ObjectIntPair', "Object${name}Pair") + $content = $content.Replace('IntIterator', "${name}Iterator") + $content = $content.Replace('IntSpliterator', "${name}Spliterator") + $content = $content.Replace('IntSpliterators', "${name}Spliterators") + $content = $content.Replace('IntCollection', "${name}Collection") + $content = $content.Replace('AbstractIntCollection', "Abstract${name}Collection") + $content = $content.Replace("import java.util.function.IntConsumer;`n", '') + $content = $content.Replace('IntConsumer', ($consumer -split '\.')[-1]) + if ($consumer.Contains('.')) { + $content = $content.Replace('import java.util.function.Consumer;', "import java.util.function.Consumer;`nimport $consumer;") + } + + # 值数组按类型生成,键哈希始终为 int。 + $content = $content.Replace('int[] value', "${value}[] value") + $content = $content.Replace('final int[] newValue = new int[newN + 1];', "final ${value}[] newValue = new ${value}[newN + 1];") + + # 替换与值类型绑定的方法名。 + $content = $content.Replace('removeInt', "remove${name}") + $content = $content.Replace('getIntValue', "get${name}Value") + $content = $content.Replace('rightInt', "right${name}") + $content = $content.Replace('computeIntIfPresent', "compute${name}IfPresent") + $content = $content.Replace('computeInt', "compute${name}") + $content = $content.Replace('mergeInt', "merge${name}") + $content = $content.Replace('getInt', "get${name}") + $content = $content.Replace('nextInt', "next${name}") + $content = $content.Replace('object2IntEntrySet', "object2${name}EntrySet") + + # 替换值类型参数和局部变量。 + $content = $content.Replace('private int removeEntry(int pos)', "private ${value} removeEntry(int pos)") + $content = $content.Replace('private int removeNullEntry()', "private ${value} removeNullEntry()") + $content = $content.Replace('private int addToValue(final int pos, final int incr)', "private ${value} addToValue(final int pos, final ${value} incr)") + $content = $content.Replace('private void insert(final int pos, final K k, final int v, final int h)', "private void insert(final int pos, final K k, final ${value} v, final int h)") + $content = $content.Replace('public int put(final K k', "public ${value} put(final K k") + $content = $content.Replace('public int putIfAbsent(final K k', "public ${value} putIfAbsent(final K k") + $content = $content.Replace('public int addTo(final K k', "public ${value} addTo(final K k") + $content = $content.Replace('public int replace(final K k, final int oldValue, final int v)', "public ${value} replace(final K k, final ${value} oldValue, final ${value} v)") + $content = $content.Replace('public int replace(final K k, final int v)', "public ${value} replace(final K k, final ${value} v)") + $content = $content.Replace('public boolean remove(final Object k, final int v)', "public boolean remove(final Object k, final ${value} v)") + $content = $content.Replace('public int getOrDefault(final Object k, final int defaultValue)', "public ${value} getOrDefault(final Object k, final ${value} defaultValue)") + $content = $content.Replace('public int remove' + $name + '(final Object k)', "public ${value} remove${name}(final Object k)") + $content = $content.Replace('public int get' + $name + '(final Object k)', "public ${value} get${name}(final Object k)") + $content = $content.Replace('public int compute' + $name + 'IfPresent(final K k', "public ${value} compute${name}IfPresent(final K k") + $content = $content.Replace('public int compute' + $name + '(final K k', "public ${value} compute${name}(final K k") + $content = $content.Replace('public int merge' + $name + '(final K k, final int v', "public ${value} merge${name}(final K k, final ${value} v") + $content = $content.Replace('public int merge(final K k, final int v', "public ${value} merge(final K k, final ${value} v") + $content = $content.Replace('public int computeIfAbsent(final K k, final Object2' + $name + 'Function', "public ${value} computeIfAbsent(final K k, final Object2${name}Function") + $content = $content.Replace('public int get' + $name + 'Value()', "public ${value} get${name}Value()") + $content = $content.Replace('public int right' + $name + '()', "public ${value} right${name}()") + $content = $content.Replace('public int setValue(final int v)', "public ${value} setValue(final ${value} v)") + $content = $content.Replace('public Object' + $name + 'Pair right(final int v)', "public Object${name}Pair right(final ${value} v)") + $content = $content.Replace('public int next' + $name + '()', "public ${value} next${name}()") + $content = $content.Replace('public boolean contains(int v)', "public boolean contains(${value} v)") + # 先转换条目视图里的装箱值。 + $content = $content.Replace('final int v = (Integer) (e.getValue());', "final ${value} v = ((${wrapper}) (e.getValue())).${prim}Value();") + $content = $content.Replace('!(e.getValue() instanceof Integer)', "!(e.getValue() instanceof ${wrapper})") + # 转换其余值参数。 + $content = $content.Replace('final int v', "final ${value} v") + $content = $content.Replace('final int oldValue', "final ${value} oldValue") + $content = $content.Replace('final int incr', "final ${value} incr") + $content = $content.Replace('int newVal = newValue;', "${value} newVal = newValue;") + $content = $content.Replace('final int newValue = mappingFunction.applyAsInt(k);', "final ${value} newValue = mappingFunction.get${name}(k);") + $content = $content.Replace('final int newValue = remappingFunction.applyAsInt(value[pos], v);', "final ${value} newValue = remappingFunction.apply(value[pos], v);") + # 调整装箱合并与计算。 + $content = $content.Replace('final Integer newValue = remappingFunction.apply((k), value[pos]);', "final ${wrapper} newValue = remappingFunction.apply((k), ${wrapper}.valueOf(value[pos]));") + $content = $content.Replace('final Integer newValue = remappingFunction.apply((k), pos >= 0 ? value[pos] : null);', "final ${wrapper} newValue = remappingFunction.apply((k), pos >= 0 ? ${wrapper}.valueOf(value[pos]) : null);") + $content = $content.Replace('final Integer newValue = remappingFunction.apply(value[pos], v);', "final ${wrapper} newValue = remappingFunction.apply(${wrapper}.valueOf(value[pos]), ${wrapper}.valueOf(v));") + + # 更新条目的相等比较。 + if ($code -eq 'D') { + $content = $content.Replace('((value[index]) == (e.getValue()))', '(Double.doubleToRawLongBits(value[index]) == Double.doubleToRawLongBits((e.getValue()).doubleValue()))') + } elseif ($code -eq 'F') { + $content = $content.Replace('((value[index]) == (e.getValue()))', '(Float.floatToRawIntBits(value[index]) == Float.floatToRawIntBits((e.getValue()).floatValue()))') + } else { + $content = $content.Replace('((value[index]) == (e.getValue()))', "((value[index]) == ((e.getValue()).${prim}Value()))") + } + + # 窄整数加法需转换回值类型。 + if ($code -in @('B', 'S', 'C')) { + $cast = '(' + $value + ')' + $content = $content.Replace('value[pos] = oldValue + incr;', "value[pos] = ${cast}(oldValue + incr);") + $content = $content.Replace('value[pos] = defRetValue + incr;', "value[pos] = ${cast}(defRetValue + incr);") + } + + # 浮点按位比较,布尔沿用标准哈希。 + if ($code -eq 'D') { + $content = $content.Replace('((value[n]) == (v))', '(Double.doubleToRawLongBits(value[n]) == Double.doubleToRawLongBits(v))') + $content = $content.Replace('((value[pos]) == (v))', '(Double.doubleToRawLongBits(value[pos]) == Double.doubleToRawLongBits(v))') + $content = $content.Replace('t ^= value[i];', 't ^= HashCommon.double2int(value[i]);') + $content = $content.Replace('h += value[n];', 'h += HashCommon.double2int(value[n]);') + $content = $content.Replace('hash[index] ^ value[index];', 'hash[index] ^ HashCommon.double2int(value[index]);') + $content = $content.Replace('value[last] = 0;', 'value[last] = 0d;') + $content = $content.Replace('final double newValue = remappingFunction.apply(value[pos], v);', 'final double newValue = remappingFunction.applyAsDouble(value[pos], v);') + } elseif ($code -eq 'F') { + $content = $content.Replace('((value[n]) == (v))', '(Float.floatToRawIntBits(value[n]) == Float.floatToRawIntBits(v))') + $content = $content.Replace('((value[pos]) == (v))', '(Float.floatToRawIntBits(value[pos]) == Float.floatToRawIntBits(v))') + $content = $content.Replace('t ^= value[i];', 't ^= HashCommon.float2int(value[i]);') + $content = $content.Replace('h += value[n];', 'h += HashCommon.float2int(value[n]);') + $content = $content.Replace('hash[index] ^ value[index];', 'hash[index] ^ HashCommon.float2int(value[index]);') + $content = $content.Replace('value[last] = 0;', 'value[last] = 0f;') + } elseif ($code -eq 'Z') { + $content = $content.Replace('t ^= value[i];', 't ^= (value[i] ? 1231 : 1237);') + $content = $content.Replace('h += value[n];', 'h += (value[n] ? 1231 : 1237);') + $content = $content.Replace('hash[index] ^ value[index];', 'hash[index] ^ (value[index] ? 1231 : 1237);') + $content = $content.Replace('value[last] = 0;', 'value[last] = false;') + } + + # 调整合并操作符类型。 + $content = $content.Replace("import java.util.function.IntBinaryOperator;`n", '') + if ($code -ne 'Z') { + $content = $content.Replace('IntBinaryOperator', ($op -split '\.')[-1]) + if ($code -eq 'D') { + $content = $content.Replace('import java.util.function.Consumer;', "import java.util.function.Consumer;`nimport $op;") + } + } + if ($code -in @('Z','D','F')) { + $function = if ($code -eq 'Z') { 'Predicate' } else { 'ToDoubleFunction' } + $content = $content.Replace('import java.util.function.ToIntFunction;', "import java.util.function.$function;") + } + if ($code -in @('B','S','C','F')) { + $content = $content.Replace('import it.unimi.dsi.fastutil.HashCommon;', "import it.unimi.dsi.fastutil.HashCommon;`nimport it.unimi.dsi.fastutil.SafeMath;") + } + + # 保留装箱条目接口。 + $content = $content.Replace('public Integer getValue()', "public ${wrapper} getValue()") + $content = $content.Replace('public Integer setValue(final Integer v)', "public ${wrapper} setValue(final ${wrapper} v)") + $content = $content.Replace('return setValue((v).intValue());', "return ${wrapper}.valueOf(setValue((v).${prim}Value()));") + + # 写入时统一使用 LF。 + return $content +} + +foreach ($t in $types) { + $normalName = "Object2$($t.Name)OpenCachedHashMap" + $customName = "Object2$($t.Name)OpenCustomCachedHashMap" + + $n = Transform (Read-Template 'Object2IntOpenCachedHashMap') $t $false + Write-File (Join-Path $outputDirectory "$normalName.java") $n + + $c = Transform (Read-Template 'Object2IntOpenCustomCachedHashMap') $t $true + Write-File (Join-Path $outputDirectory "$customName.java") $c + + Write-Host "generated $normalName / $customName" +} diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCachedHashMap.java index 0b6a7c2..75ec88e 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCachedHashMap.java @@ -309,7 +309,7 @@ public boolean computeIfAbsent(final K k, final Object2BooleanFunction= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final boolean newValue = mappingFunction.getBoolean(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java index 56caedf..2251cb2 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java @@ -313,7 +313,7 @@ public boolean computeIfAbsent(final K k, final Object2BooleanFunction= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final boolean newValue = mappingFunction.getBoolean(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCachedHashMap.java index 1b25cbd..1106013 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCachedHashMap.java @@ -342,7 +342,7 @@ public byte computeIfAbsent(final K k, final Object2ByteFunction mapp pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final byte newValue = mappingFunction.getByte(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java index b22d2e2..bda5db4 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ByteOpenCustomCachedHashMap.java @@ -346,7 +346,7 @@ public byte computeIfAbsent(final K k, final Object2ByteFunction mapp pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final byte newValue = mappingFunction.getByte(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCachedHashMap.java index 340bda9..e8e628b 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCachedHashMap.java @@ -342,7 +342,7 @@ public char computeIfAbsent(final K k, final Object2CharFunction mapp pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final char newValue = mappingFunction.getChar(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCustomCachedHashMap.java index ab906a5..d07bc87 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2CharOpenCustomCachedHashMap.java @@ -346,7 +346,7 @@ public char computeIfAbsent(final K k, final Object2CharFunction mapp pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final char newValue = mappingFunction.getChar(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCachedHashMap.java index 4bf949a..0cda57f 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCachedHashMap.java @@ -342,7 +342,7 @@ public double computeIfAbsent(final K k, final Object2DoubleFunction pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final double newValue = mappingFunction.getDouble(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java index b6162d8..8842e33 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2DoubleOpenCustomCachedHashMap.java @@ -346,7 +346,7 @@ public double computeIfAbsent(final K k, final Object2DoubleFunction pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final double newValue = mappingFunction.getDouble(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCachedHashMap.java index c31de0d..8c01947 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCachedHashMap.java @@ -342,7 +342,7 @@ public float computeIfAbsent(final K k, final Object2FloatFunction ma pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final float newValue = mappingFunction.getFloat(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java index 89403fd..ddfd7c7 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2FloatOpenCustomCachedHashMap.java @@ -346,7 +346,7 @@ public float computeIfAbsent(final K k, final Object2FloatFunction ma pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final float newValue = mappingFunction.getFloat(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCachedHashMap.java index 0ae1a11..3048c62 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCachedHashMap.java @@ -342,7 +342,7 @@ public int computeIfAbsent(final K k, final Object2IntFunction mappin pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final int newValue = mappingFunction.applyAsInt(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCustomCachedHashMap.java index 67a69af..52cbebf 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2IntOpenCustomCachedHashMap.java @@ -346,7 +346,7 @@ public int computeIfAbsent(final K k, final Object2IntFunction mappin pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final int newValue = mappingFunction.applyAsInt(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java index d0e9e4a..a6670a1 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCachedHashMap.java @@ -347,7 +347,7 @@ public long computeIfAbsent(final K k, final Object2LongFunction mapp pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final long newValue = mappingFunction.applyAsLong(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCustomCachedHashMap.java index 843c4f1..7042b9f 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2LongOpenCustomCachedHashMap.java @@ -346,7 +346,7 @@ public long computeIfAbsent(final K k, final Object2LongFunction mapp pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final long newValue = mappingFunction.applyAsLong(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCachedHashMap.java index 88e062c..91d79fb 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCachedHashMap.java @@ -342,7 +342,7 @@ public short computeIfAbsent(final K k, final Object2ShortFunction ma pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final short newValue = mappingFunction.getShort(k); insert(-pos - 1, k, newValue, h); return newValue; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java index e07f5d3..ad2a07f 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java @@ -346,7 +346,7 @@ public short computeIfAbsent(final K k, final Object2ShortFunction ma pos = find(k, h); } if (pos >= 0) return value[pos]; - if (!mappingFunction.containsKey(key)) return defRetValue; + if (!mappingFunction.containsKey(k)) return defRetValue; final short newValue = mappingFunction.getShort(k); insert(-pos - 1, k, newValue, h); return newValue; From 3785fec21918a1165ff6b9a749cfd763265653aa Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 12:09:31 +0800 Subject: [PATCH 14/79] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E5=93=88=E5=B8=8C=E5=AE=B9=E5=99=A8=E7=9A=84=E7=A9=BA?= =?UTF-8?q?=E5=80=BC=E7=AD=89=E4=BB=B7=E9=94=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/gen_cache_maps.ps1 | 5 ++- ...Object2BooleanOpenCustomCachedHashMap.java | 39 +++++++++-------- .../Object2ByteOpenCustomCachedHashMap.java | 43 ++++++++++--------- .../Object2CharOpenCustomCachedHashMap.java | 43 ++++++++++--------- .../Object2DoubleOpenCustomCachedHashMap.java | 43 ++++++++++--------- .../Object2FloatOpenCustomCachedHashMap.java | 43 ++++++++++--------- .../Object2IntOpenCustomCachedHashMap.java | 43 ++++++++++--------- .../Object2LongOpenCustomCachedHashMap.java | 43 ++++++++++--------- .../Object2ObjectOpenCustomCachedHashMap.java | 39 +++++++++-------- .../Object2ShortOpenCustomCachedHashMap.java | 43 ++++++++++--------- .../hash/ObjectOpenCustomCachedHashSet.java | 13 +++--- 11 files changed, 205 insertions(+), 192 deletions(-) diff --git a/scripts/gen_cache_maps.ps1 b/scripts/gen_cache_maps.ps1 index 8f030f7..04b6991 100644 --- a/scripts/gen_cache_maps.ps1 +++ b/scripts/gen_cache_maps.ps1 @@ -38,6 +38,7 @@ function Transform($content, $t, $isCustom) { $wrapper = $t.Wrapper; $prim = $t.Prim; $consumer = $t.Consumer; $op = $t.Operator $className = "Object2${name}Open$(if ($isCustom) { 'Custom' })CachedHashMap" $hashLine = if ($isCustom) { ' h = strategy.hashCode(k);' } else { ' h = k.hashCode();' } + $nullKeyCheck = if ($isCustom) { 'strategy.equals(k, null)' } else { 'k == null' } # 改写基本类型的映射接口、参数和返回值。 @@ -46,7 +47,7 @@ function Transform($content, $t, $isCustom) { @Override public int computeIfAbsent(final K k, final ToIntFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if ($nullKeyCheck) { pos = containsNullKey ? n : -(n + 1); } else { $hashLine @@ -64,7 +65,7 @@ $hashLine @Override public boolean computeIfAbsent(final K k, final Predicate mappingFunction) { int pos, h = 0; - if (k == null) { + if ($nullKeyCheck) { pos = containsNullKey ? n : -(n + 1); } else { $hashLine diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java index 2251cb2..3308122 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2BooleanOpenCustomCachedHashMap.java @@ -125,7 +125,7 @@ private void insert(final int pos, final K k, final boolean v, final int h) { @Override public boolean put(final K k, final boolean v) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -142,7 +142,7 @@ public boolean put(final K k, final boolean v) { @Override public boolean removeBoolean(final Object k) { - if (k == null) { + if (strategy.equals((K) k, null)) { if (containsNullKey) return removeNullEntry(); return defRetValue; } @@ -163,7 +163,7 @@ public boolean removeBoolean(final Object k) { @Override public boolean getBoolean(final Object k) { - if (k == null) return containsNullKey ? value[n] : defRetValue; + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; K fk = (K) k; K curr; final K[] key = this.key; @@ -181,7 +181,7 @@ public boolean getBoolean(final Object k) { @Override public boolean containsKey(final Object k) { - if (k == null) return containsNullKey; + if (strategy.equals((K) k, null)) return containsNullKey; K fk = (K) k; K curr; final K[] key = this.key; @@ -199,7 +199,7 @@ public boolean containsKey(final Object k) { @Override public boolean getOrDefault(final Object k, final boolean defaultValue) { - if (k == null) return containsNullKey ? value[n] : defaultValue; + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; K fk = (K) k; K curr; final K[] key = this.key; @@ -218,7 +218,7 @@ public boolean getOrDefault(final Object k, final boolean defaultValue) { @Override public boolean putIfAbsent(final K k, final boolean v) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -231,7 +231,7 @@ public boolean putIfAbsent(final K k, final boolean v) { @Override public boolean remove(final Object k, final boolean v) { - if (k == null) { + if (strategy.equals((K) k, null)) { if (containsNullKey && v == value[n]) { removeNullEntry(); return true; @@ -262,7 +262,7 @@ public boolean remove(final Object k, final boolean v) { @Override public boolean replace(final K k, final boolean oldValue, final boolean v) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -276,7 +276,7 @@ public boolean replace(final K k, final boolean oldValue, final boolean v) { @Override public boolean replace(final K k, final boolean v) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -291,7 +291,7 @@ public boolean replace(final K k, final boolean v) { @Override public boolean computeIfAbsent(final K k, final Predicate mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -306,7 +306,7 @@ public boolean computeIfAbsent(final K k, final Predicate mappingFunc @Override public boolean computeIfAbsent(final K k, final Object2BooleanFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -322,7 +322,7 @@ public boolean computeIfAbsent(final K k, final Object2BooleanFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -331,7 +331,7 @@ public boolean computeBooleanIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -350,7 +350,7 @@ public boolean computeBoolean(final K k, final BiFunction= 0 ? Boolean.valueOf(value[pos]) : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -366,7 +366,7 @@ public boolean computeBoolean(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -378,7 +378,7 @@ public boolean merge(final K k, final boolean v, final BiFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -339,7 +339,7 @@ public byte computeIfAbsent(final K k, final ToIntFunction mappingFun @Override public byte computeIfAbsent(final K k, final Object2ByteFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public byte computeIfAbsent(final K k, final Object2ByteFunction mapp @Override public byte computeByteIfPresent(final K k, final BiFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -364,7 +364,7 @@ public byte computeByteIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public byte computeByte(final K k, final BiFunction= 0 ? Byte.valueOf(value[pos]) : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -399,7 +399,7 @@ public byte computeByte(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -428,7 +428,7 @@ public byte merge(final K k, final byte v, final BiFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -339,7 +339,7 @@ public char computeIfAbsent(final K k, final ToIntFunction mappingFun @Override public char computeIfAbsent(final K k, final Object2CharFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public char computeIfAbsent(final K k, final Object2CharFunction mapp @Override public char computeCharIfPresent(final K k, final BiFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -364,7 +364,7 @@ public char computeCharIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public char computeChar(final K k, final BiFunction= 0 ? Character.valueOf(value[pos]) : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -399,7 +399,7 @@ public char computeChar(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -428,7 +428,7 @@ public char merge(final K k, final char v, final BiFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -339,7 +339,7 @@ public double computeIfAbsent(final K k, final ToDoubleFunction mappi @Override public double computeIfAbsent(final K k, final Object2DoubleFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public double computeIfAbsent(final K k, final Object2DoubleFunction @Override public double computeDoubleIfPresent(final K k, final BiFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -364,7 +364,7 @@ public double computeDoubleIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public double computeDouble(final K k, final BiFunction= 0 ? Double.valueOf(value[pos]) : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -399,7 +399,7 @@ public double computeDouble(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -428,7 +428,7 @@ public double merge(final K k, final double v, final BiFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -339,7 +339,7 @@ public float computeIfAbsent(final K k, final ToDoubleFunction mappin @Override public float computeIfAbsent(final K k, final Object2FloatFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public float computeIfAbsent(final K k, final Object2FloatFunction ma @Override public float computeFloatIfPresent(final K k, final BiFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -364,7 +364,7 @@ public float computeFloatIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public float computeFloat(final K k, final BiFunction= 0 ? Float.valueOf(value[pos]) : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -399,7 +399,7 @@ public float computeFloat(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -428,7 +428,7 @@ public float merge(final K k, final float v, final BiFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -339,7 +339,7 @@ public int computeIfAbsent(final K k, final ToIntFunction mappingFunc @Override public int computeIfAbsent(final K k, final Object2IntFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public int computeIfAbsent(final K k, final Object2IntFunction mappin @Override public int computeIntIfPresent(final K k, final BiFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -364,7 +364,7 @@ public int computeIntIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public int computeInt(final K k, final BiFunction= 0 ? value[pos] : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -399,7 +399,7 @@ public int computeInt(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -428,7 +428,7 @@ public int merge(final K k, final int v, final BiFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -339,7 +339,7 @@ public long computeIfAbsent(final K k, final ToLongFunction mappingFu @Override public long computeIfAbsent(final K k, final Object2LongFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public long computeIfAbsent(final K k, final Object2LongFunction mapp @Override public long computeLongIfPresent(final K k, final BiFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -364,7 +364,7 @@ public long computeLongIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public long computeLong(final K k, final BiFunction= 0 ? value[pos] : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -399,7 +399,7 @@ public long computeLong(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -428,7 +428,7 @@ public long merge(final K k, final long v, final BiFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -310,7 +310,7 @@ public V computeIfAbsent(K k, Function mappingFunction) @Override public V computeIfAbsent(final K k, final Object2ObjectFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -326,7 +326,7 @@ public V computeIfAbsent(final K k, final Object2ObjectFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -336,7 +336,7 @@ public V computeIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public V compute(final K k, final BiFunction final V newValue = remappingFunction.apply((k), pos >= 0 ? (value[pos]) : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -370,7 +370,7 @@ public V compute(final K k, final BiFunction @Override public V merge(final K k, final V v, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public V merge(final K k, final V v, final BiFunction e)) return false; final K k = ((K) e.getKey()); final V v = ((V) e.getValue()); - if (((k) == null)) return Object2ObjectOpenCustomCachedHashMap.this.containsNullKey && Objects.equals(value[n], v); + 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; @@ -778,7 +778,7 @@ 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 (strategy.equals(k, null)) { if (containsNullKey && Objects.equals(value[n], v)) { removeNullEntry(); return true; @@ -1042,6 +1042,7 @@ protected void rehash(final int newN) { newValue[pos] = value[i]; newHash[pos] = h; } + newKey[newN] = key[n]; newValue[newN] = value[n]; n = newN; this.mask = mask; diff --git a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java index ad2a07f..b7a4d83 100644 --- a/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java +++ b/src/main/java/com/modularmc/mmclutils/collection/map/hash/Object2ShortOpenCustomCachedHashMap.java @@ -127,7 +127,7 @@ private void insert(final int pos, final K k, final short v, final int h) { @Override public short put(final K k, final short v) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -151,7 +151,7 @@ private short addToValue(final int pos, final short incr) { @Override public short addTo(final K k, final short incr) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { if (containsNullKey) return addToValue(n, incr); pos = n; containsNullKey = true; @@ -175,7 +175,7 @@ public short addTo(final K k, final short incr) { @Override public short removeShort(final Object k) { - if (k == null) { + if (strategy.equals((K) k, null)) { if (containsNullKey) return removeNullEntry(); return defRetValue; } @@ -196,7 +196,7 @@ public short removeShort(final Object k) { @Override public short getShort(final Object k) { - if (k == null) return containsNullKey ? value[n] : defRetValue; + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defRetValue; K fk = (K) k; K curr; final K[] key = this.key; @@ -214,7 +214,7 @@ public short getShort(final Object k) { @Override public boolean containsKey(final Object k) { - if (k == null) return containsNullKey; + if (strategy.equals((K) k, null)) return containsNullKey; K fk = (K) k; K curr; final K[] key = this.key; @@ -232,7 +232,7 @@ public boolean containsKey(final Object k) { @Override public short getOrDefault(final Object k, final short defaultValue) { - if (k == null) return containsNullKey ? value[n] : defaultValue; + if (strategy.equals((K) k, null)) return containsNullKey ? value[n] : defaultValue; K fk = (K) k; K curr; final K[] key = this.key; @@ -251,7 +251,7 @@ public short getOrDefault(final Object k, final short defaultValue) { @Override public short putIfAbsent(final K k, final short v) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -264,7 +264,7 @@ public short putIfAbsent(final K k, final short v) { @Override public boolean remove(final Object k, final short v) { - if (k == null) { + if (strategy.equals((K) k, null)) { if (containsNullKey && v == value[n]) { removeNullEntry(); return true; @@ -295,7 +295,7 @@ public boolean remove(final Object k, final short v) { @Override public boolean replace(final K k, final short oldValue, final short v) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -309,7 +309,7 @@ public boolean replace(final K k, final short oldValue, final short v) { @Override public short replace(final K k, final short v) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -324,7 +324,7 @@ public short replace(final K k, final short v) { @Override public short computeIfAbsent(final K k, final ToIntFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -339,7 +339,7 @@ public short computeIfAbsent(final K k, final ToIntFunction mappingFu @Override public short computeIfAbsent(final K k, final Object2ShortFunction mappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -355,7 +355,7 @@ public short computeIfAbsent(final K k, final Object2ShortFunction ma @Override public short computeShortIfPresent(final K k, final BiFunction remappingFunction) { int pos; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { int h = strategy.hashCode(k); @@ -364,7 +364,7 @@ public short computeShortIfPresent(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -383,7 +383,7 @@ public short computeShort(final K k, final BiFunction= 0 ? Short.valueOf(value[pos]) : null); if (newValue == null) { if (pos >= 0) { - if (k == null) removeNullEntry(); + if (strategy.equals(k, null)) removeNullEntry(); else removeEntry(pos); } return defRetValue; @@ -399,7 +399,7 @@ public short computeShort(final K k, final BiFunction remappingFunction) { int pos, h = 0; - if (k == null) { + if (strategy.equals(k, null)) { pos = containsNullKey ? n : -(n + 1); } else { h = strategy.hashCode(k); @@ -428,7 +428,7 @@ public short merge(final K k, final short v, final BiFunction Date: Tue, 24 Nov 2026 12:15:47 +0800 Subject: [PATCH 15/79] =?UTF-8?q?=E8=A1=A5=E9=BD=90=E8=8F=9C=E5=8D=95?= =?UTF-8?q?=E6=B5=81=E4=BD=93=E5=AE=B9=E5=99=A8=E6=89=B9=E9=87=8F=E4=BA=A4?= =?UTF-8?q?=E4=BA=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/fluid/FluidContainers.java | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/src/main/java/com/modularmc/mmclutils/fluid/FluidContainers.java b/src/main/java/com/modularmc/mmclutils/fluid/FluidContainers.java index b5e200c..01cb7e0 100644 --- a/src/main/java/com/modularmc/mmclutils/fluid/FluidContainers.java +++ b/src/main/java/com/modularmc/mmclutils/fluid/FluidContainers.java @@ -1,11 +1,25 @@ package com.modularmc.mmclutils.fluid; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.inventory.AbstractContainerMenu; import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.common.SoundActions; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.transfer.RangedResourceHandler; import net.neoforged.neoforge.transfer.ResourceHandler; +import net.neoforged.neoforge.transfer.ResourceHandlerUtil; import net.neoforged.neoforge.transfer.access.ItemAccess; import net.neoforged.neoforge.transfer.fluid.FluidResource; +import net.neoforged.neoforge.transfer.item.CarriedSlotWrapper; +import net.neoforged.neoforge.transfer.item.ItemResource; +import net.neoforged.neoforge.transfer.item.ItemStacksResourceHandler; +import net.neoforged.neoforge.transfer.item.PlayerInventoryWrapper; +import net.neoforged.neoforge.transfer.transaction.Transaction; import net.neoforged.neoforge.transfer.transaction.TransactionContext; +import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import org.jspecify.annotations.Nullable; /** 通过 NeoForge 的物品访问修改容器,流体与原物品的替换在同一个事务中完成。 */ @@ -26,4 +40,90 @@ public static int drain(ItemAccess item, int tank, ResourceHandler handler, int tank, + boolean batch, boolean allowFill, boolean allowDrain) { + return click(player, player.containerMenu, handler, tank, batch ? Integer.MAX_VALUE : 1, allowFill, allowDrain); + } + + /** + * 只操作指定储罐。装入容器成功后按同一方向继续,无法装入时可尝试倒空。 + * 光标空出后放回一组结果,其余交给玩家库存。声音和菜单同步发生在提交后。 + * + * @return 成功装入或倒空的容器数量 + */ + public static int click(ServerPlayer player, AbstractContainerMenu menu, ResourceHandler handler, + int tank, int maximumContainers, boolean allowFill, boolean allowDrain) { + if (maximumContainers < 0) throw new IllegalArgumentException("容器数量应为非负数"); + var cursor = CarriedSlotWrapper.of(menu); + int count = Math.min(maximumContainers, cursor.getAmountAsInt(0)); + if (count == 0 || (!allowFill && !allowDrain)) return 0; + + var tankAccess = RangedResourceHandler.ofSingleIndex(handler, tank); + BatchResult result; + boolean fill = allowFill; + try (var transaction = Transaction.openRoot()) { + result = fill ? transferContainers(cursor, tankAccess, count, true, player, transaction) : null; + if (result == null && allowDrain) { + fill = false; + result = transferContainers(cursor, tankAccess, count, false, player, transaction); + } + if (result == null) return 0; + transaction.commit(); + } + + var fluid = result.fluid(); + var stack = fluid.toStack(FluidType.BUCKET_VOLUME); + var sound = fluid.getFluidType().getSound(stack, fill ? SoundActions.BUCKET_FILL : SoundActions.BUCKET_EMPTY); + if (sound == null) sound = fill ? SoundEvents.BUCKET_FILL : SoundEvents.BUCKET_EMPTY; + player.level().playSound(null, player, sound, SoundSource.BLOCKS, 1, 1); + menu.broadcastChanges(); + return result.containers(); + } + + private static @Nullable BatchResult transferContainers(ResourceHandler cursor, ResourceHandler tank, + int count, boolean fill, ServerPlayer player, TransactionContext parent) { + var original = cursor.getResource(0); + var single = new ItemStacksResourceHandler(1); + var access = ItemAccess.forHandlerIndexStrict(single, 0); + var results = new Object2IntLinkedOpenHashMap(); + FluidResource firstFluid = FluidResource.EMPTY; + int containers = 0; + for (; containers < count; containers++) { + // 每次仅从光标取原始容器,产物在本批结束后回填。 + try (var attempt = Transaction.open(parent)) { + if (cursor.extract(0, original, 1, attempt) != 1) break; + if (single.insert(0, original, 1, attempt) != 1) break; + var container = access.getCapability(Capabilities.Fluid.ITEM); + if (container == null) break; + var moved = ResourceHandlerUtil.moveFirst(fill ? tank : container, fill ? container : tank, + resource -> true, Integer.MAX_VALUE, attempt); + if (moved == null) break; + + var product = single.getResource(0); + if (!product.isEmpty()) { + int amount = single.extract(0, product, single.getAmountAsInt(0), attempt); + results.addTo(product, amount); + } + attempt.commit(); + if (firstFluid.isEmpty()) firstFluid = moved.resource(); + } + } + if (containers == 0) return null; + + if (!results.isEmpty() && cursor.getResource(0).isEmpty()) { + ItemResource last = results.lastKey(); + int inserted = cursor.insert(0, last, results.getInt(last), parent); + results.addTo(last, -inserted); + } + var inventory = PlayerInventoryWrapper.of(player); + for (var entry : results.object2IntEntrySet()) { + int amount = entry.getIntValue(); + if (amount > 0) inventory.placeItemBackInInventory(entry.getKey(), amount, parent); + } + return new BatchResult(containers, firstFluid); + } + + private record BatchResult(int containers, FluidResource fluid) {} } From 233b04dbefa129cf6229fc3d42dc38492edcf396 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 12:15:47 +0800 Subject: [PATCH 16/79] =?UTF-8?q?=E8=BF=81=E5=85=A5=E6=96=B9=E5=9D=97?= =?UTF-8?q?=E5=B1=80=E9=83=A8=E6=96=B9=E5=90=91=E4=B8=8E=E7=82=B9=E5=87=BB?= =?UTF-8?q?=E5=88=86=E5=8C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mmclutils/spatial/BlockDirections.java | 231 +++++++++++++++++- 1 file changed, 230 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java b/src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java index 2356ec9..39a73c5 100644 --- a/src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java +++ b/src/main/java/com/modularmc/mmclutils/spatial/BlockDirections.java @@ -2,11 +2,23 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.util.StringRepresentable; +import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import it.unimi.dsi.fastutil.longs.LongComparator; +import org.jspecify.annotations.Nullable; + +import java.util.Comparator; +import java.util.EnumSet; +import java.util.Locale; + /** 将局部方向、点击位置与打包坐标映射到原版方块面。 */ public final class BlockDirections { + private static final Direction[] DIRECTIONS = Direction.values(); + public static final int ALL_SIDES = (1 << DIRECTIONS.length) - 1; + private BlockDirections() {} public static long offset(long packedPosition, Direction side) { @@ -20,6 +32,223 @@ public static Direction nearestSide(Vec3 point, BlockPos position) { public static Direction rotateHorizontal(Direction direction, int quarterTurns) { if (direction.getAxis().isVertical()) return direction; - return Direction.from2DDataValue(Math.floorMod(direction.get2DDataValue() + quarterTurns, 4)); + return Direction.from2DDataValue((direction.get2DDataValue() + quarterTurns) & 3); + } + + /** 中央返回命中面,边缘返回相邻面,四角返回背面。 */ + public static Direction gridSide(BlockHitResult hit) { + Vec3 point = hit.getLocation(); + BlockPos pos = hit.getBlockPos(); + return gridSide(hit.getDirection(), point.x - pos.getX(), point.y - pos.getY(), point.z - pos.getZ()); + } + + /** 坐标相对命中的方块,边缘带宽各占四分之一。 */ + public static Direction gridSide(Direction face, double x, double y, double z) { + return switch (face.getAxis()) { + case X -> gridSide(face, edge(z, Direction.NORTH, Direction.SOUTH), edge(y, Direction.DOWN, Direction.UP)); + case Y -> gridSide(face, edge(x, Direction.WEST, Direction.EAST), edge(z, Direction.NORTH, Direction.SOUTH)); + case Z -> gridSide(face, edge(x, Direction.WEST, Direction.EAST), edge(y, Direction.DOWN, Direction.UP)); + }; + } + + private static @Nullable Direction edge(double coordinate, Direction low, Direction high) { + if (coordinate < .25) return low; + return coordinate > .75 ? high : null; + } + + private static Direction gridSide(Direction face, @Nullable Direction first, @Nullable Direction second) { + if (first != null) return second == null ? first : face.getOpposite(); + return second == null ? face : second; + } + + /** 仅在两个位置共享一个方块面时返回从源指向邻居的方向。 */ + public static @Nullable Direction neighborSide(long source, long neighbor) { + int x = BlockPos.getX(neighbor) - BlockPos.getX(source); + int y = BlockPos.getY(neighbor) - BlockPos.getY(source); + int z = BlockPos.getZ(neighbor) - BlockPos.getZ(source); + return Math.abs(x) + Math.abs(y) + Math.abs(z) == 1 ? Direction.getNearest(x, y, z, null) : null; + } + + public static @Nullable Direction neighborSide(BlockPos source, BlockPos neighbor) { + return neighborSide(source.asLong(), neighbor.asLong()); + } + + /** 每个方向占原版方向索引对应的一位,可直接用于比较区段的可见面。 */ + public static int mask(Direction side) { + return 1 << side.ordinal(); + } + + public static int mask(Iterable sides) { + int mask = 0; + for (Direction side : sides) mask |= mask(side); + return mask; + } + + public static EnumSet sides(int mask) { + var result = EnumSet.noneOf(Direction.class); + replaceSides(result, mask); + return result; + } + + /** 忽略高于原版方向数的位,返回集合是否变化。 */ + public static boolean replaceSides(EnumSet target, int mask) { + mask &= ALL_SIDES; + if (mask(target) == mask) return false; + target.clear(); + while (mask != 0) { + target.add(DIRECTIONS[Integer.numberOfTrailingZeros(mask)]); + mask &= mask - 1; + } + return true; + } + + /** 以北为前时的六个局部面。 */ + public enum LocalSide implements StringRepresentable { + + FRONT(Direction.NORTH), + BACK(Direction.SOUTH), + UP(Direction.UP), + DOWN(Direction.DOWN), + LEFT(Direction.WEST), + RIGHT(Direction.EAST); + + public static final EnumCodec CODEC = StringRepresentable.fromEnum(LocalSide::values); + private static final LocalSide[] BY_SIDE = new LocalSide[DIRECTIONS.length]; + + static { + for (LocalSide local : values()) BY_SIDE[local.side.ordinal()] = local; + } + + private final Direction side; + private final String name; + + LocalSide(Direction side) { + this.side = side; + this.name = name().toLowerCase(Locale.ROOT); + } + + public static LocalSide fromNorthFacing(Direction side) { + return BY_SIDE[side.ordinal()]; + } + + public Direction northFacing() { + return side; + } + + public LocalSide opposite() { + return fromNorthFacing(side.getOpposite()); + } + + public boolean isSameAxis(LocalSide other) { + return side.getAxis() == other.side.getAxis(); + } + + @Override + public String getSerializedName() { + return name; + } + } + + /** 前方与上方使用互相垂直的世界方向。镜像沿左右轴生效。 */ + public record Orientation(Direction front, Direction up, boolean mirrored) { + + public Orientation { + if (front.getAxis() == up.getAxis()) throw new IllegalArgumentException("前方和上方必须互相垂直"); + } + + public static Orientation facing(Direction front) { + return new Orientation(front, front.getAxis().isVertical() ? Direction.NORTH : Direction.UP, false); + } + + /** 指向水平时,北、南、西、东分别表示正立、倒置、向右和向左翻转九十度。 */ + public static Orientation fromRoll(Direction front, Direction roll, boolean mirrored) { + Direction up = front.getAxis().isVertical() ? roll : switch (roll) { + case NORTH -> Direction.UP; + case SOUTH -> Direction.DOWN; + case EAST -> front.getCounterClockWise(); + case WEST -> front.getClockWise(); + default -> throw new IllegalArgumentException("旋转编码必须使用水平方向"); + }; + return new Orientation(front, up, mirrored); + } + + public Direction left() { + Direction side = Direction.getApproximateNearest( + up.getStepY() * front.getStepZ() - up.getStepZ() * front.getStepY(), + up.getStepZ() * front.getStepX() - up.getStepX() * front.getStepZ(), + up.getStepX() * front.getStepY() - up.getStepY() * front.getStepX()); + return mirrored ? side.getOpposite() : side; + } + + public Direction direction(LocalSide side) { + return switch (side) { + case FRONT -> front; + case BACK -> front.getOpposite(); + case UP -> up; + case DOWN -> up.getOpposite(); + case LEFT -> left(); + case RIGHT -> left().getOpposite(); + }; + } + + public LocalSide localSide(Direction side) { + if (side.getAxis() == front.getAxis()) return side == front ? LocalSide.FRONT : LocalSide.BACK; + if (side.getAxis() == up.getAxis()) return side == up ? LocalSide.UP : LocalSide.DOWN; + return side == left() ? LocalSide.LEFT : LocalSide.RIGHT; + } + + public Direction roll() { + if (front.getAxis().isVertical()) return up; + if (up == Direction.UP) return Direction.NORTH; + if (up == Direction.DOWN) return Direction.SOUTH; + return up == front.getCounterClockWise() ? Direction.EAST : Direction.WEST; + } + + /** 保留翻转状态,将坐标轴一起旋到新的前方。 */ + public Orientation withFront(Direction nextFront) { + if (front == nextFront) return this; + Direction nextUp; + if (front.getAxis().isHorizontal() && nextFront.getAxis().isHorizontal()) { + nextUp = rotateHorizontal(up, nextFront.get2DDataValue() - front.get2DDataValue()); + } else if (front.getAxis().isVertical() && nextFront.getAxis().isVertical()) { + nextUp = up.getOpposite(); + } else if (up.getAxis() == nextFront.getAxis()) { + nextUp = up == nextFront ? front.getOpposite() : front; + } else { + nextUp = up; + } + return new Orientation(nextFront, nextUp, mirrored); + } + + public long offset(long position, int leftSteps, int upSteps, int forwardSteps) { + Direction left = left(); + return BlockPos.offset(position, + left.getStepX() * leftSteps + up.getStepX() * upSteps + front.getStepX() * forwardSteps, + left.getStepY() * leftSteps + up.getStepY() * upSteps + front.getStepY() * forwardSteps, + left.getStepZ() * leftSteps + up.getStepZ() * upSteps + front.getStepZ() * forwardSteps); + } + + public BlockPos offset(BlockPos position, int leftSteps, int upSteps, int forwardSteps) { + return BlockPos.of(offset(position.asLong(), leftSteps, upSteps, forwardSteps)); + } + + public LongComparator packedOrder(LocalSide side) { + Direction direction = direction(side); + return switch (direction) { + case EAST -> (a, b) -> Integer.compare(BlockPos.getX(a), BlockPos.getX(b)); + case WEST -> (a, b) -> Integer.compare(BlockPos.getX(b), BlockPos.getX(a)); + case UP -> (a, b) -> Integer.compare(BlockPos.getY(a), BlockPos.getY(b)); + case DOWN -> (a, b) -> Integer.compare(BlockPos.getY(b), BlockPos.getY(a)); + case SOUTH -> (a, b) -> Integer.compare(BlockPos.getZ(a), BlockPos.getZ(b)); + case NORTH -> (a, b) -> Integer.compare(BlockPos.getZ(b), BlockPos.getZ(a)); + }; + } + + public Comparator order(LocalSide side) { + Direction direction = direction(side); + Direction.Axis axis = direction.getAxis(); + Comparator order = Comparator.comparingInt(pos -> axis.choose(pos.getX(), pos.getY(), pos.getZ())); + return direction.getAxisDirection() == Direction.AxisDirection.POSITIVE ? order : order.reversed(); + } } } From 67ef5b82b89ef9497f5fd988529d27866cdfce72 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Tue, 24 Nov 2026 12:34:57 +0800 Subject: [PATCH 17/79] =?UTF-8?q?=E8=A1=A5=E9=BD=90=E5=B7=B2=E5=8A=A0?= =?UTF-8?q?=E8=BD=BD=E5=8C=BA=E6=AE=B5=E9=87=87=E9=9B=86=E5=92=8C=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E4=BD=9C=E5=BA=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../client/level/LoadedSectionCursor.java | 3 - .../client/level/SectionCapture.java | 58 ++++++++--- .../client/level/SectionGeometryCache.java | 97 +++++++++++++++++++ .../client/level/SectionGeometryData.java | 6 +- .../client/level/SectionOccupancy.java | 7 +- .../mmclutils/spatial/LevelSections.java | 16 +-- .../mmclutils/spatial/VoxelContours.java | 3 - .../mmclutils/spatial/VoxelContoursShape.java | 5 +- .../mmclutils/spatial/VoxelShapes.java | 15 ++- 9 files changed, 159 insertions(+), 51 deletions(-) create mode 100644 src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryCache.java diff --git a/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java b/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java index f425117..749f3e0 100644 --- a/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java +++ b/src/main/java/com/modularmc/mmclutils/client/level/LoadedSectionCursor.java @@ -3,14 +3,11 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.core.SectionPos; import net.minecraft.world.level.chunk.LevelChunk; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; import lombok.Getter; import org.jspecify.annotations.Nullable; /** 以中心区块为起点螺旋遍历,按高度交替访问已加载的非空区段。 */ -@OnlyIn(Dist.CLIENT) public final class LoadedSectionCursor { public static final long NO_SECTION = Long.MIN_VALUE; diff --git a/src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java b/src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java index 43637bd..7c8fa23 100644 --- a/src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java +++ b/src/main/java/com/modularmc/mmclutils/client/level/SectionCapture.java @@ -1,6 +1,7 @@ package com.modularmc.mmclutils.client.level; import com.modularmc.mmclutils.level.BlockEnvironment; +import com.modularmc.mmclutils.spatial.BlockDirections; import com.modularmc.mmclutils.spatial.VoxelContoursShape; import com.modularmc.mmclutils.spatial.VoxelShapes; @@ -12,13 +13,12 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.shapes.VoxelShape; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; import org.jspecify.annotations.Nullable; +import java.util.Arrays; + /** 在客户端线程分步读取已加载区段。单个复杂形状的读取同样受本轮时限约束。 */ -@OnlyIn(Dist.CLIENT) public final class SectionCapture { private static final Direction[] DIRECTIONS = Direction.values(); @@ -31,9 +31,11 @@ public final class SectionCapture { private final int[] visible = new int[4096]; private final BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); private final BlockPos.MutableBlockPos neighbor = new BlockPos.MutableBlockPos(); - private static final ChunkEntry UNQUERIED = new ChunkEntry(false, null); - private final ChunkEntry[] chunks = { UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED, UNQUERIED }; + private final LevelChunk[] chunks = new LevelChunk[9]; + private @Nullable ClientLevel world; + private @Nullable SectionGeometryData result; private @Nullable PendingBlock pending; + private int queriedChunks; private int cursor; public SectionCapture(long section, int modes) { @@ -43,7 +45,14 @@ public SectionCapture(long section, int modes) { this.modes = modes; } + /** 在同一客户端世界线程恢复采集,时限使用 System.nanoTime 计时。 */ public @Nullable SectionGeometryData advance(ClientLevel level, VoxelShapes 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); @@ -76,7 +85,10 @@ public SectionCapture(long section, int modes) { visible[index] = exposedFaces(level, position, state); if ((modes & SectionGeometryData.INCLUDE_TEMPERATURE) != 0 && (visible[index] != 0 || shape != VoxelContoursShape.BLOCK)) temperatures[index] = BlockEnvironment.temperature(state, level, position); } - return cursor == shapes.length ? new SectionGeometryData(origin, modes, shapes, temperatures, visible) : null; + if (cursor != shapes.length) return null; + Arrays.fill(chunks, null); + result = new SectionGeometryData(origin, modes, shapes, temperatures, visible); + return result; } private int exposedFaces(ClientLevel level, BlockPos position, BlockState state) { @@ -85,10 +97,10 @@ private int exposedFaces(ClientLevel level, BlockPos position, BlockState state) for (Direction direction : DIRECTIONS) { neighbor.setWithOffset(position, direction); LevelChunk chunk = loadedChunk(level, neighbor.getX() >> 4, neighbor.getZ() >> 4); - if (chunk == null) faces |= 1 << direction.ordinal(); + if (chunk == null) faces |= BlockDirections.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 |= 1 << direction.ordinal(); + if ((fluid.isEmpty() || !fluid.getType().isSame(adjacent.getFluidState().getType())) && Block.shouldRenderFace(level, position, state, adjacent, direction)) faces |= BlockDirections.mask(direction); } } return faces; @@ -96,15 +108,31 @@ private int exposedFaces(ClientLevel level, BlockPos position, BlockState state) private @Nullable LevelChunk loadedChunk(ClientLevel level, int chunkX, int chunkZ) { int chunkIndex = (chunkX - baseChunkX + 1) * 3 + chunkZ - baseChunkZ + 1; - ChunkEntry entry = chunks[chunkIndex]; - if (!entry.queried()) { - entry = new ChunkEntry(true, level.getChunkSource().getChunk(chunkX, chunkZ, false)); - chunks[chunkIndex] = entry; + int bit = 1 << chunkIndex; + if ((queriedChunks & bit) == 0) { + chunks[chunkIndex] = level.getChunkSource().getChunk(chunkX, chunkZ, false); + queriedChunks |= bit; } - return entry.chunk(); + return chunks[chunkIndex]; } - private record PendingBlock(BlockState state, VoxelShape shape) {} + 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 ChunkEntry(boolean queried, @Nullable LevelChunk chunk) {} + private record PendingBlock(BlockState state, VoxelShape shape) {} } diff --git a/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryCache.java b/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryCache.java new file mode 100644 index 0000000..032d7ed --- /dev/null +++ b/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryCache.java @@ -0,0 +1,97 @@ +package com.modularmc.mmclutils.client.level; + +import com.modularmc.mmclutils.spatial.VoxelShapes; + +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 VoxelShapes shapes = new VoxelShapes(); + 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 SectionGeometryData get(long section, int modes) { + Entry entry = sections.getAndMoveToLast(section); + return entry != null && entry.modes == modes ? entry.geometry : null; + } + + /** 推进采集至指定时限。采集完成时转交可在后台读取的数据。 */ + public @Nullable SectionGeometryData 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(); + } + SectionCapture 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 SectionCapture capture; + private @Nullable SectionGeometryData geometry; + + private Entry(long section, int modes) { + this.modes = modes; + capture = new SectionCapture(section, modes); + } + } +} diff --git a/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java b/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java index e1b02af..1497cbe 100644 --- a/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java +++ b/src/main/java/com/modularmc/mmclutils/client/level/SectionGeometryData.java @@ -2,11 +2,7 @@ import com.modularmc.mmclutils.spatial.VoxelContoursShape; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; - -/** 区段和一格邻接范围的几何数据。采集完成后可交由后台读取。 */ -@OnlyIn(Dist.CLIENT) +/** 区段和一格邻接范围的几何数据。构造时接管各数组,交付后调用方和后台线程均只读。 */ public record SectionGeometryData(long origin, int modes, VoxelContoursShape[] shapes, int[] temperatures, int[] visibleFaces) { public static final int INCLUDE_TEMPERATURE = 1; diff --git a/src/main/java/com/modularmc/mmclutils/client/level/SectionOccupancy.java b/src/main/java/com/modularmc/mmclutils/client/level/SectionOccupancy.java index 878a967..1e8c6d0 100644 --- a/src/main/java/com/modularmc/mmclutils/client/level/SectionOccupancy.java +++ b/src/main/java/com/modularmc/mmclutils/client/level/SectionOccupancy.java @@ -1,12 +1,8 @@ package com.modularmc.mmclutils.client.level; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; - import it.unimi.dsi.fastutil.objects.ObjectArrayList; -/** Fixed-size primitive pages. Ownership transfers after capture, avoiding a final whole-grid flatten/copy. */ -@OnlyIn(Dist.CLIENT) +/** 用原始类型分页存储占用区间的端点。采集结束后由后台只读访问。 */ public final class SectionOccupancy { private static final int PAGE_BITS = 10; @@ -14,6 +10,7 @@ public final class SectionOccupancy { 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]); diff --git a/src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java b/src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java index 2d8d178..a8fc3f3 100644 --- a/src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java +++ b/src/main/java/com/modularmc/mmclutils/spatial/LevelSections.java @@ -18,7 +18,7 @@ /** * 把维度的方块状态按区段交给 {@link SectionScan}。功能: *