Compare commits
2
Commits
ce1a195277
...
9f224236bf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f224236bf | ||
|
|
643802b329 |
@@ -41,3 +41,12 @@ __pycache__/
|
||||
/collab-workspace/result/TASK-M5/完成说明.md
|
||||
/collab-workspace/result/TASK-M4/完成说明.md
|
||||
/collab-workspace/
|
||||
/output/
|
||||
/modules/thaumicenergistics-neoRen/docs/
|
||||
/modules/thaumicenergistics-neoRen/tools/
|
||||
/modules/thaumicenergistics-neoRen/AGENTS.md
|
||||
/modules/thaumicenergistics-neo/CHANGELOG-2026-10-16.md
|
||||
/modules/thaumicnext/CONTAINER_SCANNING.md
|
||||
/PubLib/
|
||||
/modules/thaumicenergistics-neo/CHANGELOG-2026-10-24.md
|
||||
/modules/thaumicenergistics-neo/ISSUE-FIX-2.6.8.md
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# 当前代码结构与维护边界
|
||||
|
||||
更新于 2026-10-13。本文件描述当前实现,历史任务文档用于追溯,不作为运行完成的证据。
|
||||
|
||||
## 无线奥术终端
|
||||
|
||||
- 注册 ID 保持 `thaumicenergistics:wireless_arcane_crafting_terminal`。
|
||||
- `ModItems` 只通过返回公共 `Item` 类型的兼容工厂创建可选实现,避免 JVM 提前加载 `ItemWT`。
|
||||
- 完整 `ae2wtlib` 存在:`AE2WTArcaneTerminalItem` / `AE2WTArcaneTerminalMenuHost` 复用 AE2WT 连接、量子桥、奇点、电量与升级卡;客户端使用 `AE2WTArcaneTerminalScreen`,通过 `IUniversalTerminalCapable` 添加 Current Terminal 按钮与快捷键。
|
||||
- 完整 `ae2wtlib` 缺席:使用独立无线物品/宿主和普通奥术屏幕。只有其他附属模组自带 `ae2wtlib_api` 时也走独立实现;API 本身不是启用正式集成的判据。
|
||||
- `IArcaneTerminalInventoryHost` 只声明宿主能力;库存保存由 `PersistedTerminalInventories` 承担,打开期间的无线法杖补充由 `WirelessArcaneVis` 承担。
|
||||
- `ArcaneTerminalRecipeState` 负责配方和成本计算,菜单保留槽位、操作和状态同步。
|
||||
|
||||
## 源质转移
|
||||
|
||||
- `AspectIds`:要素 ID 与实例查找。
|
||||
- `EssentiaEndpoints`:带明确访问面的 TC capability 适配;未覆盖的旧容器交由兼容兜底。
|
||||
- `LegacyFurnaceEssentia`:固定 TC 版本炼金炉私有方面缓存的反射。`TCReflection` 保留旧入口,避免一次性破坏调用者。
|
||||
- `EssentiaTransfer`:网络与外部容器之间转移,返回实际交付量及余量;`insertOwned` 只处理已由 CPU/宿主持有的资源。
|
||||
- `TransferBudget` / `EssentiaEnergy`:取得能量预算、限制资源数量、结算实际量并退款。
|
||||
- `EssentiaItemContainers` / `EssentiaFillHelper`:真实玩家容器及部分成功后的内容保存。
|
||||
- `EssentiaContainerItemStrategy`:AE2 标准填充/抽空及源质包装物品回收。
|
||||
- `EssentiaTerminalInputHandler`:必要的客户端自定义手势;不拦截工具栏按钮。
|
||||
- `EssentiaStorageBusInventory`:源质视图的读写权限和分区过滤,过滤配置变化才重新构建分区。
|
||||
- `EssentiaInterfaceState`:接口缓冲与业务规则,Mixin 只接入字段和生命周期。
|
||||
|
||||
余量属于产生它的宿主,必须保存并重试。拆除无法退网的源质通过 AE2 包装物品保存,不能忽略实际插入数量。
|
||||
|
||||
## 样板与装配器
|
||||
|
||||
- `ArcaneAssemblerPattern`:AE2 样板定义与真实输入校验。
|
||||
- `ArcanePatternDecoder`:完整编码样板的身份与解码,区分同产物不同配方。
|
||||
- `ArcaneCraftJob`:当前订单的实际输入、配方成本、产物和待输出余量;沿用既有存档键。
|
||||
- `TileArcaneAssembler`:节点、制作进度、vis 补充与方块生命周期。
|
||||
|
||||
制作前只校验 CPU 输入,接受后才清空输入计数器。生成产物只发生一次;之后只重试未被网络接收的部分。拆除时,制作前退真实输入,制作后掉落剩余产物和催化剂。
|
||||
|
||||
旧版本没有保存完整订单。仅在知识核心能唯一恢复对应配方时恢复;不能唯一确定时暂停旧订单并记录日志,不猜配方或让新订单覆盖它。
|
||||
|
||||
## 第三方供应器
|
||||
|
||||
`ProviderEssentiaTargets` 共用卡片判断与输出组合目标,物品/流体继续使用原目标,源质使用 `ThEEssentiaPushTarget`,不再次从网络取料。
|
||||
|
||||
- AE2 / EAE:沿用 AE2 逻辑和卡槽接入。EAE 准入采用注册 ID 软查。
|
||||
- AAE 1.6.12:独立逻辑、宿主、菜单与两种屏幕追加升级库存及 UI;AppFlux 在场时跳过我方卡槽组。双参数 `findAdapter` 出口接入源质能力,能力组不与 AppFlux 互斥。
|
||||
- AE2LT 2.1.2-beta3:普通路径复用 AE2;`ProviderTarget.resolveStorageTarget` 出口按来源卡片接入源质目标,定向、无线、批量和余量重试沿用其原生派发。
|
||||
|
||||
上述是代码实现范围,最终运行验收由用户负责,不宣称覆盖其他版本。
|
||||
|
||||
## 其他职责拆分
|
||||
|
||||
- `InfusionMonitorDisplay` / `InfusionMonitorText` 管理注魔监控器显示实体与文字;风险采集仍使用已有计算器和扫描间隔。
|
||||
- `ProbabilityBrainRules` 集中概率之脑随机规则和数值;方块实体保留绑定、付费、库存及持久化协调。
|
||||
|
||||
## Mixin 边界
|
||||
|
||||
删除了两个空 Mixin 和两个重复屏幕点击 Mixin。原有配置保留 19 个接入;AAE 增加 6 个可选接入,AE2LT 增加 1 个可选接入,总计配置 26 个。可选加载插件在目标模组缺席时跳过对应接入。
|
||||
|
||||
保留 Mixin 的原因是宿主卡槽、生命周期和来源卡片门控没有足够的公开注册 API;不为减少数量而移除必要门控。
|
||||
|
||||
依赖和参考资料版本见 [DEPENDENCIES.md](DEPENDENCIES.md)。本轮交付记录见 [CHANGELOG-2026-10-13.md](CHANGELOG-2026-10-13.md)。
|
||||
@@ -0,0 +1,61 @@
|
||||
# 2026-10-13 审查整改与兼容交付
|
||||
|
||||
## 当前交付状态
|
||||
|
||||
用户已授权实施审查建议,并明确后续测试由用户负责。本轮代码已编译和打包;最终构建未运行测试。修改尚未提交,Git HEAD 仍为 5716d61,因此内部版本仍为 2.5.13-alpha。
|
||||
|
||||
测试包:`build/libs/ThaumicEnergistics-1.21.1-neoforge-2.5.13-alpha-review-20261013-aba095b5.jar`
|
||||
|
||||
- 大小:1,590,828 B
|
||||
- SHA-1:`aba095b5f7b242252a77ea8966fbaa38b52acb40`
|
||||
- 内部版本:`2.5.13-alpha`
|
||||
- 4 个 Mixin 配置,合计 26 个配置类,已确认对应 class 均在包内。
|
||||
- 发布包不包含 gameTest 测试类。
|
||||
|
||||
这个包包含新的源码修改,与此前同名 2.5.13-alpha 旧包内容不同,请按以上指纹区分。安装时替换旧包,避免同一模组加载两个 JAR。
|
||||
|
||||
## 已实现
|
||||
|
||||
1. **Current Terminal 切换修复**:AE2WT 奥术屏幕实现官方 IUniversalTerminalCapable,创建左侧切换按钮并接入快捷键;保留 IPN 忽略标记。量子连接继续由 WTMenuHost 处理。
|
||||
2. **可选加载修复**:普通物品注册只调用返回 Item 的兼容工厂,避免缺少 AE2WT 时提前解析 ItemWT。只有其他附属携带旧 API 时,不强迫启用 AE2WT 实现,也不拦截独立终端运行。
|
||||
3. **容器真实来源与部分转移**:服务器验证物品和网络连接,更新实际玩家槽位/光标/主手;保留未转移内容,不使用客户端副本补料,不做错误的网络回滚。
|
||||
4. **资源所有权与能量**:供应器输出已由 CPU 持有的源质,不再次扣网络资源;总线使用统一能量预算,实际量计费、未使用预算退款;退回失败的余量保留并持久化。
|
||||
5. **读写与过滤**:源质存储总线通过库存处理器应用权限及过滤,并缓存分区配置;多要素输入按过滤和网络容量选择,避免首项饿死后续要素。
|
||||
6. **API 替代与拆除恢复**:标准容器交互使用 AE2 ContainerItemStrategy;自定义点击使用 NeoForge 屏幕事件;拆除源质余量使用可回收的 AE2 包装物品。
|
||||
7. **安全合并配方**:四个配方使用本项目序列化器;升级卡不足、物品库存/奇点/绑定冲突或电量无法全部容纳时拒绝配方;终端偏好冲突以另一终端/已有通用终端为准。补齐 JEI 展示入口。
|
||||
8. **装配器订单**:完整样板身份和解码器,接受前校验真实 CPU 输入,接受后清空输入计数器;执行状态和待输出余量保存,产物只生成一次,网络拒收后仅重试余量;重载不叠加额外节点耗电。
|
||||
9. **AAE 1.6.12**:独立逻辑与菜单升级槽、大小两种屏幕升级面板及源质输出入口。AppFlux 在场时仅跳过我方卡槽组,源质组继续接入其升级库存。
|
||||
10. **AE2LT 2.1.2-beta3**:通过 ProviderTarget.resolveStorageTarget 的共享出口按来源卡片增加源质目标,复用定向/无线/批量调度和原生余量队列,不注册全局强制 TC 适配器。
|
||||
11. **职责拆分**:样板、订单、终端配方/法杖补充、接口状态、库存保存、概率规则、注魔显示、要素 ID 和遗留炼金炉反射各有独立类。删除 4 个旧 Mixin 和日志空入口,清理过时注释。
|
||||
12. **依赖和资料**:兼容开发开关补齐基础运行前置及 GeckoLib/Glodium;添加 ARCHITECTURE.md、DEPENDENCIES.md,保留旧资料,不移动庞大的 library。
|
||||
|
||||
## 给用户的验收重点
|
||||
|
||||
- 通用终端切入奥术后,左侧 Current Terminal 仍存在,左右键/快捷键能切回;持有源质容器点击工具栏不会被拦截。
|
||||
- 量子桥卡 + 奇点使用正常,取消无线访问节点后仍按 AE2WT 的量子路径连接;取出桥卡/奇点后连接规则恢复。
|
||||
- 合并保留电量、升级卡、奇点、绑定、法杖和合成材料;升级槽不足或重要数据冲突时不能生成会丢数据的结果。
|
||||
- 源质部分存入/取出、网络满、能量不足、断网、拆除和重载时总量守恒;包装掉落可用容器或终端回收。
|
||||
- 装配器同输出不同配方、实际替代材料、制作中重载、部分输出和珍珠返还。
|
||||
- EAE 四宿主、AAE 大小两档方块/部件、AE2LT 两档方块,分别核对插卡、拔卡、派发、持久化和 AppFlux 组合。
|
||||
- 未安装 AE2WT/AAE/AE2LT/EAE 时的客户端和服务端;仅装第三方附属自带 API 时的独立终端;AAE/AE2LT 新 Mixin 注入点需要重点观察启动日志。
|
||||
|
||||
旧存档正在制作的订单没有完整定义:核心里能唯一对应的配方才恢复;缺失或同产物多配方导致歧义时暂停旧订单并记录日志。恢复唯一对应的知识核心后才继续,不会猜配方或覆盖该订单。
|
||||
|
||||
## 验证边界
|
||||
|
||||
最终只执行源码编译、打包和包内容检查,未运行新的测试。
|
||||
|
||||
用户接管测试前,曾通过 6 项 TransferBudget 单元测试及基础/AE2WT 隔离服务器的小范围游戏检查。之后进行了职责拆分、JEI 展示、AAE/AE2LT 接入和依赖调整,因此早期结果不代表最终包已完成实机验收。UI 切换、完整量子链路、全部供应器组合与大量设备性能仍由用户验收。
|
||||
|
||||
没有性能采样结果,不宣称已经消除性能瓶颈;本轮仅移除已知重复工作并增加必要缓存。
|
||||
|
||||
## 构建与源码
|
||||
|
||||
编译/打包(跳过测试):
|
||||
|
||||
```powershell
|
||||
$env:GRADLE_USER_HOME = 'D:\GradleCache'
|
||||
& 'D:\Software\Gradle\gradle-8.12.1\bin\gradle.bat' :thaumicenergistics:assemble --offline -x test
|
||||
```
|
||||
|
||||
依赖版本、modid、指纹、运行开关见 [DEPENDENCIES.md](DEPENDENCIES.md);类职责与 Mixin 边界见 [ARCHITECTURE.md](ARCHITECTURE.md)。
|
||||
@@ -0,0 +1,56 @@
|
||||
# 依赖与参考资料索引
|
||||
|
||||
更新于 2026-10-13。`library` 是资料区,不等于全部运行依赖;没有移动或删除其中的旧资料。
|
||||
|
||||
## 当前依赖
|
||||
|
||||
- Minecraft 1.21.1 / NeoForge 21.1.234 / Java 21。
|
||||
- AE2 Maven 坐标 `org.appliedenergistics:appliedenergistics2:19.2.17`,同时使用 API 与完整 JAR 编译内部接入。
|
||||
- AE2 完整 JAR SHA-1:`49c18d6a4af487957d7e5a6ad5dcbf71090b8e14`;sources JAR SHA-1:`260a230e9fa1b4885489f7f58b30c19226093a52`。
|
||||
- AE2WT API 编译坐标 `de.mari_023:ae2wtlib_api:19.5.1`,`transitive=false`。仅完整 `ae2wtlib` 存在时加载接入类。
|
||||
- 生产依赖保持 compileOnly;开发运行前置只在兼容开关启用时添加。
|
||||
|
||||
| library 文件 | modid | 用途 | SHA-1 |
|
||||
|---|---|---|---|
|
||||
| AdvancedAE-1.6.12-1.21.1.jar | advanced_ae | 可选 AAE 接入;Maven ablTMAjP 与该文件同指纹 | `9358ccfa5477c7ab1c5ffab6c831e105fe46ecc3` |
|
||||
| ae2jeiintegration-1.2.1.jar | ae2jeiintegration | 当前可选 JEI 转换 API | `e99898b3e9c32bf6ac757e7ad50247746622cdfc` |
|
||||
| ae2lt-2.1.2-beta3.jar | ae2lt | 可选 AE2LT 接入;Maven AosdXlfS | `f21381bdcc4af71781050f02166d847e4dbb0880` |
|
||||
| ae2wtlib-19.5.1.jar | ae2wtlib | 可选正式接入与运行开关 | `b1bee01393b15f1eb0f46d58862ef99234e1d337` |
|
||||
| ae2wtlib_api-19.5.1.jar | ae2wtlib_api | API 对照;Gradle 使用固定 Maven 编译坐标 | `8383d132b7b5f4b31ca77c7bdbaf61fe01aaabc1` |
|
||||
| ExtendedAE-1.21-2.2.35-neoforge.jar | extendedae | 可选 EAE 对照;Maven bC302UUP | `e3521ca2567fabe0f0131cc923ec94dd99d6fa7b` |
|
||||
| extendedae_plus-1.6.1.jar | extendedae_plus | 当前可选 EAP Mixin 编译目标 | `222c613c091ab607ad6f8b900600c77bf804ac1c` |
|
||||
| InventoryProfilesNext-neoforge-1.21.1-2.2.5.jar | inventoryprofilesnext | 当前 IPN 注解编译依赖 | `b09d7c0820c233ea34af54d0a3ab7ed510b32dcc` |
|
||||
| jei-1.21.1-neoforge-19.39.0.368.jar | jei | 当前可选 JEI 编译 API | `82a8ee647d81c40f149c444c5d37088f035cb773` |
|
||||
| thaumcraft-0.2.2.34-port.1.jar | thaumcraft | 历史/辅助对照;不是当前编译基线 | `852fd2a72632d14c5bcf0f6dcab054f18bf059f9` |
|
||||
| thaumcraft-0.2.2.95-port.229.jar | thaumcraft | 历史/辅助对照;不是当前编译基线 | `63fd2766e3853cb4bb6985a3f3f627a5e2c51b45` |
|
||||
| thaumcraft-0.2.2.95-port.256.jar | thaumcraft | 历史/辅助对照;不是当前编译基线 | `bc0c25588ea23ea4c1d02df02662dc01de7230aa` |
|
||||
| thaumcraft-0.2.2.95-port.261.jar | thaumcraft | 当前编译与运行基线 | `1584c9cedfacf25009d0518697e98290c9f5d4fd` |
|
||||
| thunderbolt-2.0.3-beta2.jar | thunderbolt | AE2LT 前置;Maven oyVnlG5A | `f16d374a08f5cde870d4221e5c8e7d89f858e0d4` |
|
||||
| wcwt-1.3.8.jar-ME综合工作终端.jar | wcwt | 历史/辅助对照;不是当前编译基线 | `02b41fab2e7507edb9c98aa43f750bf466010880` |
|
||||
|
||||
## 固定兼容版本与开发运行
|
||||
|
||||
- `-PcompatWT=true`:AE2WT 19.5.1,完整 JAR 内嵌对应 API。
|
||||
- `-PcompatAAE=true`:AAE 1.6.12(ablTMAjP)+ GeckoLib 4.8.2(RVIo5f6E);AAE 内嵌 AE2AddonLib 1.0.3 和 AE2WT API 19.2.5。
|
||||
- `-PcompatAE2LT=true`:AE2LT 2.1.2-beta3(AosdXlfS)+ Thunderbolt 2.0.3-beta2(oyVnlG5A);AE2LT 内嵌 AE2WT API 19.4.1。
|
||||
- `-PenableExtendedAeCompatTest=true`:EAE 1.21-2.2.35(bC302UUP)+ Glodium 1.21-2.2(pfbmdJ3b);EAE 内嵌 AE2WT API 19.2.0。
|
||||
- 启用任一兼容开关自动补齐 AE2、TC、GuideME 21.1.1(PALpfSdf)、Curios 9.5.1+1.21.1(yohfFbgD)。已下载的隔离依赖可复用 `build/smoke-deps`。
|
||||
- 仅第三方附属模组自带旧 AE2WT API 时,不启用我方 ItemWT 实现,也不因 API 版本阻止独立终端启动;完整 AE2WT 自身会要求其匹配的 API。
|
||||
- AE2LT 元数据要求 AE2 `[19.2.17,19.3)`,不要在这套组合中升级到 19.3+。
|
||||
|
||||
## 资料优先级
|
||||
|
||||
1. 当前固定版本的完整 JAR / sources JAR / 实际字节码。
|
||||
2. 与固定版本一致的 API 文档。
|
||||
3. `thaumcraft-addon-sdk-0.2.2.95-port.264` 只作导航,不能替代 port.261 的实际 API。
|
||||
4. `参考` 内旧 TC port.34/其他反编译、1.7.10 源码及 AE2 工作树只用于历史和思路对照;先核对版本。
|
||||
5. `ExtendedAE-appflux-1.21.1-neoforge` 可用于卡槽蓝图对照,不能直接照搬其能量或工具箱私有类型。
|
||||
6. 材质包、备份资源、日志与笔记不进入编译依赖;不进行整体递归扫描。
|
||||
|
||||
## 发布来源
|
||||
|
||||
- [AE2](https://github.com/AppliedEnergistics/Applied-Energistics-2)、[AE2WT](https://github.com/Mari023/AE2WirelessTerminalLibrary/tree/1.21.1)。
|
||||
- [AdvancedAE 固定发布](https://modrinth.com/mod/advancedae/version/ablTMAjP)、[AE2LT 固定发布](https://modrinth.com/mod/ae2-lightning-tech/version/AosdXlfS)。
|
||||
- [ExtendedAE 固定发布](https://modrinth.com/mod/extended-ae/version/bC302UUP)。
|
||||
- [GeckoLib](https://modrinth.com/mod/geckolib/version/RVIo5f6E)、[Glodium](https://modrinth.com/mod/glodium/version/pfbmdJ3b)、[GuideME](https://modrinth.com/mod/guideme/version/PALpfSdf)、[Curios](https://modrinth.com/mod/curios/version/yohfFbgD)。
|
||||
- TC 使用本地 port.261 构件,索引记录本地指纹,不把旧 SDK 或旧源码目录当作该构件来源。
|
||||
+111
-32
@@ -3,6 +3,8 @@ plugins {
|
||||
id 'maven-publish'
|
||||
}
|
||||
|
||||
apply from: file('../../versioning.gradle')
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
def localRepository = mavenLocal()
|
||||
@@ -19,6 +21,14 @@ repositories {
|
||||
maven {
|
||||
url "https://api.modrinth.com/maven"
|
||||
}
|
||||
// COMPAT-PLAN:ae2wtlib_api 独立坐标(完整 ae2wtlib jar 的 API 在内嵌 jar,
|
||||
// 外层 compileOnly files 看不到 API 类,必须用 modmaven 的独立 API 构件)
|
||||
maven {
|
||||
url "https://modmaven.dev"
|
||||
content {
|
||||
includeGroup "de.mari_023"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
group = mod_group
|
||||
@@ -27,21 +37,69 @@ var modName = mod_name
|
||||
var mcVersion = minecraft_version
|
||||
base { archivesName = "${modName}-${mcVersion}-neoforge" }
|
||||
|
||||
def compatBaseRun = ['compatSmokeTest', 'compatWT', 'compatAAE', 'compatAE2LT', 'enableExtendedAeCompatTest']
|
||||
.any { key -> providers.gradleProperty(key).map { it.toBoolean() }.getOrElse(false) }
|
||||
|
||||
java {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(21)
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
gameTest {
|
||||
compileClasspath += sourceSets.main.output
|
||||
runtimeClasspath += sourceSets.main.output
|
||||
}
|
||||
}
|
||||
configurations {
|
||||
gameTestImplementation.extendsFrom implementation
|
||||
gameTestCompileOnly.extendsFrom compileOnly
|
||||
gameTestRuntimeOnly.extendsFrom runtimeOnly
|
||||
}
|
||||
|
||||
neoForge {
|
||||
version = neoforge_version
|
||||
addModdingDependenciesTo(sourceSets.gameTest)
|
||||
runs {
|
||||
client { client() }
|
||||
server { server() }
|
||||
smokeServer {
|
||||
server()
|
||||
gameDirectory = file('build/smoke-server')
|
||||
programArgument '--nogui'
|
||||
}
|
||||
smokeGameTests {
|
||||
type = 'gameTestServer'
|
||||
sourceSet = sourceSets.gameTest
|
||||
gameDirectory = file('build/smoke-gametests')
|
||||
systemProperty 'neoforge.enabledGameTestNamespaces', 'thaumicenergistics_tests'
|
||||
}
|
||||
}
|
||||
mods { "${mod_id}" { sourceSet sourceSets.main } }
|
||||
if (providers.gradleProperty('compatSmokeTest').map { it.toBoolean() }.getOrElse(false)) {
|
||||
mods { thaumicenergistics_tests { sourceSet sourceSets.gameTest } }
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.10.2'
|
||||
// 兼容联调开关自动补齐基础运行前置;普通生产构建仍仅 compileOnly。
|
||||
if (compatBaseRun) {
|
||||
runtimeOnly('org.appliedenergistics:appliedenergistics2:19.2.17') {
|
||||
exclude group: 'org.appliedenergistics', module: 'guideme'
|
||||
}
|
||||
def localGuide = file('build/smoke-deps/guideme-21.1.1.jar')
|
||||
if (localGuide.exists()) runtimeOnly files(localGuide)
|
||||
else runtimeOnly 'maven.modrinth:guideme:PALpfSdf'
|
||||
runtimeOnly files('library/thaumcraft-0.2.2.95-port.261.jar')
|
||||
def localCurios = file('build/smoke-deps/curios-neoforge-9.5.1+1.21.1.jar')
|
||||
if (localCurios.exists()) runtimeOnly files(localCurios)
|
||||
else runtimeOnly 'maven.modrinth:curios:yohfFbgD'
|
||||
}
|
||||
if (providers.gradleProperty('compatWT').map { it.toBoolean() }.getOrElse(false)) {
|
||||
runtimeOnly files('library/ae2wtlib-19.5.1.jar')
|
||||
}
|
||||
compileOnly "org.appliedenergistics:appliedenergistics2:19.2.17:api"
|
||||
compileOnly "org.appliedenergistics:appliedenergistics2:19.2.17" // 加这行保留!!让AE2内部类可编译
|
||||
compileOnly files('library/thaumcraft-0.2.2.95-port.261.jar') // 必须与整合包运行版本一致(0.2.2.95);.34 缺少 getRemainingItems/findMatchingArcaneRecipeEntry 等 API
|
||||
@@ -50,6 +108,54 @@ dependencies {
|
||||
compileOnly files('library/InventoryProfilesNext-neoforge-1.21.1-2.2.5.jar')
|
||||
compileOnly files('library/extendedae_plus-1.6.1.jar') // eap mixin target(InputEvents.toGenericStack)
|
||||
compileOnly "maven.modrinth:jade:${jade_version}"
|
||||
|
||||
// COMPAT-PLAN 编译依赖:全部可选集成,零运行时强依赖(普通代码仅 ModList 守护 +
|
||||
// 注册表软查;Mixin 目标类引用仅出现在各自独立 mixins.json 的兼容配置内)。
|
||||
// ae2wtlib_api:ItemWT/WTMenuHost/AddTerminalEvent 正式接入奥术终端功能。
|
||||
compileOnly("de.mari_023:ae2wtlib_api:19.5.1") {
|
||||
transitive = false
|
||||
}
|
||||
// AdvancedAE:AdvPatternProviderLogic 独立卡槽组与源质能力组 Mixin 编译。
|
||||
compileOnly("maven.modrinth:advancedae:ablTMAjP") {
|
||||
transitive = false
|
||||
}
|
||||
// AE2 Lightning Tech:过载样板供应器独立派发路径源质门控 Mixin 编译。
|
||||
compileOnly("maven.modrinth:ae2-lightning-tech:AosdXlfS") {
|
||||
transitive = false
|
||||
}
|
||||
|
||||
// EAE-COMPAT 联调开关:仅指定 -PenableExtendedAeCompatTest=true 时加载 Extended AE
|
||||
// (1.21-2.2.35-neoforge,Modrinth bC302UUP)作运行时依赖;兼容代码零 EAE 编译引用,
|
||||
// API 由本体内嵌,基础前置由 compatBaseRun 提供,Glodium 在此补齐。
|
||||
if (providers.gradleProperty('enableExtendedAeCompatTest')
|
||||
.map { it.toBoolean() }
|
||||
.getOrElse(false)) {
|
||||
runtimeOnly("maven.modrinth:extended-ae:bC302UUP") {
|
||||
transitive = false
|
||||
}
|
||||
runtimeOnly("maven.modrinth:glodium:pfbmdJ3b") { transitive = false }
|
||||
}
|
||||
// COMPAT-PLAN 联调开关:同上,仅运行环境加载,生产构建不受影响。
|
||||
// AAE 内嵌 AE2AddonLib/API,外部前置 GeckoLib 在此补齐。
|
||||
if (providers.gradleProperty('compatAAE')
|
||||
.map { it.toBoolean() }
|
||||
.getOrElse(false)) {
|
||||
runtimeOnly("maven.modrinth:advancedae:ablTMAjP") {
|
||||
transitive = false
|
||||
}
|
||||
runtimeOnly("maven.modrinth:geckolib:RVIo5f6E") { transitive = false }
|
||||
}
|
||||
// AE2LT 必需前置 Thunderbolt Core(2.0.3-beta2,Modrinth oyVnlG5A),随开关一起加载。
|
||||
if (providers.gradleProperty('compatAE2LT')
|
||||
.map { it.toBoolean() }
|
||||
.getOrElse(false)) {
|
||||
runtimeOnly("maven.modrinth:ae2-lightning-tech:AosdXlfS") {
|
||||
transitive = false
|
||||
}
|
||||
runtimeOnly("maven.modrinth:thunderbolt-core:oyVnlG5A") {
|
||||
transitive = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,8 +164,12 @@ tasks.withType(JavaCompile).configureEach {
|
||||
it.options.release = 21
|
||||
}
|
||||
|
||||
tasks.withType(Test).configureEach {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
// mods.toml 的 version 也用 git 实时版本(与 jar 版本一致,不依赖写死的 mod_version)
|
||||
var modVersion = gitVersion()
|
||||
var modVersion = version.toString()
|
||||
def loaderRange = project.findProperty('loader_version_range') ?: '[4,)'
|
||||
def neoforgeRange = project.findProperty('neoforge_version_range') ?: '[21,)'
|
||||
def mcRange = project.findProperty('minecraft_version_range') ?: '[1.21.1,1.22)'
|
||||
@@ -86,34 +196,3 @@ jar {
|
||||
include 'pack.png'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//// 获取git提交总数
|
||||
//def gitCommitCount = providers.exec {
|
||||
// commandLine 'git', 'rev-list', '--count', 'HEAD'
|
||||
//}.standardOutput.asText.map { it.trim() }
|
||||
//
|
||||
//// 最终完整版本 = 主版本+构建号
|
||||
//version = "${mod_version}.${gitCommitCount.get()}-alpha"
|
||||
// build.gradle 替换现有 version 逻辑
|
||||
def gitVersion() {
|
||||
def describe = providers.exec {
|
||||
commandLine 'git', 'describe', '--tags', '--always'
|
||||
}.standardOutput.asText.map { it.trim() }.get()
|
||||
// 支持 "2.2" / "v2.2.0" / "2.2-3-gabc1234" / "abc1234"(无tag时)
|
||||
// 版本 = tag 的 X.Y + 提交数:tag 2.2 + 2 提交 → 2.2.2
|
||||
// find() 只匹配开头,忽略尾部 commit hash(-gabc1234)
|
||||
// [vV] 兼容大小写标签前缀(V2.5 / v2.4)
|
||||
def m = describe =~ /^[vV]?(\d+\.\d+)(?:\.\d+)?(?:-(\d+))?/
|
||||
if (m.find()) {
|
||||
def xy = m.group(1) // 2.2
|
||||
def count = m.group(2) ? m.group(2) : '0' // tag 后提交数
|
||||
return "${xy}.${count}-alpha" // 2.2.2-alpha
|
||||
}
|
||||
// 兜底(从未打 tag):0.0.<提交总数>-alpha,不依赖写死的 mod_version
|
||||
def count = providers.exec {
|
||||
commandLine 'git', 'rev-list', '--count', 'HEAD'
|
||||
}.standardOutput.asText.map { it.trim() }.get()
|
||||
return "0.0.${count}-alpha"
|
||||
}
|
||||
version = modVersion
|
||||
+3
-3
@@ -14,13 +14,13 @@ neoforge_version=21.1.234
|
||||
# Dependency versions
|
||||
ae2_version=19.2.17
|
||||
jei_version=19.39.0.368
|
||||
thaumcraft_version=0.2.2.34-port.1
|
||||
thaumcraft_version=0.2.2.95-port.261
|
||||
jade_version=15.9.1+neoforge
|
||||
org.gradle.jvmargs=-Xmx2G
|
||||
org.gradle.jvmargs=-Xmx4G -Xms2G
|
||||
org.gradle.daemon=true
|
||||
org.gradle.parallel=true
|
||||
org.gradle.caching=true
|
||||
org.gradle.configuration-cache=true
|
||||
org.gradle.build-cache.enabled=true
|
||||
minecraft_version_range=[1.21.1,1.22)
|
||||
neoforge_version_range=[21,)
|
||||
loader_version_range=[4,)
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package thaumicenergistics.tests;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.RedstoneMode;
|
||||
import appeng.api.config.Settings;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.parts.PartHelper;
|
||||
import appeng.api.stacks.AEKey;
|
||||
import appeng.api.stacks.GenericStack;
|
||||
import appeng.api.storage.MEStorage;
|
||||
import appeng.api.util.AEColor;
|
||||
import appeng.blockentity.networking.CableBusBlockEntity;
|
||||
import appeng.core.definitions.AEBlocks;
|
||||
import appeng.core.definitions.AEItems;
|
||||
import appeng.core.definitions.AEParts;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.EssentiaCapabilities;
|
||||
import thaumcraft.common.blockentities.ArcaneLampFertilityBlockEntity;
|
||||
import thaumcraft.common.blockentities.JarBlockEntity;
|
||||
import thaumicenergistics.api.storage.AspectStack;
|
||||
import thaumicenergistics.common.essentia.capability.EssentiaContainerStorage;
|
||||
import thaumicenergistics.common.essentia.capability.EssentiaTransferBuffer;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.tc.AspectIds;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaEndpoints;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
final class EssentiaBusChecks {
|
||||
static void jarsFromEveryFace(GameTestHelper helper) {
|
||||
var pos = new BlockPos(1, 1, 1);
|
||||
helper.setBlock(pos, block("jar_of_essentia"));
|
||||
JarBlockEntity jar = helper.getBlockEntity(pos);
|
||||
var key = AEssentiaKey.of(AspectIds.getAspectId(Aspect.LIFE));
|
||||
var source = IActionSource.ofPlayer(helper.makeMockPlayer(GameType.SURVIVAL));
|
||||
for (Direction side : Direction.values()) {
|
||||
jar.clearContents();
|
||||
jar.removeFilter();
|
||||
var storage = new EssentiaContainerStorage(() -> jar, Component.literal("jar test"), () -> side);
|
||||
helper.assertTrue(storage.insert(key, 12, Actionable.SIMULATE, source) == 12,
|
||||
"Storage simulation must accept jar face " + side);
|
||||
helper.assertTrue(jar.getAmount() == 0, "Simulation must not change the jar");
|
||||
helper.assertTrue(EssentiaEndpoints.insert(jar, key.getId(), 12, side) == 12,
|
||||
"Export must fill jar face " + side);
|
||||
helper.assertTrue(EssentiaEndpoints.contents(jar, side).getFirst().amount() == 12,
|
||||
"Import must see the same contents on " + side);
|
||||
helper.assertTrue(storage.extract(key, 4, Actionable.SIMULATE, source) == 4 && jar.getAmount() == 12,
|
||||
"Storage extraction simulation is non-destructive");
|
||||
var extracted = EssentiaEndpoints.extract(jar, key.getId(), 4, side);
|
||||
helper.assertTrue(extracted != null && extracted.amount() == 4 && jar.getAmount() == 8,
|
||||
"Import must extract from jar face " + side);
|
||||
helper.assertTrue(storage.insert(key, 100, Actionable.SIMULATE, source) == 56,
|
||||
"Six-face access must retain the jar capacity");
|
||||
helper.assertTrue(storage.insert(key, 100, Actionable.MODULATE, source) == 56 && jar.getAmount() == 64,
|
||||
"Storage simulation and actual insertion must agree");
|
||||
jar.clearContents();
|
||||
jar.setFilter(Aspect.AIR);
|
||||
helper.assertTrue(EssentiaEndpoints.insert(jar, key.getId(), 1, side) == 0
|
||||
&& storage.insert(key, 1, Actionable.SIMULATE, source) == 0,
|
||||
"Six-face access must retain the label filter");
|
||||
}
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
static void fertilityLampPullsFromExportBus(GameTestHelper helper) {
|
||||
var level = helper.getLevel();
|
||||
var cablePos = new BlockPos(1, 1, 1);
|
||||
var lampPos = cablePos.above();
|
||||
helper.setBlock(cablePos.west(), AEBlocks.CREATIVE_ENERGY_CELL.block());
|
||||
var absoluteCable = helper.absolutePos(cablePos);
|
||||
PartHelper.setPart(level, absoluteCable, null, null, AEParts.GLASS_CABLE.item(AEColor.TRANSPARENT));
|
||||
var bus = PartHelper.setPart(level, absoluteCable, Direction.UP, null, AEParts.EXPORT_BUS.get());
|
||||
helper.assertTrue(bus != null, "Export bus must install below the lamp");
|
||||
var key = AEssentiaKey.of(AspectIds.getAspectId(Aspect.LIFE));
|
||||
bus.getConfig().setStack(0, new GenericStack(key, 1));
|
||||
helper.setBlock(lampPos, block("arcane_lamp_fertility"));
|
||||
ArcaneLampFertilityBlockEntity lamp = helper.getBlockEntity(lampPos);
|
||||
var nbt = lamp.saveWithFullMetadata(level.registryAccess());
|
||||
nbt.putInt("orientation", Direction.DOWN.get3DDataValue());
|
||||
lamp.loadWithComponents(nbt, level.registryAccess());
|
||||
long[] remaining = {16};
|
||||
MEStorage inventory = new MEStorage() {
|
||||
@Override public Component getDescription() { return Component.literal("lamp supply"); }
|
||||
@Override public long extract(AEKey what, long amount, Actionable mode, IActionSource source) {
|
||||
long taken = key.equals(what) ? Math.min(amount, remaining[0]) : 0;
|
||||
if (mode == Actionable.MODULATE) remaining[0] -= taken;
|
||||
return taken;
|
||||
}
|
||||
@Override public long insert(AEKey what, long amount, Actionable mode, IActionSource source) {
|
||||
if (!key.equals(what)) return 0;
|
||||
if (mode == Actionable.MODULATE) remaining[0] += amount;
|
||||
return amount;
|
||||
}
|
||||
};
|
||||
helper.runAfterDelay(40, () -> {
|
||||
helper.assertTrue(bus.getMainNode().isActive(), "Test ME network must have power and a channel");
|
||||
var grid = bus.getMainNode().getGrid();
|
||||
grid.getStorageService().addGlobalStorageProvider(mounts -> mounts.mount(inventory, 0));
|
||||
var endpoint = EssentiaCapabilities.find(level, absoluteCable, Direction.UP);
|
||||
helper.assertTrue(endpoint != null && !endpoint.canOutputTo(Direction.UP), "No card must mean no supply");
|
||||
helper.assertTrue(bus.getUpgrades().addItems(new ItemStack(ModItems.ESSENTIA_UPGRADE_CARD.get())).isEmpty(),
|
||||
"Essentia card must install");
|
||||
grid.getTickManager().alertDevice(bus.getMainNode().getNode());
|
||||
});
|
||||
helper.runAfterDelay(110, () -> {
|
||||
helper.assertTrue(lamp.charges() > 0, "Real fertility lamp must draw LIFE without an intermediary jar");
|
||||
var buffer = (EssentiaTransferBuffer) bus;
|
||||
helper.assertTrue(remaining[0] + buffer.thE$getTransferBuffer().amount() + lamp.charges() == 16,
|
||||
"Network, persisted bus stock and lamp charges must conserve essentia");
|
||||
var endpoint = EssentiaCapabilities.find(level, absoluteCable, Direction.UP);
|
||||
helper.assertTrue(endpoint.takeEssentia(Aspect.AIR, 1, Direction.UP) == 0,
|
||||
"Wrong aspect must not consume stock");
|
||||
helper.assertTrue(endpoint.takeEssentia(Aspect.LIFE, 1, Direction.DOWN) == 0,
|
||||
"Only the outward export-bus face may supply");
|
||||
bus.getUpgrades().addItems(AEItems.REDSTONE_CARD.stack());
|
||||
bus.getConfigManager().putSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.HIGH_SIGNAL);
|
||||
helper.assertTrue(endpoint.takeEssentia(Aspect.LIFE, 1, Direction.UP) == 0,
|
||||
"Disabled redstone mode must block consumer pulls");
|
||||
bus.getConfigManager().putSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE);
|
||||
var saved = new net.minecraft.nbt.CompoundTag();
|
||||
bus.writeToNBT(saved, level.registryAccess());
|
||||
var stock = buffer.thE$getTransferBuffer();
|
||||
buffer.thE$setTransferBuffer(AspectStack.EMPTY);
|
||||
bus.readFromNBT(saved, level.registryAccess());
|
||||
helper.assertTrue(buffer.thE$getTransferBuffer().equals(stock), "Owned stock must survive bus reload");
|
||||
bus.getConfig().setStack(0, null);
|
||||
helper.assertTrue(!endpoint.canOutputTo(Direction.UP), "Removing filter must immediately block pulls");
|
||||
var host = (CableBusBlockEntity) helper.getBlockEntity(cablePos);
|
||||
host.removePartFromSide(Direction.UP);
|
||||
helper.assertTrue(!endpoint.canOutputTo(Direction.UP), "Cached endpoint must not outlive its bus");
|
||||
helper.succeed();
|
||||
});
|
||||
}
|
||||
|
||||
private static net.minecraft.world.level.block.Block block(String id) {
|
||||
return BuiltInRegistries.BLOCK.get(ResourceLocation.fromNamespaceAndPath("thaumcraft", id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package thaumicenergistics.tests;
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.neoforge.gametest.GameTestHolder;
|
||||
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.stacks.AEKey;
|
||||
import appeng.api.stacks.KeyCounter;
|
||||
import appeng.api.storage.MEStorage;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import thaumicenergistics.common.container.EssentiaFillHelper;
|
||||
import thaumicenergistics.common.integration.tc.ArcaneCraftingPattern;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaItemContainers;
|
||||
import thaumicenergistics.common.integration.tc.TCReflection;
|
||||
import thaumicenergistics.common.tiles.TileArcaneAssembler;
|
||||
import thaumicenergistics.common.integration.appeng.EssentiaContainerItemStrategy;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
|
||||
/** 只在隔离验收运行中加载,不进入发布 JAR。 */
|
||||
@Mod("thaumicenergistics_tests")
|
||||
@GameTestHolder("thaumicenergistics_tests")
|
||||
@PrefixGameTestTemplate(false)
|
||||
public final class RegressionTests {
|
||||
@GameTest(template = "empty")
|
||||
public static void jarsSupportEveryBusFace(GameTestHelper helper) {
|
||||
EssentiaBusChecks.jarsFromEveryFace(helper);
|
||||
}
|
||||
|
||||
@GameTest(template = "empty", timeoutTicks = 200)
|
||||
public static void exportBusSuppliesFertilityLamp(GameTestHelper helper) {
|
||||
EssentiaBusChecks.fertilityLampPullsFromExportBus(helper);
|
||||
}
|
||||
|
||||
public RegressionTests(net.neoforged.bus.api.IEventBus bus) {
|
||||
WirelessChargingChecks.register(bus);
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void partialDepositConservesEssentia(GameTestHelper helper) {
|
||||
var original = new ItemStack(BuiltInRegistries.ITEM.get(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", "glass_phial")));
|
||||
var filled = EssentiaItemContainers.withContents(original, new AspectList().add(Aspect.AIR, 8));
|
||||
helper.assertTrue(filled != null, "Generic phial must retain arbitrary essentia amounts");
|
||||
var player = helper.makeMockPlayer(GameType.SURVIVAL);
|
||||
long[] stored = {0};
|
||||
MEStorage storage = new MEStorage() {
|
||||
@Override public Component getDescription() { return Component.literal("partial test storage"); }
|
||||
@Override public long insert(AEKey key, long amount, Actionable mode, IActionSource source) {
|
||||
long accepted = Math.min(amount, 3 - stored[0]);
|
||||
if (mode == Actionable.MODULATE) stored[0] += accepted;
|
||||
return accepted;
|
||||
}
|
||||
};
|
||||
var remainder = EssentiaFillHelper.depositContainerContent(storage,
|
||||
(amount, mode, multiplier) -> amount, IActionSource.ofPlayer(player), player, filled);
|
||||
helper.assertTrue(stored[0] == 3, "Only actual acceptance reaches the network");
|
||||
helper.assertTrue(EssentiaItemContainers.contents(remainder).getAmount(Aspect.AIR) == 5,
|
||||
"Five unaccepted essentia must remain in the physical phial");
|
||||
helper.assertTrue(EssentiaItemContainers.contents(filled).getAmount(Aspect.AIR) == 8,
|
||||
"Building a replacement must not mutate the source component");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void recoveredDropsRemainUsable(GameTestHelper helper) {
|
||||
var key = AEssentiaKey.of(TCReflection.getAspectId(Aspect.AIR));
|
||||
var drops = new java.util.ArrayList<ItemStack>();
|
||||
key.addDrops(123, drops, helper.getLevel(), helper.absolutePos(net.minecraft.core.BlockPos.ZERO));
|
||||
helper.assertTrue(drops.size() == 1, "Essentia needs a recoverable physical drop");
|
||||
var player = helper.makeMockPlayer(GameType.SURVIVAL);
|
||||
player.getInventory().setItem(0, drops.getFirst());
|
||||
var strategy = new EssentiaContainerItemStrategy();
|
||||
var context = strategy.findPlayerSlotContext(player, 0);
|
||||
helper.assertTrue(context != null, "Recovery drops must have an extraction context");
|
||||
helper.assertTrue(strategy.extract(context, key, 23, Actionable.SIMULATE) == 23, "Simulation quantity");
|
||||
helper.assertTrue(strategy.getExtractableContent(context).amount() == 123, "Simulation cannot consume drops");
|
||||
helper.assertTrue(strategy.extract(context, key, 23, Actionable.MODULATE) == 23, "Actual recovery quantity");
|
||||
helper.assertTrue(strategy.getExtractableContent(context).amount() == 100, "Unrecovered resources survive");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void patternIdentityAndActualInputs(GameTestHelper helper) {
|
||||
ItemStack[] first = new ItemStack[9];
|
||||
java.util.Arrays.fill(first, ItemStack.EMPTY);
|
||||
first[0] = new ItemStack(Items.STONE);
|
||||
var aspects = new AspectList().add(Aspect.AIR, 1);
|
||||
var pattern = TileArcaneAssembler.buildArcanePattern(
|
||||
new ArcaneCraftingPattern(aspects, new ItemStack(Items.DIAMOND), first));
|
||||
ItemStack[] second = first.clone();
|
||||
second[0] = new ItemStack(Items.DIRT);
|
||||
var other = TileArcaneAssembler.buildArcanePattern(
|
||||
new ArcaneCraftingPattern(aspects, new ItemStack(Items.DIAMOND), second));
|
||||
helper.assertFalse(pattern.equals(other), "Same output with different inputs is a different pattern");
|
||||
var holder = new KeyCounter();
|
||||
holder.add(appeng.api.stacks.AEItemKey.of(Items.STONE), 1);
|
||||
helper.assertTrue(pattern.materializeInputs(new KeyCounter[]{holder}, helper.getLevel()) != null,
|
||||
"Real matching input should be accepted");
|
||||
helper.assertTrue(holder.get(appeng.api.stacks.AEItemKey.of(Items.STONE)) == 1,
|
||||
"Preflight must not consume CPU inputs");
|
||||
holder.add(appeng.api.stacks.AEItemKey.of(Items.DIRT), 1);
|
||||
helper.assertTrue(pattern.materializeInputs(new KeyCounter[]{holder}, helper.getLevel()) == null,
|
||||
"Extra or mismatched materials must not be silently consumed");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void pendingCraftSurvivesReload(GameTestHelper helper) {
|
||||
var pos = new net.minecraft.core.BlockPos(1, 1, 1);
|
||||
helper.setBlock(pos, thaumicenergistics.init.ModBlocks.ARCANE_ASSEMBLER.get());
|
||||
TileArcaneAssembler tile = helper.getBlockEntity(pos);
|
||||
var registries = helper.getLevel().registryAccess();
|
||||
var saved = tile.saveWithFullMetadata(registries);
|
||||
saved.putBoolean("IsCrafting", true);
|
||||
saved.putInt("CraftTick", 20);
|
||||
saved.putBoolean("ResultProduced", true);
|
||||
saved.put("CurrentCraftResult", new ItemStack(Items.DIAMOND, 4).save(registries));
|
||||
var outputs = new net.minecraft.nbt.ListTag();
|
||||
outputs.add(new ItemStack(Items.DIAMOND, 2).save(registries));
|
||||
saved.put("PendingCraftOutputs", outputs);
|
||||
var aspects = new net.minecraft.nbt.CompoundTag();
|
||||
new AspectList().add(Aspect.AIR, 3).writeToNBT(aspects);
|
||||
saved.put("CurrentCraftAspects", aspects);
|
||||
var stored = new net.minecraft.nbt.CompoundTag();
|
||||
stored.putInt(Aspect.AIR.getTag(), 17);
|
||||
saved.put("StoredVis", stored);
|
||||
tile.loadWithComponents(saved, registries);
|
||||
var restored = tile.saveWithFullMetadata(registries);
|
||||
helper.assertTrue(tile.isCrafting(), "Pending output must remain busy across reload");
|
||||
helper.assertTrue(restored.getBoolean("ResultProduced"), "Completion phase must survive reload");
|
||||
helper.assertTrue(ItemStack.parseOptional(registries,
|
||||
restored.getList("PendingCraftOutputs", net.minecraft.nbt.Tag.TAG_COMPOUND).getCompound(0)).getCount() == 2,
|
||||
"Only the unaccepted part of output may be retried");
|
||||
helper.assertTrue(tile.getStoredVis().getAmount(Aspect.AIR) == 17, "Reload must not charge vis again");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void encodedWispAspectSurvivesPlanning(GameTestHelper helper) {
|
||||
ItemStack essence = new ItemStack(BuiltInRegistries.ITEM.get(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", "wisp_essence")));
|
||||
helper.assertTrue(essence.getItem() instanceof thaumcraft.api.aspects.IEssentiaContainerItem,
|
||||
"Generic wisp essence must expose its aspect component");
|
||||
((thaumcraft.api.aspects.IEssentiaContainerItem) essence.getItem()).setAspects(
|
||||
essence, new AspectList().add(Aspect.AIR, 2));
|
||||
helper.assertFalse(essence.getComponentsPatch().isEmpty(), "Aspect must be encoded on the item");
|
||||
ItemStack[] grid = new ItemStack[9];
|
||||
java.util.Arrays.fill(grid, ItemStack.EMPTY);
|
||||
grid[0] = essence;
|
||||
var encoded = new ArcaneCraftingPattern(new AspectList().add(Aspect.AIR, 1),
|
||||
new ItemStack(Items.DIAMOND), grid);
|
||||
var restored = new ArcaneCraftingPattern(encoded.writeToNBT(new net.minecraft.nbt.CompoundTag()));
|
||||
var input = TileArcaneAssembler.buildArcanePattern(restored).getInputs()[0];
|
||||
var expected = appeng.api.stacks.AEItemKey.of(essence);
|
||||
helper.assertTrue(input.getPossibleInputs().length == 1,
|
||||
"Explicit aspect components must not be replaced by bare tag variants");
|
||||
helper.assertTrue(input.getPossibleInputs()[0].what().equals(expected),
|
||||
"The crafting plan must show the encoded aspect after serialization");
|
||||
helper.assertFalse(input.isValid(appeng.api.stacks.AEItemKey.of(essence.getItem()), helper.getLevel()),
|
||||
"Unknown-aspect essence must not satisfy the encoded aspect");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void selectedWispVariantIsPrimary(GameTestHelper helper) {
|
||||
ItemStack essence = new ItemStack(BuiltInRegistries.ITEM.get(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", "wisp_essence_ordo")));
|
||||
helper.assertFalse(essence.isEmpty(), "Selected wisp variant must exist");
|
||||
ItemStack[] grid = new ItemStack[9];
|
||||
java.util.Arrays.fill(grid, ItemStack.EMPTY);
|
||||
grid[0] = essence;
|
||||
var pattern = TileArcaneAssembler.buildArcanePattern(new ArcaneCraftingPattern(
|
||||
new AspectList().add(Aspect.AIR, 1), new ItemStack(Items.DIAMOND), grid));
|
||||
var inputs = pattern.getInputs()[0].getPossibleInputs();
|
||||
helper.assertTrue(inputs[0].what().equals(appeng.api.stacks.AEItemKey.of(essence)),
|
||||
"The selected variant, not the first tag member, must be the primary input");
|
||||
var unknown = appeng.api.stacks.AEItemKey.of(BuiltInRegistries.ITEM.get(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", "wisp_essence")));
|
||||
for (var input : inputs) {
|
||||
helper.assertFalse(input.what().equals(unknown), "Bare unknown-aspect essence is not a substitute");
|
||||
}
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void optionalWirelessMerge(GameTestHelper helper) {
|
||||
if (net.neoforged.fml.ModList.get().isLoaded("ae2wtlib")) WirelessMergeChecks.run(helper);
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void closedWirelessTerminalChargesWand(GameTestHelper helper) {
|
||||
WirelessChargingChecks.run(helper);
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void emptyWirelessTerminalsSurvivePlayerTick(GameTestHelper helper) {
|
||||
WirelessChargingChecks.emptyTerminals(helper);
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void probabilityBrainUsesContinuousPower(GameTestHelper helper) {
|
||||
helper.setBlock(net.minecraft.core.BlockPos.ZERO, thaumicenergistics.init.ModBlocks.BRAIN_OF_PROBABILITY.get());
|
||||
helper.runAfterDelay(2, () -> {
|
||||
var brain = (thaumicenergistics.common.tiles.BrainOfProbabilityBlockEntity)
|
||||
helper.getBlockEntity(net.minecraft.core.BlockPos.ZERO);
|
||||
var node = brain.getActionableNode();
|
||||
helper.assertTrue(node != null && node.getIdlePowerUsage() == 50.0,
|
||||
"The real grid node must advertise 50 AE per tick");
|
||||
helper.succeed();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package thaumicenergistics.tests;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.List;
|
||||
import appeng.api.networking.IGrid;
|
||||
import appeng.api.networking.IGridNode;
|
||||
import appeng.api.storage.ILinkStatus;
|
||||
import appeng.api.upgrades.Upgrades;
|
||||
import appeng.helpers.WirelessTerminalMenuHost;
|
||||
import appeng.menu.locator.ItemMenuHostLocator;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.ItemContainerContents;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.neoforged.neoforge.event.tick.PlayerTickEvent;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.common.items.TCFunctionalItems;
|
||||
import thaumicenergistics.common.items.WirelessArcaneCraftingTerminalItem;
|
||||
import thaumicenergistics.common.items.WirelessArcaneCraftingTerminalMenuHost;
|
||||
import thaumicenergistics.common.parts.VisInterfacePart;
|
||||
import thaumicenergistics.common.parts.WirelessArcaneChargingHandler;
|
||||
import thaumicenergistics.init.ModComponents;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/** 隔离无线链路之外的世界搭建,验证真实玩家 tick、法杖组件及卡片门控。 */
|
||||
final class WirelessChargingChecks {
|
||||
private static final net.neoforged.neoforge.registries.DeferredRegister.Items ITEMS =
|
||||
net.neoforged.neoforge.registries.DeferredRegister.createItems("thaumicenergistics_tests");
|
||||
private static final net.neoforged.neoforge.registries.DeferredItem<TestTerminal> TERMINAL =
|
||||
ITEMS.registerItem("charging_fixture", TestTerminal::new);
|
||||
private static IGridNode chargingNode;
|
||||
private static boolean connected;
|
||||
|
||||
static void register(net.neoforged.bus.api.IEventBus bus) { ITEMS.register(bus); }
|
||||
|
||||
static void emptyTerminals(GameTestHelper helper) {
|
||||
var player = new net.minecraft.server.level.ServerPlayer(helper.getLevel().getServer(), helper.getLevel(),
|
||||
new com.mojang.authlib.GameProfile(java.util.UUID.randomUUID(), "EmptyTerminalTest"),
|
||||
net.minecraft.server.level.ClientInformation.createDefault());
|
||||
var item = TERMINAL.get();
|
||||
Upgrades.add(ModItems.VIS_CONNECTOR_CARD.get(), item, 1);
|
||||
// Vanilla AE2 terminals also pass through the background charging handler.
|
||||
player.getInventory().setItem(1, appeng.core.definitions.AEItems.WIRELESS_TERMINAL.stack());
|
||||
player.getInventory().setItem(2, appeng.core.definitions.AEItems.WIRELESS_CRAFTING_TERMINAL.stack());
|
||||
for (boolean withCard : new boolean[]{false, true}) {
|
||||
var terminal = new ItemStack(item);
|
||||
if (withCard) item.getUpgrades(terminal).addItems(new ItemStack(ModItems.VIS_CONNECTOR_CARD.get()));
|
||||
player.getInventory().setItem(0, terminal);
|
||||
WirelessArcaneChargingHandler.onPlayerTick(new PlayerTickEvent.Post(player));
|
||||
helper.assertTrue(!terminal.has(ModComponents.WAND_INV.get()),
|
||||
"A missing wand component must be skipped without changing the item");
|
||||
terminal.set(ModComponents.WAND_INV.get(), ItemContainerContents.EMPTY);
|
||||
WirelessArcaneChargingHandler.onPlayerTick(new PlayerTickEvent.Post(player));
|
||||
// Removing the last wand trims the serialized component to zero slots.
|
||||
terminal.set(ModComponents.WAND_INV.get(), ItemContainerContents.fromItems(List.of(ItemStack.EMPTY)));
|
||||
var restored = ItemStack.parse(helper.getLevel().registryAccess(),
|
||||
terminal.save(helper.getLevel().registryAccess())).orElseThrow();
|
||||
player.getInventory().setItem(0, restored);
|
||||
WirelessArcaneChargingHandler.onPlayerTick(new PlayerTickEvent.Post(player));
|
||||
helper.assertTrue(restored.getOrDefault(ModComponents.WAND_INV.get(), ItemContainerContents.EMPTY)
|
||||
.equals(ItemContainerContents.EMPTY), "An empty wand component must survive reload and tick");
|
||||
}
|
||||
player.discard();
|
||||
}
|
||||
|
||||
private static class TestTerminal extends WirelessArcaneCraftingTerminalItem {
|
||||
TestTerminal(Item.Properties properties) { super(() -> 10000, properties); }
|
||||
|
||||
@Override
|
||||
public WirelessTerminalMenuHost<?> getMenuHost(Player holder, ItemMenuHostLocator locator, BlockHitResult hit) {
|
||||
return new WirelessArcaneCraftingTerminalMenuHost(this, holder, locator, (p, menu) -> { }) {
|
||||
@Override public IGridNode getActionableNode() { return chargingNode; }
|
||||
@Override public ILinkStatus getLinkStatus() {
|
||||
return connected ? ILinkStatus.ofConnected() : ILinkStatus.ofDisconnected();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
static void run(GameTestHelper helper) {
|
||||
// 不触发登录同步;无协议握手的 GameTest 客户端无法接收 TC 研究数据负载。
|
||||
var player = new net.minecraft.server.level.ServerPlayer(helper.getLevel().getServer(), helper.getLevel(),
|
||||
new com.mojang.authlib.GameProfile(java.util.UUID.randomUUID(), "WirelessChargeTest"),
|
||||
net.minecraft.server.level.ClientInformation.createDefault());
|
||||
connected = true;
|
||||
var source = new VisInterfacePart(ModItems.VIS_INTERFACE.get()) {
|
||||
@Override
|
||||
public int consumeVis(net.minecraft.resources.ResourceLocation aspect, int amount) {
|
||||
return amount;
|
||||
}
|
||||
};
|
||||
var grid = (IGrid) Proxy.newProxyInstance(IGrid.class.getClassLoader(), new Class<?>[]{IGrid.class},
|
||||
(proxy, method, arguments) -> {
|
||||
if (method.getName().equals("getMachines")) return java.util.Set.of(source);
|
||||
throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
var node = (IGridNode) Proxy.newProxyInstance(IGridNode.class.getClassLoader(), new Class<?>[]{IGridNode.class},
|
||||
(proxy, method, arguments) -> switch (method.getName()) {
|
||||
case "getGrid" -> grid;
|
||||
case "isActive" -> true;
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
chargingNode = node;
|
||||
var terminalItem = TERMINAL.get();
|
||||
Upgrades.add(ModItems.VIS_CONNECTOR_CARD.get(), terminalItem, 1);
|
||||
var terminal = new ItemStack(terminalItem);
|
||||
var wandItem = BuiltInRegistries.ITEM.stream()
|
||||
.filter(item -> item instanceof TCFunctionalItems.WandCastingItem).findFirst().orElseThrow();
|
||||
var wand = new ItemStack(wandItem);
|
||||
var casting = (TCFunctionalItems.WandCastingItem) wandItem;
|
||||
terminal.set(ModComponents.WAND_INV.get(), ItemContainerContents.fromItems(List.of(wand)));
|
||||
player.getInventory().setItem(0, terminal);
|
||||
// 不打开终端菜单,验证后台 tick 对保存的法杖组件生效。
|
||||
WirelessArcaneChargingHandler.onPlayerTick(new PlayerTickEvent.Post(player));
|
||||
helper.assertTrue(vis(terminal, casting) == 0, "No Vis card must mean no passive charge");
|
||||
helper.assertTrue(terminalItem.getUpgrades(terminal).addItems(new ItemStack(ModItems.VIS_CONNECTOR_CARD.get())).isEmpty(),
|
||||
"Vis card must install");
|
||||
WirelessArcaneChargingHandler.onPlayerTick(new PlayerTickEvent.Post(player));
|
||||
helper.assertTrue(vis(terminal, casting) == 5, "Closed terminal charges and persists five centivis per aspect");
|
||||
connected = false;
|
||||
WirelessArcaneChargingHandler.onPlayerTick(new PlayerTickEvent.Post(player));
|
||||
helper.assertTrue(vis(terminal, casting) == 5, "Disconnected terminal must stop passive charging");
|
||||
player.getInventory().setItem(0, ItemStack.EMPTY);
|
||||
player.discard();
|
||||
chargingNode = null;
|
||||
}
|
||||
|
||||
private static int vis(ItemStack terminal, TCFunctionalItems.WandCastingItem casting) {
|
||||
return casting.getVis(terminal.get(ModComponents.WAND_INV.get()).getStackInSlot(0), Aspect.AIR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package thaumicenergistics.tests;
|
||||
|
||||
import java.util.List;
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.ids.AEComponents;
|
||||
import de.mari_023.ae2wtlib.api.AE2wtlibAPI;
|
||||
import de.mari_023.ae2wtlib.api.registration.WTDefinition;
|
||||
import de.mari_023.ae2wtlib.api.terminal.ItemWT;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.component.ItemContainerContents;
|
||||
import thaumicenergistics.common.integration.ae2wt.SafeTerminalMerge;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
import thaumicenergistics.init.ModComponents;
|
||||
|
||||
/** 可选 API 测试与通用测试类隔离,缺席时不解析其类型。 */
|
||||
final class WirelessMergeChecks {
|
||||
static void run(GameTestHelper helper) {
|
||||
var arcane = new ItemStack(ModItems.WIRELESS_ARCANE_CRAFTING_TERMINAL.get());
|
||||
var crafting = new ItemStack(appeng.core.definitions.AEItems.WIRELESS_CRAFTING_TERMINAL.asItem());
|
||||
helper.assertTrue(crafting.getItem() instanceof ItemWT, "Pinned AE2WT crafting terminal must exist");
|
||||
arcane.set(ModComponents.WAND_INV.get(), ItemContainerContents.fromItems(List.of(new ItemStack(Items.STICK))));
|
||||
arcane.set(AEComponents.CRAFTING_INV, ItemContainerContents.fromItems(List.of(new ItemStack(Items.STONE, 3))));
|
||||
((ItemWT) arcane.getItem()).injectAEPower(arcane, 100, Actionable.MODULATE);
|
||||
((ItemWT) crafting.getItem()).injectAEPower(crafting, 200, Actionable.MODULATE);
|
||||
var merged = SafeTerminalMerge.merge(arcane, crafting, "crafting");
|
||||
helper.assertFalse(merged.isEmpty(), "Normal arcane + crafting merge must remain craftable");
|
||||
helper.assertTrue(AE2wtlibAPI.isUniversalTerminal(merged), "Merge result must be a universal terminal");
|
||||
helper.assertTrue(merged.has(WTDefinition.of(arcane).componentType()), "Arcane mode flag must be preserved");
|
||||
helper.assertTrue(((ItemWT) merged.getItem()).getAECurrentPower(merged) == 300, "Both batteries migrate");
|
||||
helper.assertTrue(merged.get(ModComponents.WAND_INV.get()).getStackInSlot(0).is(Items.STICK), "Wand inventory migrates");
|
||||
helper.assertTrue(merged.get(AEComponents.CRAFTING_INV).getStackInSlot(0).getCount() == 3, "Crafting materials migrate");
|
||||
helper.assertTrue(SafeTerminalMerge.merge(arcane, merged, "").isEmpty(), "Duplicate arcane mode must be rejected");
|
||||
helper.assertTrue(((ItemWT) arcane.getItem()).getAECurrentPower(arcane) == 100, "Recipe preview cannot debit input battery");
|
||||
var player = new net.minecraft.server.level.ServerPlayer(helper.getLevel().getServer(), helper.getLevel(),
|
||||
new com.mojang.authlib.GameProfile(java.util.UUID.randomUUID(), "UniversalChargeTest"),
|
||||
net.minecraft.server.level.ClientInformation.createDefault());
|
||||
var craftingMode = WTDefinition.of(crafting);
|
||||
merged.set(de.mari_023.ae2wtlib.api.AE2wtlibComponents.CURRENT_TERMINAL, craftingMode);
|
||||
player.getInventory().setItem(0, merged);
|
||||
var passiveHost = thaumicenergistics.common.integration.ae2wt.AE2WTCompat.createPassiveArcaneHost(
|
||||
player, appeng.menu.locator.MenuLocators.forInventorySlot(0));
|
||||
helper.assertTrue(passiveHost instanceof thaumicenergistics.common.container.IArcaneTerminalInventoryHost,
|
||||
"Universal terminal in crafting mode must expose its passive arcane inventory");
|
||||
helper.assertTrue(merged.get(de.mari_023.ae2wtlib.api.AE2wtlibComponents.CURRENT_TERMINAL) == craftingMode,
|
||||
"Passive arcane host creation must not change the selected terminal");
|
||||
helper.assertTrue(merged.get(ModComponents.WAND_INV.get()).getStackInSlot(0).is(Items.STICK),
|
||||
"Passive host must preserve the saved wand");
|
||||
player.getInventory().setItem(0, ItemStack.EMPTY);
|
||||
player.discard();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
modLoader="javafml"
|
||||
loaderVersion="[4,)"
|
||||
license="MIT"
|
||||
[[mods]]
|
||||
modId="thaumicenergistics_tests"
|
||||
version="1.0"
|
||||
displayName="ThaumicEnergistics regression tests"
|
||||
[[dependencies.thaumicenergistics_tests]]
|
||||
modId="thaumicenergistics"
|
||||
type="required"
|
||||
versionRange="*"
|
||||
ordering="AFTER"
|
||||
side="BOTH"
|
||||
Binary file not shown.
@@ -28,7 +28,10 @@ import org.slf4j.LoggerFactory;
|
||||
import thaumicenergistics.common.container.*;
|
||||
import thaumicenergistics.common.features.RecipeRegistration;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKeyType;
|
||||
import thaumicenergistics.common.integration.appeng.ThEAppliedEnergistics;
|
||||
import thaumicenergistics.common.integration.ae2wt.AE2WTCompat;
|
||||
import thaumicenergistics.common.integration.ae2lt.AE2LTCompat;
|
||||
import thaumicenergistics.common.integration.advancedae.AdvancedAECompat;
|
||||
import thaumicenergistics.common.integration.extendedae.ThEExtendedAE;
|
||||
import thaumicenergistics.common.integration.tc.ThEThaumcraft;
|
||||
import thaumicenergistics.common.items.ItemGolemWirelessBackpack;
|
||||
import thaumicenergistics.common.items.WirelessArcaneCraftingTerminalMenuHost;
|
||||
@@ -61,6 +64,7 @@ public final class ThaumicEnergistics {
|
||||
ModMenuTypes.REGISTRY.register(modBus);
|
||||
ModCreativeTab.REGISTRY.register(modBus);
|
||||
ModComponents.REGISTRY.register(modBus);
|
||||
ModRecipeSerializers.REGISTRY.register(modBus);
|
||||
modBus.addListener(this::registerScreens);
|
||||
modBus.addListener(this::commonSetup);
|
||||
modBus.addListener(this::registerKeyTypes);
|
||||
@@ -69,7 +73,13 @@ public final class ThaumicEnergistics {
|
||||
if (FMLLoader.getDist().isClient()) {
|
||||
modBus.addListener(ClientInit::onClientSetup);
|
||||
}
|
||||
ThEAppliedEnergistics.init();
|
||||
|
||||
// COMPAT-PLAN:AE2WT 通用终端奥术功能注册——必须在此(模组构造阶段)登记,
|
||||
// AddTerminalEvent 的一次性回调在 RegisterEvent(ITEM) 由 API 统一执行;
|
||||
// ae2wtlib 缺席时兼容类不加载,独立无线奥术终端照常运行。
|
||||
if (ModList.get().isLoaded("ae2wtlib")) {
|
||||
AE2WTCompat.registerArcaneTerminal();
|
||||
}
|
||||
|
||||
GridServices.register(
|
||||
IEssentiaGrid.class,
|
||||
@@ -108,6 +118,11 @@ public final class ThaumicEnergistics {
|
||||
|
||||
event.enqueueWork(() -> {
|
||||
RecipeRegistration.registerAll();
|
||||
appeng.api.crafting.PatternDetailsHelper.registerDecoder(
|
||||
new thaumicenergistics.common.crafting.ArcanePatternDecoder());
|
||||
appeng.api.behaviors.ContainerItemStrategy.register(AEssentiaKeyType.INSTANCE,
|
||||
thaumicenergistics.common.integration.appeng.AEssentiaKey.class,
|
||||
new thaumicenergistics.common.integration.appeng.EssentiaContainerItemStrategy());
|
||||
ThEThaumcraft.init();
|
||||
P2PTunnelAttunement.registerAttunementTag(ModItems.VIS_INTERFACE.get());
|
||||
GridLinkables.register(ModItems.GOLEM_WIFI_BACKPACK.get(), ItemGolemWirelessBackpack.LINKABLE_HANDLER);
|
||||
@@ -148,13 +163,19 @@ public final class ThaumicEnergistics {
|
||||
Upgrades.add(essentiaCard, AEParts.PATTERN_PROVIDER, 1, patternProviderGroup);
|
||||
Upgrades.add(essentiaCard, AEBlocks.PATTERN_PROVIDER, 1, patternProviderGroup);
|
||||
|
||||
// T-M3-VISCARD-REV:vis 连接卡(升级卡)仅关联无线奥术合成终端——
|
||||
// 允许插入其升级槽(2 槽,AE2 无线终端白送),并在 tooltip「Supported By」行显示宿主。
|
||||
// EAE-COMPAT:Extended AE 扩展样板供应器/超大接口准入(可选软依赖)——
|
||||
// 两类宿主复用 AE2 PatternProviderLogic / InterfaceLogic,本项目的卡槽与源质
|
||||
// Mixin 对其自动生效,此处只补 Upgrades.add 准入;缺席时整体跳过。
|
||||
ThEExtendedAE.registerEssentiaUpgrades();
|
||||
// COMPAT-PLAN:AdvancedAE / AE2 Lightning Tech 源质访问卡准入(可选软依赖,
|
||||
// ID 软查注册;其独立逻辑层的卡槽与源质 Mixin 由各自兼容配置另行挂载)。
|
||||
AdvancedAECompat.registerEssentiaUpgrades();
|
||||
AE2LTCompat.registerEssentiaUpgrades();
|
||||
|
||||
// 独立终端的 vis 卡准入;AE2WT 体系另由 UpgradeHelper 注册所有终端。
|
||||
Upgrades.add(ModItems.VIS_CONNECTOR_CARD.get(), ModItems.WIRELESS_ARCANE_CRAFTING_TERMINAL.get(), 1);
|
||||
|
||||
// WTBRIDGE:量子桥卡准入适配(软依赖)——ae2wtlib 的 UpgradeHelper 只对注册进其
|
||||
// AddTerminalEvent 体系的终端映射卡表,我方 WACT 未注册(ItemWT 类层级硬绑死、单继承无解),
|
||||
// 故自行补一条 Upgrades.add 映射放行插入(AE2 升级槽准入 = Upgrades.getMaxInstallable)。
|
||||
// 保留桥卡显式准入,与 AE2WT 全终端注册使用相同上限,兼容历史独立宿主。
|
||||
if (ModList.get().isLoaded(WirelessArcaneCraftingTerminalMenuHost.AE2WTLIB_MODID)) {
|
||||
var bridgeCard = BuiltInRegistries.ITEM
|
||||
.getOptional(WirelessArcaneCraftingTerminalMenuHost.AE2WTLIB_QUANTUM_BRIDGE_CARD).orElse(null);
|
||||
@@ -181,11 +202,15 @@ public final class ThaumicEnergistics {
|
||||
-> new GuiArcaneCraftingTerminal(menu, inv, title,
|
||||
StyleManager.loadStyleDoc("/screens/arcane_crafting_terminal.json")));
|
||||
|
||||
// 无线奥术合成终端:复用同一屏幕类与样式(共用菜单类)
|
||||
// AE2WT 宿主使用可切换的屏幕;独立终端保持原屏幕。
|
||||
if (ModList.get().isLoaded("ae2wtlib")) {
|
||||
thaumicenergistics.client.integration.ae2wt.AE2WTClientCompat.registerScreen(event);
|
||||
} else {
|
||||
event.register(ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL.get(),
|
||||
(ContainerArcaneCraftingTerminal menu, Inventory inv, Component title)
|
||||
-> new GuiArcaneCraftingTerminal(menu, inv, title,
|
||||
StyleManager.loadStyleDoc("/screens/arcane_crafting_terminal.json")));
|
||||
}
|
||||
|
||||
event.register(ModMenuTypes.ESSENTIA_LEVEL_EMITTER.get(),
|
||||
(ContainerEssentiaLevelEmitter menu, Inventory inv, Component title)
|
||||
@@ -202,6 +227,11 @@ public final class ThaumicEnergistics {
|
||||
}
|
||||
|
||||
private void registerCapabilities(RegisterCapabilitiesEvent event) {
|
||||
event.registerBlockEntity(
|
||||
thaumcraft.api.aspects.EssentiaCapabilities.TRANSPORT,
|
||||
appeng.core.definitions.AEBlockEntities.CABLE_BUS.get(),
|
||||
(be, side) -> side == null || !(be.getPart(side) instanceof appeng.parts.automation.ExportBusPart) ? null
|
||||
: new thaumicenergistics.common.essentia.capability.ExportBusEssentiaTransport(be, side));
|
||||
LOG.info("Registering AE2 grid node capabilities...");
|
||||
event.registerBlockEntity(
|
||||
AECapabilities.IN_WORLD_GRID_NODE_HOST,
|
||||
|
||||
@@ -10,6 +10,7 @@ public final class ClientInit {
|
||||
private ClientInit() {}
|
||||
|
||||
public static void onClientSetup(FMLClientSetupEvent event) {
|
||||
net.neoforged.neoforge.common.NeoForge.EVENT_BUS.register(EssentiaTerminalInputHandler.class);
|
||||
event.enqueueWork(() -> {
|
||||
AEKeyRendering.register(
|
||||
AEssentiaKeyType.INSTANCE,
|
||||
|
||||
@@ -1,36 +1,28 @@
|
||||
package thaumicenergistics.client;
|
||||
|
||||
import net.minecraft.client.model.geom.EntityModelSet;
|
||||
import net.minecraft.client.renderer.entity.EntityRenderer;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.fml.common.EventBusSubscriber;
|
||||
import net.neoforged.neoforge.client.event.EntityRenderersEvent;
|
||||
import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent;
|
||||
import net.minecraft.server.packs.resources.ResourceManagerReloadListener;
|
||||
import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent;
|
||||
import thaumcraft.client.renderers.entity.ThaumcraftGolemRenderer;
|
||||
import thaumcraft.common.registry.TCEntityTypes;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.client.render.layer.GolemBackpackLayer;
|
||||
import thaumicenergistics.client.render.model.GolemBackpackModel;
|
||||
import thaumicenergistics.client.render.model.GolemBackpackModels;
|
||||
import thaumicenergistics.client.render.RenderTileArcaneAssembler;
|
||||
import thaumicenergistics.client.render.RenderTileBrainOfProbability;
|
||||
import thaumicenergistics.client.render.RenderTileEVC;
|
||||
import thaumicenergistics.init.ModBlockEntities;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
import net.minecraft.client.model.geom.ModelLayerLocation;
|
||||
import net.minecraft.client.model.geom.ModelPart;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/** 客户端渲染注册的事件处理器。 */
|
||||
@EventBusSubscriber(modid = ThaumicEnergistics.MODID, value = Dist.CLIENT)
|
||||
public final class ClientSetup {
|
||||
|
||||
/** 背包模型的 LayerDefinition 注册 key */
|
||||
public static final ModelLayerLocation GOLEM_BACKPACK_LAYER =
|
||||
new ModelLayerLocation(
|
||||
ResourceLocation.fromNamespaceAndPath(ThaumicEnergistics.MODID, "golem_backpack"),
|
||||
"main");
|
||||
|
||||
@SubscribeEvent
|
||||
public static void registerBER(EntityRenderersEvent.RegisterRenderers event) {
|
||||
event.registerBlockEntityRenderer(ModBlockEntities.ARCANE_ASSEMBLER.get(), RenderTileArcaneAssembler::new);
|
||||
@@ -38,9 +30,10 @@ public final class ClientSetup {
|
||||
event.registerBlockEntityRenderer(ModBlockEntities.BRAIN_OF_PROBABILITY.get(), RenderTileBrainOfProbability::new);
|
||||
}
|
||||
|
||||
/** Reload the CE per-face model without baking it into the block texture atlas. */
|
||||
@SubscribeEvent
|
||||
public static void registerLayerDefinitions(EntityRenderersEvent.RegisterLayerDefinitions event) {
|
||||
event.registerLayerDefinition(GOLEM_BACKPACK_LAYER, GolemBackpackModel::createBodyLayer);
|
||||
public static void registerBackpackReloadListener(RegisterClientReloadListenersEvent event) {
|
||||
event.registerReloadListener((ResourceManagerReloadListener) GolemBackpackModels::reload);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
@@ -48,10 +41,7 @@ public final class ClientSetup {
|
||||
// 给 Thaumcraft 的傀儡渲染器添加背包渲染层
|
||||
EntityRenderer<?> renderer = event.getRenderer(TCEntityTypes.GOLEM.get());
|
||||
if (renderer instanceof ThaumcraftGolemRenderer golemRenderer) {
|
||||
EntityModelSet modelSet = event.getEntityModels();
|
||||
ModelPart backpackPart = modelSet.bakeLayer(GOLEM_BACKPACK_LAYER);
|
||||
GolemBackpackModel backpackModel = new GolemBackpackModel(backpackPart);
|
||||
golemRenderer.addLayer(new GolemBackpackLayer(golemRenderer, backpackModel));
|
||||
golemRenderer.addLayer(new GolemBackpackLayer(golemRenderer));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.texture.OverlayTexture;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.level.Level;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
@@ -31,6 +33,33 @@ public class EssentiaKeyRenderHandler implements AEKeyRenderHandler<AEssentiaKey
|
||||
@Override
|
||||
public void drawOnBlockFace(PoseStack poseStack, MultiBufferSource buffers, AEssentiaKey what,
|
||||
float scale, int combinedLight, Level level) {
|
||||
Aspect aspect = Aspect.getAspect(what.getId().getPath());
|
||||
if (aspect == null || scale <= 0) return;
|
||||
int color = 0xFF000000 | aspect.getColor();
|
||||
float half = scale / 2;
|
||||
poseStack.pushPose();
|
||||
try {
|
||||
// Direct aspect textures are not sprites in the block texture atlas.
|
||||
poseStack.translate(0, 0, 0.01f);
|
||||
var pose = poseStack.last();
|
||||
var buffer = buffers.getBuffer(RenderType.entityTranslucent(aspect.getImage()));
|
||||
var normal = new org.joml.Vector3f(0, 0, 1);
|
||||
pose.normal().transform(normal).normalize();
|
||||
buffer.addVertex(pose, -half, -half, 0).setColor(color).setUv(0, 1)
|
||||
.setOverlay(OverlayTexture.NO_OVERLAY).setLight(combinedLight)
|
||||
.setNormal(normal.x, normal.y, normal.z);
|
||||
buffer.addVertex(pose, half, -half, 0).setColor(color).setUv(1, 1)
|
||||
.setOverlay(OverlayTexture.NO_OVERLAY).setLight(combinedLight)
|
||||
.setNormal(normal.x, normal.y, normal.z);
|
||||
buffer.addVertex(pose, half, half, 0).setColor(color).setUv(1, 0)
|
||||
.setOverlay(OverlayTexture.NO_OVERLAY).setLight(combinedLight)
|
||||
.setNormal(normal.x, normal.y, normal.z);
|
||||
buffer.addVertex(pose, -half, half, 0).setColor(color).setUv(0, 0)
|
||||
.setOverlay(OverlayTexture.NO_OVERLAY).setLight(combinedLight)
|
||||
.setNormal(normal.x, normal.y, normal.z);
|
||||
} finally {
|
||||
poseStack.popPose();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package thaumicenergistics.client;
|
||||
|
||||
import appeng.client.gui.me.common.RepoSlot;
|
||||
import appeng.helpers.InventoryAction;
|
||||
import appeng.menu.me.common.MEStorageMenu;
|
||||
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.client.event.ScreenEvent;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.appeng.EssentiaContainerItemStrategy;
|
||||
import thaumicenergistics.common.integration.tc.ThEEssentiaContainers;
|
||||
import thaumicenergistics.common.network.EssentiaTerminalDepositC2SPacket;
|
||||
import thaumicenergistics.common.network.EssentiaTerminalFillC2SPacket;
|
||||
|
||||
/** 屏幕事件覆盖原版和第三方终端,鼠标在工具栏上时不抢占模式切换按钮。 */
|
||||
public final class EssentiaTerminalInputHandler {
|
||||
private EssentiaTerminalInputHandler() {
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void mousePressed(ScreenEvent.MouseButtonPressed.Pre event) {
|
||||
if (event.getButton() != 1 || !(event.getScreen() instanceof AbstractContainerScreen<?> screen)
|
||||
|| !(screen.getMenu() instanceof MEStorageMenu menu)) {
|
||||
return;
|
||||
}
|
||||
var hovered = screen.getSlotUnderMouse();
|
||||
if (hovered == null) return;
|
||||
boolean shift = AbstractContainerScreen.hasShiftDown();
|
||||
if (menu.isPlayerSideSlot(hovered)) {
|
||||
if (shift && ThEEssentiaContainers.isEssentiaContainer(hovered.getItem())) {
|
||||
PacketDistributor.sendToServer(EssentiaTerminalDepositC2SPacket.fromSlot(
|
||||
menu.containerId, hovered.getSlotIndex(), hovered.getItem()));
|
||||
event.setCanceled(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!(hovered instanceof RepoSlot repo)) return;
|
||||
var carried = menu.getCarried();
|
||||
if (EssentiaContainerItemStrategy.recoveredContent(carried) != null) {
|
||||
menu.handleInteraction(-1, InventoryAction.EMPTY_ENTIRE_ITEM);
|
||||
event.setCanceled(true);
|
||||
return;
|
||||
}
|
||||
var source = carried.isEmpty() ? menu.getPlayerInventory().player.getMainHandItem() : carried;
|
||||
if (!ThEEssentiaContainers.isEssentiaContainer(source)) return;
|
||||
if (ThEEssentiaContainers.hasEssentia(source)) {
|
||||
if (!carried.isEmpty()) {
|
||||
// carried 的标准抽空通过 AE2 原生协议和 ContainerItemStrategy 处理。
|
||||
menu.handleInteraction(-1, InventoryAction.EMPTY_ENTIRE_ITEM);
|
||||
} else {
|
||||
PacketDistributor.sendToServer(EssentiaTerminalDepositC2SPacket.fromClientStack(
|
||||
menu.containerId, source));
|
||||
}
|
||||
} else if (!shift && repo.getEntry() != null && repo.getEntry().getWhat() instanceof AEssentiaKey key) {
|
||||
PacketDistributor.sendToServer(EssentiaTerminalFillC2SPacket.create(menu.containerId, key.getId(), source));
|
||||
}
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package thaumicenergistics.client.integration.ae2wt;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
|
||||
import appeng.client.gui.style.ScreenStyle;
|
||||
import de.mari_023.ae2wtlib.api.AE2wtlibAPI;
|
||||
import de.mari_023.ae2wtlib.api.gui.ScrollingUpgradesPanel;
|
||||
import de.mari_023.ae2wtlib.api.terminal.IUniversalTerminalCapable;
|
||||
import de.mari_023.ae2wtlib.api.terminal.WTMenuHost;
|
||||
import thaumicenergistics.common.container.ContainerArcaneCraftingTerminal;
|
||||
import thaumicenergistics.common.container.GuiArcaneCraftingTerminal;
|
||||
import org.anti_ad.mc.ipn.api.IPNIgnore;
|
||||
|
||||
/** 通用终端切换入口属于屏幕 API;仅接入物品和宿主不会自动创建切换按钮。 */
|
||||
@IPNIgnore
|
||||
public final class AE2WTArcaneTerminalScreen extends GuiArcaneCraftingTerminal
|
||||
implements IUniversalTerminalCapable {
|
||||
/** AE2WT 官方滚动升级面板(奇点居首、量子桥卡门控显隐,槽多经滚动条翻页)。 */
|
||||
private ScrollingUpgradesPanel upgradesPanel;
|
||||
|
||||
public AE2WTArcaneTerminalScreen(ContainerArcaneCraftingTerminal menu, Inventory inventory,
|
||||
Component title, ScreenStyle style) {
|
||||
super(menu, inventory, title, style);
|
||||
// 官方滚动升级面板接管右侧卡槽(普通 UpgradesPanel 经无线屏 JSON 挪出屏外防双面板
|
||||
// 抢位);槽源 = SINGULARITY + UPGRADE 两组拼接。WUT 合并多终端后升级库存扩容,
|
||||
// 普通面板纵向溢出的「插卡槽乱」由本面板的滚动窗口解决。
|
||||
upgradesPanel = addUpgradePanel(widgets, getMenu());
|
||||
if (AE2wtlibAPI.isUniversalTerminal(getHost().getItemStack())) {
|
||||
addToLeftToolbar(cycleTerminalButton());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
super.init();
|
||||
// 固定四行可视窗口(含奇点格);量子桥卡未装且奇点为空时官方逻辑自动隐藏奇点格
|
||||
// (singularitySlotHidden),滚动条范围由面板内部随可见格数自适应。
|
||||
upgradesPanel.setMaxRows(4);
|
||||
}
|
||||
|
||||
@Override
|
||||
public WTMenuHost getHost() {
|
||||
return (WTMenuHost) getMenu().getHost();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
|
||||
return checkForTerminalKeys(keyCode, scanCode)
|
||||
|| super.keyPressed(keyCode, scanCode, modifiers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package thaumicenergistics.client.integration.ae2wt;
|
||||
|
||||
import appeng.client.gui.style.StyleManager;
|
||||
import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent;
|
||||
import thaumicenergistics.init.ModMenuTypes;
|
||||
|
||||
/** 与普通客户端入口隔离,未安装 AE2WT 时不加载其屏幕 API。 */
|
||||
public final class AE2WTClientCompat {
|
||||
private AE2WTClientCompat() {
|
||||
}
|
||||
|
||||
public static void registerScreen(RegisterMenuScreensEvent event) {
|
||||
// 无线屏专用样式:继承有线布局,叠加官方三键——scrollingUpgrades/upgradeScrollbar
|
||||
// 摆位 + 普通 upgrades 面板挪出屏外(-9999),防滚动/普通双面板抢位。
|
||||
event.register(ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL.get(),
|
||||
(thaumicenergistics.common.container.ContainerArcaneCraftingTerminal menu,
|
||||
net.minecraft.world.entity.player.Inventory inventory,
|
||||
net.minecraft.network.chat.Component title) -> new AE2WTArcaneTerminalScreen(menu, inventory, title,
|
||||
StyleManager.loadStyleDoc("/screens/arcane_crafting_terminal_wireless.json")));
|
||||
}
|
||||
}
|
||||
@@ -1,89 +1,51 @@
|
||||
package thaumicenergistics.client.render.layer;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import net.minecraft.client.model.geom.ModelPart;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.entity.RenderLayerParent;
|
||||
import net.minecraft.client.renderer.entity.layers.RenderLayer;
|
||||
import net.minecraft.client.renderer.texture.OverlayTexture;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.api.distmarker.OnlyIn;
|
||||
import thaumcraft.client.renderers.entity.LegacyGolemModel;
|
||||
import thaumcraft.common.entities.golem.ThaumcraftGolemEntity;
|
||||
import thaumicenergistics.client.render.model.GolemBackpackModel;
|
||||
import thaumicenergistics.common.entities.BackpackSkins;
|
||||
import thaumicenergistics.client.render.model.GolemBackpackModels;
|
||||
import thaumicenergistics.common.network.GolemBackpackClientData;
|
||||
import thaumicenergistics.mixins.tc.AccessorLegacyGolemModel;
|
||||
|
||||
/**
|
||||
* 傀儡无线背包渲染层。
|
||||
* 当傀儡装备了无线背包时,在背上渲染天线 + 背包盒(使用当前皮肤纹理),以及旋转的福鲁伊克斯珍珠(绿色=连接,红色=断开)。
|
||||
* 数据来源:{@link GolemBackpackClientData}(由 S2C 网络包更新)。
|
||||
* 皮肤和连接状态均从客户端缓存读取,不直接查询 NBT。
|
||||
*/
|
||||
/** CE backpack geometry attached to the animated Minecraft 1.21.1 golem body. */
|
||||
@OnlyIn(Dist.CLIENT)
|
||||
public class GolemBackpackLayer extends RenderLayer<ThaumcraftGolemEntity, LegacyGolemModel> {
|
||||
public final class GolemBackpackLayer extends RenderLayer<ThaumcraftGolemEntity, LegacyGolemModel> {
|
||||
private final ModelPart root;
|
||||
private final ModelPart body;
|
||||
|
||||
/** 默认纹理(Thaumium 皮肤) */
|
||||
private static final ResourceLocation DEFAULT_TEXTURE =
|
||||
BackpackSkins.Thaumium.getTextureLocation();
|
||||
|
||||
/** 珍珠旋转速度(度/tick) */
|
||||
private static final float PEARL_ROTATION_SPEED = 2.0f;
|
||||
|
||||
private final GolemBackpackModel model;
|
||||
|
||||
public GolemBackpackLayer(RenderLayerParent<ThaumcraftGolemEntity, LegacyGolemModel> parent,
|
||||
GolemBackpackModel model) {
|
||||
public GolemBackpackLayer(RenderLayerParent<ThaumcraftGolemEntity, LegacyGolemModel> parent) {
|
||||
super(parent);
|
||||
this.model = model;
|
||||
root = ((AccessorLegacyGolemModel) (Object) getParentModel()).the$getRoot();
|
||||
body = root.getChild("body");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(PoseStack poseStack, MultiBufferSource bufferSource, int packedLight,
|
||||
public void render(PoseStack poses, MultiBufferSource buffers, int packedLight,
|
||||
ThaumcraftGolemEntity golem, float limbSwing, float limbSwingAmount,
|
||||
float partialTick, float ageInTicks, float netHeadYaw, float headPitch) {
|
||||
// 仅在傀儡装备了背包时渲染(从客户端缓存读取)
|
||||
if (!GolemBackpackClientData.hasBackpack(golem)) {
|
||||
if (golem.isInvisible() || !GolemBackpackClientData.hasBackpack(golem)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 从客户端缓存读取连接状态和皮肤
|
||||
boolean inRange = GolemBackpackClientData.isInRange(golem);
|
||||
BackpackSkins skin = GolemBackpackClientData.getSkin(golem);
|
||||
ResourceLocation texture = skin.getTextureLocation();
|
||||
|
||||
float pearlRotation = (golem.tickCount + partialTick) * PEARL_ROTATION_SPEED;
|
||||
|
||||
VertexConsumer buffer = bufferSource.getBuffer(cutoutRenderType(texture));
|
||||
|
||||
// 对齐到傀儡身体
|
||||
poseStack.pushPose();
|
||||
// 傀儡模型尺寸约 0.4×0.95,背包放在背部偏上
|
||||
poseStack.scale(0.5f, 0.5f, 0.5f);
|
||||
// 略微后移到背上
|
||||
poseStack.translate(0, 0.5, -1.5);
|
||||
|
||||
model.renderToBuffer(poseStack, buffer, packedLight, OverlayTexture.NO_OVERLAY, pearlRotation);
|
||||
|
||||
// 渲染珍珠(使用 entityTranslucent 允许半透明效果)
|
||||
VertexConsumer pearlBuffer = bufferSource.getBuffer(translucentRenderType(texture));
|
||||
model.renderPearl(poseStack, pearlBuffer, packedLight, OverlayTexture.NO_OVERLAY,
|
||||
pearlRotation, inRange);
|
||||
|
||||
poseStack.popPose();
|
||||
poses.pushPose();
|
||||
try {
|
||||
// LegacyGolemModel applies this scale only inside its own renderToBuffer.
|
||||
// Layers must repeat it before applying the animated body hierarchy.
|
||||
poses.scale(0.4F, 0.4F, 0.4F);
|
||||
root.translateAndRotate(poses);
|
||||
body.translateAndRotate(poses);
|
||||
GolemBackpackModels.current().render(poses, buffers,
|
||||
GolemBackpackClientData.getSkin(golem),
|
||||
GolemBackpackClientData.isInRange(golem),
|
||||
packedLight, OverlayTexture.NO_OVERLAY);
|
||||
} finally {
|
||||
poses.popPose();
|
||||
}
|
||||
|
||||
/** 按贴图缓存 RenderType,避免每帧创建(渲染主线程单线程安全)。 */
|
||||
private static final java.util.Map<ResourceLocation, RenderType> CUTOUT_CACHE = new java.util.HashMap<>();
|
||||
private static final java.util.Map<ResourceLocation, RenderType> TRANSLUCENT_CACHE = new java.util.HashMap<>();
|
||||
|
||||
private static RenderType cutoutRenderType(ResourceLocation tex) {
|
||||
return CUTOUT_CACHE.computeIfAbsent(tex, RenderType::entityCutoutNoCull);
|
||||
}
|
||||
|
||||
private static RenderType translucentRenderType(ResourceLocation tex) {
|
||||
return TRANSLUCENT_CACHE.computeIfAbsent(tex, RenderType::entityTranslucent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
package thaumicenergistics.client.render.model;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import net.minecraft.client.model.geom.ModelPart;
|
||||
import net.minecraft.client.model.geom.PartPose;
|
||||
import net.minecraft.client.model.geom.builders.CubeListBuilder;
|
||||
import net.minecraft.client.model.geom.builders.LayerDefinition;
|
||||
import net.minecraft.client.model.geom.builders.MeshDefinition;
|
||||
import net.minecraft.client.model.geom.builders.PartDefinition;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector4f;
|
||||
import com.mojang.math.Axis;
|
||||
|
||||
/**
|
||||
* 傀儡无线背包模型(简化版)。
|
||||
*
|
||||
* 包含三个部件:Antenna(天线,1×3×1)、PackBack(背包主体,2×6×6)、PackFront(背包前面板,1×2×4)。
|
||||
* 旋转的福鲁伊克斯珍珠由 GolemBackpackLayer 在渲染时手动绘制。
|
||||
* 对应 1.7.10 的 ModelGolemWifiBackpack,简化为统一的 Thaumium 皮肤。
|
||||
*/
|
||||
public class GolemBackpackModel {
|
||||
|
||||
private final ModelPart root;
|
||||
|
||||
public GolemBackpackModel(ModelPart root) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 LayerDefinition,供 {@code EntityRenderersEvent.RegisterLayerDefinitions} 注册。
|
||||
* 纹理尺寸 16×16,与 1.7.10 一致。
|
||||
*/
|
||||
public static LayerDefinition createBodyLayer() {
|
||||
MeshDefinition mesh = new MeshDefinition();
|
||||
PartDefinition part = mesh.getRoot();
|
||||
|
||||
// 天线:1×3×1,纹理偏移 (10,0),X 轴旋转 180°
|
||||
part.addOrReplaceChild("antenna",
|
||||
CubeListBuilder.create().texOffs(10, 0)
|
||||
.addBox(-0.5f, -6f, -0.5f, 1, 3, 1),
|
||||
PartPose.rotation((float) Math.PI, 0, 0));
|
||||
|
||||
// 背包主体:2×6×6,纹理偏移 (0,0),X 轴旋转 180°
|
||||
part.addOrReplaceChild("pack_back",
|
||||
CubeListBuilder.create().texOffs(0, 0)
|
||||
.addBox(-1f, -3f, -3f, 2, 6, 6),
|
||||
PartPose.rotation((float) Math.PI, 0, 0));
|
||||
|
||||
// 背包前面板:1×2×4,纹理偏移 (2,0),X 轴旋转 180°
|
||||
part.addOrReplaceChild("pack_front",
|
||||
CubeListBuilder.create().texOffs(2, 0)
|
||||
.addBox(-1.5f, -1f, -2f, 1, 2, 4),
|
||||
PartPose.rotation((float) Math.PI, 0, 0));
|
||||
|
||||
return LayerDefinition.create(mesh, 16, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染背包箱体(天线 + 主体 + 前面板)。
|
||||
*/
|
||||
public void renderToBuffer(PoseStack poseStack, VertexConsumer buffer,
|
||||
int light, int overlay, float pearlRotation) {
|
||||
root.render(poseStack, buffer, light, overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染旋转的福鲁伊克斯珍珠:位于天线上方,4 个面围绕天线绘制,随 pearlRotation 旋转。
|
||||
* UV 坐标:minU=0.5, maxU=0.84375, minV=0.375, maxV=0.71875(16×16 纹理)。
|
||||
*
|
||||
* @param poseStack PoseStack
|
||||
* @param buffer VertexConsumer
|
||||
* @param light packed light
|
||||
* @param overlay packed overlay
|
||||
* @param pearlRotation 旋转角度(度)
|
||||
* @param inRange true=正常紫色,false=红色(不在范围内)
|
||||
*/
|
||||
public void renderPearl(PoseStack poseStack, VertexConsumer buffer,
|
||||
int light, int overlay, float pearlRotation, boolean inRange) {
|
||||
float pearlScale = 0.2f;
|
||||
float antennaWidth = 0.32f;
|
||||
float faceDist = -0.013f / pearlScale;
|
||||
float twoFD = faceDist + faceDist;
|
||||
|
||||
// UV 坐标(16×16 纹理)
|
||||
float minU = 8.0f / 16.0f;
|
||||
float maxU = 13.5f / 16.0f;
|
||||
float minV = 6.0f / 16.0f;
|
||||
float maxV = 11.5f / 16.0f;
|
||||
|
||||
// 颜色:不在范围内时红色
|
||||
int red = inRange ? 255 : 255;
|
||||
int green = inRange ? 255 : 0;
|
||||
int blue = inRange ? 255 : 0;
|
||||
|
||||
poseStack.pushPose();
|
||||
|
||||
poseStack.mulPose(Axis.YP.rotationDegrees(pearlRotation));
|
||||
|
||||
poseStack.scale(pearlScale, pearlScale, pearlScale);
|
||||
|
||||
// 左面
|
||||
poseStack.pushPose();
|
||||
poseStack.translate(-0.0955f, 0.275f, -0.045f);
|
||||
drawPearlFace(poseStack, buffer, light, overlay, minU, maxU, minV, maxV, red, green, blue, 0, 0, 1);
|
||||
// 右面
|
||||
poseStack.translate(0, 0, antennaWidth - twoFD);
|
||||
drawPearlFace(poseStack, buffer, light, overlay, maxU, minU, minV, maxV, red, green, blue, 0, 0, -1);
|
||||
poseStack.popPose();
|
||||
|
||||
// 前后两面(旋转 90°)
|
||||
poseStack.pushPose();
|
||||
poseStack.mulPose(Axis.YP.rotationDegrees(90));
|
||||
poseStack.translate(-0.0955f, 0.275f, -0.045f - antennaWidth - faceDist);
|
||||
drawPearlFace(poseStack, buffer, light, overlay, maxU, minU, minV, maxV, red, green, blue, 0, 0, -1);
|
||||
poseStack.translate(0, 0, antennaWidth - twoFD);
|
||||
drawPearlFace(poseStack, buffer, light, overlay, minU, maxU, minV, maxV, red, green, blue, 0, 0, 1);
|
||||
poseStack.popPose();
|
||||
|
||||
poseStack.popPose();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制珍珠的一个面(正反两面,共 8 个顶点),手动通过矩阵变换顶点坐标。
|
||||
* 使用 1.21.1 的 VertexConsumer 新 API:addVertex + setColor + setUv + setOverlay + setLight + setNormal。
|
||||
*/
|
||||
private void drawPearlFace(PoseStack poseStack, VertexConsumer buffer, int light, int overlay,
|
||||
float minU, float maxU, float minV, float maxV,
|
||||
int r, int g, int b, float nx, float ny, float nz) {
|
||||
Matrix4f matrix = poseStack.last().pose();
|
||||
|
||||
// 四个角点的本地坐标
|
||||
float[][] corners = {
|
||||
{0, 0, 0}, // 左下
|
||||
{1, 0, 0}, // 右下
|
||||
{1, 1, 0}, // 右上
|
||||
{0, 1, 0} // 左上
|
||||
};
|
||||
|
||||
// 正面 UV
|
||||
float[][] frontUvs = {
|
||||
{maxU, maxV},
|
||||
{minU, maxV},
|
||||
{minU, minV},
|
||||
{maxU, minV}
|
||||
};
|
||||
|
||||
// 背面 UV(镜像)
|
||||
float[][] backUvs = {
|
||||
{maxU, minV},
|
||||
{minU, minV},
|
||||
{minU, maxV},
|
||||
{maxU, maxV}
|
||||
};
|
||||
|
||||
Vector4f transformed = new Vector4f();
|
||||
|
||||
// 正面
|
||||
for (int i = 0; i < 4; i++) {
|
||||
transformed.set(corners[i][0], corners[i][1], corners[i][2], 1.0f);
|
||||
matrix.transform(transformed);
|
||||
buffer.addVertex(transformed.x, transformed.y, transformed.z)
|
||||
.setColor(r, g, b, 255)
|
||||
.setUv(frontUvs[i][0], frontUvs[i][1])
|
||||
.setOverlay(overlay)
|
||||
.setLight(light)
|
||||
.setNormal(nx, ny, nz);
|
||||
}
|
||||
|
||||
// 背面(逆序 + 翻转法线)
|
||||
for (int i = 0; i < 4; i++) {
|
||||
transformed.set(corners[i][0], corners[i][1], corners[i][2], 1.0f);
|
||||
matrix.transform(transformed);
|
||||
buffer.addVertex(transformed.x, transformed.y, transformed.z)
|
||||
.setColor(r, g, b, 255)
|
||||
.setUv(backUvs[i][0], backUvs[i][1])
|
||||
.setOverlay(overlay)
|
||||
.setLight(light)
|
||||
.setNormal(-nx, -ny, -nz);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package thaumicenergistics.client.render.model;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.HashSet;
|
||||
import net.minecraft.client.renderer.FaceInfo;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.entities.BackpackSkins;
|
||||
|
||||
/**
|
||||
* Per-face model loader adapted from Thaumic Energistics: CE (Minecraft 26.1.2).
|
||||
* Copyright (c) 2026 Thaumic Energistics: CE contributors. MIT License.
|
||||
* Full notice: META-INF/licenses/thaumicenergistics-ce-backpack.txt.
|
||||
* Uses direct texture coordinates; these vertices must not use the block atlas.
|
||||
*/
|
||||
@net.neoforged.api.distmarker.OnlyIn(net.neoforged.api.distmarker.Dist.CLIENT)
|
||||
public final class GolemBackpackModels {
|
||||
public static final ResourceLocation RESOURCE = ThaumicEnergistics.id("models/entity/golem_backpack.json");
|
||||
private static volatile GolemBackpackModels current = new GolemBackpackModels(
|
||||
List.of(), Map.of(), Map.of(), Set.of(), "", new Vector3f(), new Vector3f(), new Vector3f(1));
|
||||
|
||||
private final List<Quad> quads;
|
||||
private final Map<String, ResourceLocation> textures;
|
||||
private final Map<String, String> connectedTextures;
|
||||
private final Set<ResourceLocation> emissiveTextures;
|
||||
private final String skinTexture;
|
||||
private final Vector3f translation;
|
||||
private final Vector3f rotation;
|
||||
private final Vector3f scale;
|
||||
private final Map<ResourceLocation, RenderType> renderTypes = new HashMap<>();
|
||||
|
||||
private record Vertex(Vector3f position, float u, float v) {}
|
||||
private record Quad(String texture, List<Vertex> vertices, Vector3f normal) {}
|
||||
|
||||
private GolemBackpackModels(List<Quad> quads, Map<String, ResourceLocation> textures,
|
||||
Map<String, String> connectedTextures, Set<ResourceLocation> emissiveTextures, String skinTexture,
|
||||
Vector3f translation, Vector3f rotation, Vector3f scale) {
|
||||
this.quads = List.copyOf(quads);
|
||||
this.textures = Map.copyOf(textures);
|
||||
this.connectedTextures = Map.copyOf(connectedTextures);
|
||||
this.emissiveTextures = Set.copyOf(emissiveTextures);
|
||||
this.skinTexture = skinTexture;
|
||||
this.translation = translation;
|
||||
this.rotation = rotation;
|
||||
this.scale = scale;
|
||||
}
|
||||
|
||||
public static GolemBackpackModels current() { return current; }
|
||||
|
||||
public static void reload(ResourceManager resources) {
|
||||
try (var reader = resources.getResourceOrThrow(RESOURCE).openAsReader()) {
|
||||
current = load(JsonParser.parseReader(reader).getAsJsonObject());
|
||||
} catch (Exception error) {
|
||||
ThaumicEnergistics.LOG.error("Failed to load backpack model {}. Keeping the previous model.", RESOURCE, error);
|
||||
}
|
||||
}
|
||||
|
||||
public static GolemBackpackModels load(JsonObject data) {
|
||||
var attachment = data.getAsJsonObject("attachment");
|
||||
var origin = vector(attachment.getAsJsonArray("origin"));
|
||||
var textures = new HashMap<String, ResourceLocation>();
|
||||
data.getAsJsonObject("textures").entrySet().forEach(entry -> {
|
||||
var id = ResourceLocation.parse(entry.getValue().getAsString());
|
||||
String path = id.getPath();
|
||||
if (!path.startsWith("textures/")) path = "textures/" + path;
|
||||
if (!path.endsWith(".png")) path += ".png";
|
||||
textures.put(entry.getKey(), ResourceLocation.fromNamespaceAndPath(id.getNamespace(), path));
|
||||
});
|
||||
var connected = new HashMap<String, String>();
|
||||
data.getAsJsonObject("connected_textures").entrySet().forEach(entry ->
|
||||
connected.put(entry.getKey(), entry.getValue().getAsString()));
|
||||
String skinTexture = data.get("skin_texture").getAsString();
|
||||
if (!textures.containsKey(skinTexture)) throw new IllegalArgumentException("Unknown skin texture: " + skinTexture);
|
||||
connected.forEach((source, target) -> {
|
||||
if (!textures.containsKey(source) || !textures.containsKey(target)) {
|
||||
throw new IllegalArgumentException("Unknown connected texture: " + source + " -> " + target);
|
||||
}
|
||||
});
|
||||
var emissive = new HashSet<ResourceLocation>();
|
||||
if (data.has("emissive_textures")) {
|
||||
for (var value : data.getAsJsonArray("emissive_textures")) {
|
||||
String key = value.getAsString();
|
||||
if (!textures.containsKey(key)) throw new IllegalArgumentException("Unknown emissive texture: " + key);
|
||||
emissive.add(textures.get(key));
|
||||
}
|
||||
}
|
||||
var quads = new ArrayList<Quad>();
|
||||
for (var value : data.getAsJsonArray("elements")) {
|
||||
var element = value.getAsJsonObject();
|
||||
var from = vector(element.getAsJsonArray("from"));
|
||||
var to = vector(element.getAsJsonArray("to"));
|
||||
var transform = elementTransform(element);
|
||||
for (var entry : element.getAsJsonObject("faces").entrySet()) {
|
||||
var direction = Direction.byName(entry.getKey());
|
||||
if (direction == null) throw new IllegalArgumentException("Unknown face: " + entry.getKey());
|
||||
var face = entry.getValue().getAsJsonObject();
|
||||
String texture = face.get("texture").getAsString();
|
||||
if (!texture.startsWith("#") || !textures.containsKey(texture.substring(1))) {
|
||||
throw new IllegalArgumentException("Unknown face texture: " + texture);
|
||||
}
|
||||
var uv = face.getAsJsonArray("uv");
|
||||
if (uv.size() != 4) throw new IllegalArgumentException("Expected four UV coordinates");
|
||||
float u0 = number(uv, 0) / 16, v0 = number(uv, 1) / 16;
|
||||
float u1 = number(uv, 2) / 16, v1 = number(uv, 3) / 16;
|
||||
float[][] corners = {{u0, v0}, {u0, v1}, {u1, v1}, {u1, v0}};
|
||||
int angle = face.has("rotation") ? face.get("rotation").getAsInt() : 0;
|
||||
if (angle % 90 != 0) throw new IllegalArgumentException("Face rotation must be a multiple of 90 degrees");
|
||||
var vertices = new ArrayList<Vertex>(4);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
var position = faceVertex(direction, i, from, to);
|
||||
transform.transformPosition(position);
|
||||
position.sub(origin).div(16);
|
||||
var coordinate = corners[Math.floorMod(i + angle / 90, 4)];
|
||||
vertices.add(new Vertex(position, coordinate[0], coordinate[1]));
|
||||
}
|
||||
var normal = new Vector3f(vertices.get(1).position()).sub(vertices.get(0).position())
|
||||
.cross(new Vector3f(vertices.get(2).position()).sub(vertices.get(0).position()));
|
||||
if (normal.lengthSquared() == 0) continue;
|
||||
normal.normalize();
|
||||
quads.add(new Quad(texture.substring(1), List.copyOf(vertices), normal));
|
||||
}
|
||||
}
|
||||
if (quads.isEmpty()) throw new IllegalArgumentException("Backpack model has no visible faces");
|
||||
return new GolemBackpackModels(quads, textures, connected, emissive, skinTexture,
|
||||
vector(attachment.getAsJsonArray("translation")),
|
||||
vector(attachment.getAsJsonArray("rotation")), vector(attachment.getAsJsonArray("scale")));
|
||||
}
|
||||
|
||||
// Minecraft 1.21.1 exposes the face vertex indices rather than select(from, to).
|
||||
private static Vector3f faceVertex(Direction direction, int index, Vector3f from, Vector3f to) {
|
||||
var vertex = FaceInfo.fromFacing(direction).getVertexInfo(index);
|
||||
float[] bounds = new float[6];
|
||||
bounds[FaceInfo.Constants.MIN_X] = from.x;
|
||||
bounds[FaceInfo.Constants.MIN_Y] = from.y;
|
||||
bounds[FaceInfo.Constants.MIN_Z] = from.z;
|
||||
bounds[FaceInfo.Constants.MAX_X] = to.x;
|
||||
bounds[FaceInfo.Constants.MAX_Y] = to.y;
|
||||
bounds[FaceInfo.Constants.MAX_Z] = to.z;
|
||||
return new Vector3f(bounds[vertex.xFace], bounds[vertex.yFace], bounds[vertex.zFace]);
|
||||
}
|
||||
|
||||
private static Matrix4f elementTransform(JsonObject element) {
|
||||
var transform = new Matrix4f();
|
||||
if (!element.has("rotation")) return transform;
|
||||
var rotation = element.getAsJsonObject("rotation");
|
||||
var origin = vector(rotation.getAsJsonArray("origin"));
|
||||
float angle = (float) Math.toRadians(rotation.get("angle").getAsDouble());
|
||||
if (!Float.isFinite(angle)) throw new IllegalArgumentException("Non-finite element rotation");
|
||||
String axis = rotation.get("axis").getAsString();
|
||||
transform.translate(origin);
|
||||
switch (axis) {
|
||||
case "x" -> transform.rotateX(angle);
|
||||
case "y" -> transform.rotateY(angle);
|
||||
case "z" -> transform.rotateZ(angle);
|
||||
default -> throw new IllegalArgumentException("Unknown rotation axis: " + axis);
|
||||
}
|
||||
if (rotation.has("rescale") && rotation.get("rescale").getAsBoolean()) {
|
||||
float factor = 1 / (float) Math.cos(angle);
|
||||
if (!Float.isFinite(factor)) throw new IllegalArgumentException("Invalid rotation rescale");
|
||||
transform.scale(axis.equals("x") ? 1 : factor,
|
||||
axis.equals("y") ? 1 : factor, axis.equals("z") ? 1 : factor);
|
||||
}
|
||||
return transform.translate(new Vector3f(origin).negate());
|
||||
}
|
||||
|
||||
private static Vector3f vector(JsonArray data) {
|
||||
if (data.size() != 3) throw new IllegalArgumentException("Expected a three-dimensional vector");
|
||||
return new Vector3f(number(data, 0), number(data, 1), number(data, 2));
|
||||
}
|
||||
|
||||
private static float number(JsonArray data, int index) {
|
||||
float number = data.get(index).getAsFloat();
|
||||
if (!Float.isFinite(number)) throw new IllegalArgumentException("Non-finite model coordinate");
|
||||
return number;
|
||||
}
|
||||
|
||||
public void render(PoseStack poses, MultiBufferSource buffers, BackpackSkins skin,
|
||||
boolean working, int light, int overlay) {
|
||||
poses.pushPose();
|
||||
poses.translate(translation.x, translation.y, translation.z);
|
||||
poses.mulPose(new org.joml.Quaternionf().rotationXYZ(
|
||||
(float) Math.toRadians(rotation.x), (float) Math.toRadians(rotation.y), (float) Math.toRadians(rotation.z)));
|
||||
poses.scale(scale.x, scale.y, scale.z);
|
||||
var pose = poses.last();
|
||||
var normal = new Vector3f();
|
||||
for (var quad : quads) {
|
||||
String key = working ? connectedTextures.getOrDefault(quad.texture(), quad.texture()) : quad.texture();
|
||||
var texture = key.equals(skinTexture) ? skin.getTextureLocation() : textures.get(key);
|
||||
boolean emissive = emissiveTextures.contains(texture);
|
||||
VertexConsumer buffer = buffers.getBuffer(renderTypes.computeIfAbsent(texture,
|
||||
id -> emissiveTextures.contains(id)
|
||||
? RenderType.entityTranslucentEmissive(id)
|
||||
: RenderType.entityCutoutNoCull(id)));
|
||||
normal.set(quad.normal());
|
||||
pose.normal().transform(normal).normalize();
|
||||
int faceLight = emissive ? net.minecraft.client.renderer.LightTexture.FULL_BRIGHT : light;
|
||||
for (var vertex : quad.vertices()) {
|
||||
var position = vertex.position();
|
||||
buffer.addVertex(pose, position.x, position.y, position.z)
|
||||
.setColor(255, 255, 255, 255).setUv(vertex.u(), vertex.v())
|
||||
.setOverlay(overlay).setLight(faceLight).setNormal(normal.x, normal.y, normal.z);
|
||||
}
|
||||
}
|
||||
poses.popPose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package thaumicenergistics.common.blocks;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.Containers;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.ItemInteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.context.BlockPlaceContext;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.StateDefinition;
|
||||
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
|
||||
import net.minecraft.world.level.block.state.properties.BooleanProperty;
|
||||
import net.minecraft.world.level.storage.loot.LootParams;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.shapes.CollisionContext;
|
||||
import net.minecraft.world.phys.shapes.Shapes;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
|
||||
/** Decorative dolls sharing Alkusure86's right-click variant and sneak-pickup behavior. */
|
||||
public final class FumoBlock extends Block {
|
||||
public static final BooleanProperty VARIANT = BooleanProperty.create("variant");
|
||||
|
||||
public FumoBlock(Properties properties) {
|
||||
super(properties);
|
||||
registerDefaultState(defaultBlockState().setValue(VARIANT, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
|
||||
builder.add(BlockStateProperties.HORIZONTAL_FACING, VARIANT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState getStateForPlacement(BlockPlaceContext context) {
|
||||
return defaultBlockState().setValue(BlockStateProperties.HORIZONTAL_FACING,
|
||||
context.getHorizontalDirection().getOpposite());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos,
|
||||
Player player, InteractionHand hand, BlockHitResult hit) {
|
||||
if (player.isShiftKeyDown()) pickUp(level, pos, player);
|
||||
else toggleVariant(level, pos, state);
|
||||
return ItemInteractionResult.sidedSuccess(level.isClientSide());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos,
|
||||
Player player, BlockHitResult hit) {
|
||||
if (player.isShiftKeyDown()) pickUp(level, pos, player);
|
||||
else toggleVariant(level, pos, state);
|
||||
return InteractionResult.sidedSuccess(level.isClientSide());
|
||||
}
|
||||
|
||||
private void pickUp(Level level, BlockPos pos, Player player) {
|
||||
if (level.isClientSide) return;
|
||||
ItemStack item = new ItemStack(this);
|
||||
level.removeBlock(pos, false);
|
||||
if (player.getMainHandItem().isEmpty()) player.setItemInHand(InteractionHand.MAIN_HAND, item);
|
||||
else if (!player.getInventory().add(item)) {
|
||||
Containers.dropItemStack(level, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, item);
|
||||
}
|
||||
}
|
||||
|
||||
private void toggleVariant(Level level, BlockPos pos, BlockState state) {
|
||||
if (!level.isClientSide) level.setBlock(pos, state.cycle(VARIANT), 3);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) {
|
||||
return Shapes.box(0.25, 0, 0.25, 0.75, 0.75, 0.75);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ItemStack> getDrops(BlockState state, LootParams.Builder builder) {
|
||||
return List.of(new ItemStack(this));
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,10 @@ import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
@@ -28,6 +30,37 @@ public final class ThEWrenchHandler {
|
||||
NeoForge.EVENT_BUS.register(ThEWrenchHandler.class);
|
||||
}
|
||||
|
||||
/** 判定目标是否为本模组可拆卸方块(按命名空间判断,兼容未继承 ThETileBase 的工作台等)。 */
|
||||
public static boolean isDisassemblyTarget(Level level, BlockPos pos) {
|
||||
BlockState state = level.getBlockState(pos);
|
||||
return ThaumicEnergistics.MODID
|
||||
.equals(state.getBlock().builtInRegistryHolder().key().location().getNamespace());
|
||||
}
|
||||
|
||||
/**
|
||||
* ThE 方块扳手拆卸公共入口(普通 AE2 扳手事件与法杖 AE 扳手核心共用):
|
||||
* 服务端掉落方块物品并移除方块,客户端播放拆卸音效。
|
||||
* 返回 true 表示目标为 ThE 方块且拆卸已执行。
|
||||
*/
|
||||
public static boolean disassembleThEBlock(Player player, Level level, BlockPos pos) {
|
||||
if (!isDisassemblyTarget(level, pos)) {
|
||||
return false;
|
||||
}
|
||||
BlockEntity be = level.getBlockEntity(pos);
|
||||
if (be == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!level.isClientSide) {
|
||||
// ThE 方块掉落即自身(挖掘走 getDrops 覆写;扳手拆卸直接给方块物品,避免 loot table 为空)
|
||||
player.getInventory().placeItemBackInInventory(new ItemStack(be.getBlockState().getBlock()));
|
||||
level.removeBlock(pos, false);
|
||||
} else {
|
||||
level.playSound(player, pos, SoundEvents.ITEM_FRAME_REMOVE_ITEM, SoundSource.BLOCKS, 0.7F, 1.0F);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event) {
|
||||
if (event.isCanceled() || event.getHand() != InteractionHand.MAIN_HAND) {
|
||||
@@ -44,22 +77,9 @@ public final class ThEWrenchHandler {
|
||||
|
||||
var level = event.getLevel();
|
||||
BlockPos pos = event.getPos();
|
||||
BlockState state = level.getBlockState(pos);
|
||||
// 只处理 ThE 方块(按命名空间判断,兼容未继承 ThETileBase 的工作台等)
|
||||
if (!ThaumicEnergistics.MODID.equals(state.getBlock().builtInRegistryHolder().key().location().getNamespace())) {
|
||||
return;
|
||||
}
|
||||
BlockEntity be = level.getBlockEntity(pos);
|
||||
if (be == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!level.isClientSide) {
|
||||
// ThE 方块掉落即自身(挖掘走 getDrops 覆写;扳手拆卸直接给方块物品,避免 loot table 为空)
|
||||
player.getInventory().placeItemBackInInventory(new ItemStack(be.getBlockState().getBlock()));
|
||||
level.removeBlock(pos, false);
|
||||
} else {
|
||||
level.playSound(player, pos, SoundEvents.ITEM_FRAME_REMOVE_ITEM, SoundSource.BLOCKS, 0.7F, 1.0F);
|
||||
if (!disassembleThEBlock(player, level, pos)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.setCanceled(true);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package thaumicenergistics.common.container;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import appeng.api.inventories.InternalInventory;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.CraftingInput;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import thaumcraft.common.items.TCFunctionalItems;
|
||||
import thaumcraft.common.lib.crafting.ThaumcraftCraftingManager;
|
||||
|
||||
/** 配方解析与法杖成本计算;菜单只负责槽位及同步状态。 */
|
||||
public final class ArcaneTerminalRecipeState {
|
||||
public record Match(ItemStack output, AspectList cost, boolean arcane) { }
|
||||
|
||||
private ArcaneTerminalRecipeState() { }
|
||||
|
||||
public static Match resolve(InternalInventory grid, ItemStack wand, Player player) {
|
||||
var level = player.level();
|
||||
if (level.getServer() != null) {
|
||||
var container = grid.toContainer();
|
||||
var output = ThaumcraftCraftingManager.findMatchingArcaneRecipe(container, player);
|
||||
if (!output.isEmpty()) {
|
||||
var cost = ThaumcraftCraftingManager.findMatchingArcaneRecipeAspects(container, player);
|
||||
return new Match(hasEnoughVis(wand, cost, player) ? output : ItemStack.EMPTY, cost, true);
|
||||
}
|
||||
}
|
||||
var items = new ArrayList<ItemStack>(grid.size());
|
||||
for (int i = 0; i < grid.size(); i++) items.add(grid.getStackInSlot(i).copy());
|
||||
var input = CraftingInput.of(3, 3, items);
|
||||
var recipe = level.getRecipeManager().getRecipeFor(RecipeType.CRAFTING, input, level);
|
||||
return new Match(recipe.map(holder -> holder.value().assemble(input, level.registryAccess()))
|
||||
.orElse(ItemStack.EMPTY), null, false);
|
||||
}
|
||||
|
||||
public static boolean hasEnoughVis(ItemStack stack, AspectList cost, Player player) {
|
||||
if (cost == null || cost.isEmpty()) return true;
|
||||
if (stack.isEmpty() || !(stack.getItem() instanceof TCFunctionalItems.WandCastingItem wand)) return false;
|
||||
var centivis = new AspectList();
|
||||
for (var aspect : cost.aspects()) centivis.add(aspect, cost.amount(aspect) * 100);
|
||||
return wand.consumeVisCost(stack, player, centivis, false, true);
|
||||
}
|
||||
|
||||
public static String displayedCosts(ItemStack stack, AspectList cost, Player player) {
|
||||
if (cost == null || cost.isEmpty()) return "";
|
||||
var result = new StringBuilder();
|
||||
for (var entry : cost.aspects.entrySet()) {
|
||||
if (!result.isEmpty()) result.append(',');
|
||||
float modifier = stack.getItem() instanceof TCFunctionalItems.WandCastingItem wand
|
||||
? wand.consumptionModifier(stack, player, entry.getKey(), true) : 1.0F;
|
||||
result.append(entry.getKey().getTag()).append('=')
|
||||
.append(Math.max(0, Math.round(entry.getValue() * modifier)));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static Map<String, Integer> parseCosts(String data) {
|
||||
var result = new LinkedHashMap<String, Integer>();
|
||||
for (var part : data.split(",")) {
|
||||
var pair = part.split("=", 2);
|
||||
if (pair.length != 2) continue;
|
||||
try { result.put(pair[0], Integer.parseInt(pair[1])); }
|
||||
catch (NumberFormatException ignored) { }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+40
-167
@@ -1,9 +1,7 @@
|
||||
package thaumicenergistics.common.container;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -13,8 +11,6 @@ import net.minecraft.world.Container;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.CraftingInput;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
|
||||
import appeng.api.inventories.ISegmentedInventory;
|
||||
import appeng.api.inventories.InternalInventory;
|
||||
@@ -36,16 +32,13 @@ import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import net.neoforged.fml.ModList;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import thaumicenergistics.common.network.ArcaneTerminalClearC2SPacket;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import thaumcraft.common.items.TCFunctionalItems;
|
||||
import thaumcraft.common.lib.crafting.ThaumcraftCraftingManager;
|
||||
import thaumicenergistics.common.container.slot.ArcaneCraftingResultSlot;
|
||||
import thaumicenergistics.common.items.VisConnectorCardItem;
|
||||
import thaumicenergistics.common.items.WirelessArcaneCraftingTerminalMenuHost;
|
||||
import thaumicenergistics.common.integration.ae2wt.AE2WTCompat;
|
||||
import thaumicenergistics.common.parts.ArcaneCraftingTerminalPart;
|
||||
import thaumicenergistics.common.parts.ArcaneVisReplenish;
|
||||
import thaumicenergistics.init.ModMenuTypes;
|
||||
|
||||
public class ContainerArcaneCraftingTerminal extends MEStorageMenu implements ICraftingGridMenu {
|
||||
@@ -69,28 +62,7 @@ public class ContainerArcaneCraftingTerminal extends MEStorageMenu implements IC
|
||||
@Override
|
||||
public void broadcastChanges() {
|
||||
super.broadcastChanges();
|
||||
// 无线奥术合成终端(T-M3-VISCARD-REV):终端升级槽装有 vis 连接卡时自动充能——
|
||||
// 遍历所在网络全部要素中继接口(replenishAuto),无需频率/绑定;仅菜单打开期间驱动(D1)。
|
||||
if (!isClientSide()
|
||||
&& this.craftingInventoryHost instanceof WirelessArcaneCraftingTerminalMenuHost wirelessHost) {
|
||||
var upgrades = wirelessHost.getUpgrades();
|
||||
boolean hasVisCard = false;
|
||||
for (int i = 0; i < upgrades.size(); i++) {
|
||||
if (upgrades.getStackInSlot(i).getItem() instanceof VisConnectorCardItem) {
|
||||
hasVisCard = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hasVisCard) {
|
||||
var node = wirelessHost.getActionableNode();
|
||||
var wandInv = wirelessHost.getSubInventory(ArcaneCraftingTerminalPart.INV_WAND);
|
||||
var wandStack = wandInv != null ? wandInv.getStackInSlot(0) : ItemStack.EMPTY;
|
||||
if (ArcaneVisReplenish.replenishAuto(
|
||||
node != null ? node.getGrid() : null, wandStack)) {
|
||||
wirelessHost.saveWandInv();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wireless wand charging has one owner: the server player tick, including this live menu host.
|
||||
// vis 充能恢复后自动重算结果槽:结果槽空 + 奥术配方有效 + vis 已足够 → 重新显示产物。
|
||||
// 节流:仅"待恢复"状态每 10 tick 检查一次(findMatchingArcaneRecipe 只在满足时执行)
|
||||
var player = getPlayerInventory().player;
|
||||
@@ -155,21 +127,23 @@ public class ContainerArcaneCraftingTerminal extends MEStorageMenu implements IC
|
||||
public void setChanged() {
|
||||
super.setChanged();
|
||||
// 法杖槽变化时立即重检配方,更新 resultSlot 的 wandStack
|
||||
updateCurrentRecipeAndOutput(false);
|
||||
updateCurrentRecipeAndOutput();
|
||||
}
|
||||
}, SlotSemantics.STORAGE);
|
||||
|
||||
// WTBRIDGE-SLOT:无线终端专属——量子缠绕奇点安装槽(桥卡链路第三环:奇点写入 UI)。
|
||||
// 有线部件宿主无此槽(instanceof 守卫);客户端/服务端 host 类型一致故槽集一致。
|
||||
// WTBRIDGE-SLOT:无线终端(独立 / AE2WT 通用奥术模式)专属——量子缠绕奇点安装槽。
|
||||
// 有线部件宿主无此槽(契约 getSingularityInvId 返回 null 守卫);客户端/服务端 host
|
||||
// 类型一致故槽集一致。
|
||||
// ae2wtlib 缺席时准入拦截(组件无处写回,防放入即丢);ae2 原生缠绕奇点直接编译引用。
|
||||
// 语义挂 AE2 原生 UPGRADE 组(注册顺序在基类 setupUpgrades 的升级卡槽之后)——右侧
|
||||
// 升级卡槽面板按 getSlots(UPGRADE) 挂单一 UpgradesPanel,奇点槽自动成为同面板第三格
|
||||
// (2 升级卡 + 1 奇点,一个整体)。注意:WACT host 非 IViewCellStorage,VIEW_CELL 组
|
||||
// 为空、其面板不挂载,槽挂该组将无人摆位;奇点槽仅语义归类,仍绑自有 singularityInv,
|
||||
// 升级库存读写(isInstalled 等)不受影响。
|
||||
if (this.craftingInventoryHost instanceof WirelessArcaneCraftingTerminalMenuHost wirelessHost) {
|
||||
var singularityInv = wirelessHost.getSubInventory(WirelessArcaneCraftingTerminalMenuHost.INV_SINGULARITY);
|
||||
this.addSlot(new AppEngSlot(singularityInv, 0) {
|
||||
// 语义分支:AE2WT 宿主挂官方 SINGULARITY 组——AE2WT 滚动升级面板取槽 =
|
||||
// SINGULARITY + UPGRADE 两组拼接且要求奇点居首(slots.getFirst()),面板还自带
|
||||
// 量子桥卡门控显隐;独立无线(无 ae2wtlib)保持 UPGRADE 组并入普通升级面板。
|
||||
// AE2wtlibSlotSemantics 仅 ae2wtlib 在场时存在,经 AE2WTCompat.singularitySemantic
|
||||
// 隔离解析;分支条件为契约虚调用,无需菜单侧加载 ae2wtlib 类型。
|
||||
if (this.craftingInventoryHost instanceof IArcaneTerminalInventoryHost wirelessHost
|
||||
&& wirelessHost.getSingularityInvId() != null) {
|
||||
var singularityInv = wirelessHost.getSubInventory(wirelessHost.getSingularityInvId());
|
||||
var singularitySlot = new AppEngSlot(singularityInv, 0) {
|
||||
@Override
|
||||
public int getMaxStackSize() {
|
||||
return 1;
|
||||
@@ -177,13 +151,18 @@ public class ContainerArcaneCraftingTerminal extends MEStorageMenu implements IC
|
||||
|
||||
@Override
|
||||
public boolean mayPlace(ItemStack stack) {
|
||||
return ModList.get().isLoaded(WirelessArcaneCraftingTerminalMenuHost.AE2WTLIB_MODID)
|
||||
return ModList.get().isLoaded(IArcaneTerminalInventoryHost.AE2WTLIB_MODID)
|
||||
&& stack.is(AEItems.QUANTUM_ENTANGLED_SINGULARITY.asItem());
|
||||
}
|
||||
}, SlotSemantics.UPGRADE);
|
||||
};
|
||||
if (wirelessHost.useAE2WTSingularitySemantics()) {
|
||||
this.addSlot(singularitySlot, AE2WTCompat.singularitySemantic());
|
||||
} else {
|
||||
this.addSlot(singularitySlot, SlotSemantics.UPGRADE);
|
||||
}
|
||||
}
|
||||
|
||||
updateCurrentRecipeAndOutput(true);
|
||||
updateCurrentRecipeAndOutput();
|
||||
|
||||
registerClientAction(ACTION_CLEAR_TO_PLAYER, this::clearToPlayerInventory);
|
||||
}
|
||||
@@ -311,7 +290,7 @@ public class ContainerArcaneCraftingTerminal extends MEStorageMenu implements IC
|
||||
@Override
|
||||
public void slotsChanged(Container inventory) {
|
||||
if (!isCraftingResultBeingTaken) {
|
||||
updateCurrentRecipeAndOutput(false);
|
||||
updateCurrentRecipeAndOutput();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,136 +298,30 @@ public class ContainerArcaneCraftingTerminal extends MEStorageMenu implements IC
|
||||
this.isCraftingResultBeingTaken = beingTaken;
|
||||
}
|
||||
|
||||
private static final int CENTIVIS = 100;
|
||||
|
||||
/**
|
||||
* 复刻 TC port {@code WandCastingItem.consumptionModifier}:法杖 cap 折扣 − 玩家装备/饰品折扣 − 法杖折扣。
|
||||
* 仅用于显示(GUI 所需 vis),实际扣费由 consumeVisCost 内部同公式处理。
|
||||
*/
|
||||
private float getConsumptionModifier(Aspect aspect, boolean crafting) {
|
||||
var wandInv = this.craftingInventoryHost.getSubInventory(ArcaneCraftingTerminalPart.INV_WAND);
|
||||
var wandStack = wandInv.getStackInSlot(0);
|
||||
if (wandStack.isEmpty() || !(wandStack.getItem() instanceof TCFunctionalItems.WandCastingItem wand)) {
|
||||
return 1.0f;
|
||||
}
|
||||
float modifier = wand.consumptionModifier(wandStack, getPlayerInventory().player, aspect, crafting);
|
||||
return modifier;
|
||||
}
|
||||
|
||||
/** 折扣后的 vis 成本(GUI 显示用)。 */
|
||||
private int getDiscountedVisCost(Aspect aspect, int rawCost) {
|
||||
if (rawCost <= 0 || aspect == null) return 0;
|
||||
return Math.max(0, Math.round(rawCost * getConsumptionModifier(aspect, true)));
|
||||
}
|
||||
|
||||
private boolean hasEnoughVis(AspectList cost) {
|
||||
if (cost == null || cost.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
var wandInv = this.craftingInventoryHost.getSubInventory(ArcaneCraftingTerminalPart.INV_WAND);
|
||||
var wandStack = wandInv.getStackInSlot(0);
|
||||
if (wandStack.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (!(wandStack.getItem() instanceof TCFunctionalItems.WandCastingItem wand)) {
|
||||
return false;
|
||||
}
|
||||
var centivisCost = new AspectList();
|
||||
for (var aspect : cost.aspects()) {
|
||||
centivisCost.add(aspect, cost.amount(aspect) * CENTIVIS);
|
||||
}
|
||||
return wand.consumeVisCost(wandStack, getPlayerInventory().player, centivisCost, false, true);
|
||||
var wand = craftingInventoryHost.getSubInventory(ArcaneCraftingTerminalPart.INV_WAND).getStackInSlot(0);
|
||||
return ArcaneTerminalRecipeState.hasEnoughVis(wand, cost, getPlayerInventory().player);
|
||||
}
|
||||
|
||||
private void updateCurrentRecipeAndOutput(boolean forceUpdate) {
|
||||
private void updateCurrentRecipeAndOutput() {
|
||||
var player = getPlayerInventory().player;
|
||||
var level = player.level();
|
||||
|
||||
boolean foundArcane = false;
|
||||
AspectList requiredAspects = null;
|
||||
|
||||
if (level.getServer() != null) {
|
||||
var craftContainer = this.craftingInventoryHost.getSubInventory(ArcaneCraftingTerminalPart.INV_CRAFTING).toContainer();
|
||||
|
||||
ItemStack arcaneResult = ThaumcraftCraftingManager.findMatchingArcaneRecipe(craftContainer, player);
|
||||
|
||||
if (!arcaneResult.isEmpty()) {
|
||||
requiredAspects = ThaumcraftCraftingManager.findMatchingArcaneRecipeAspects(craftContainer, player);
|
||||
foundArcane = true;
|
||||
|
||||
if (hasEnoughVis(requiredAspects)) {
|
||||
resultSlot.setDisplayedCraftingOutput(arcaneResult);
|
||||
} else {
|
||||
resultSlot.setDisplayedCraftingOutput(ItemStack.EMPTY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundArcane) {
|
||||
var testItems = new ArrayList<ItemStack>(this.craftingSlots.length);
|
||||
for (var craftingSlot : this.craftingSlots) {
|
||||
testItems.add(craftingSlot.getItem().copy());
|
||||
}
|
||||
var testInput = CraftingInput.of(3, 3, testItems);
|
||||
var recipeHolder = level.getRecipeManager().getRecipeFor(RecipeType.CRAFTING, testInput, level);
|
||||
if (recipeHolder.isPresent()) {
|
||||
ItemStack result = recipeHolder.get().value().assemble(testInput, level.registryAccess());
|
||||
resultSlot.setDisplayedCraftingOutput(result);
|
||||
} else {
|
||||
// 客户端不清空产物槽,@GuiSync 会同步服务端的正确状态
|
||||
if (!level.isClientSide()) {
|
||||
resultSlot.setDisplayedCraftingOutput(ItemStack.EMPTY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundArcane) {
|
||||
// 服务端设置 @GuiSync 字段;客户端不应覆盖来自服务端的同步值
|
||||
if (level.isClientSide()) {
|
||||
return;
|
||||
}
|
||||
this.hasValidRecipe = true;
|
||||
resultSlot.setRequiredAspects(requiredAspects);
|
||||
var wandInv = this.craftingInventoryHost.getSubInventory(ArcaneCraftingTerminalPart.INV_WAND);
|
||||
var ws = wandInv.getStackInSlot(0);
|
||||
resultSlot.setWandStack(ws);
|
||||
|
||||
if (requiredAspects != null && requiredAspects.size() > 0) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Map.Entry<Aspect, Integer> entry : requiredAspects.aspects.entrySet()) {
|
||||
if (!sb.isEmpty()) sb.append(",");
|
||||
// 存折扣后数值(GUI 显示实际所需 vis,含法杖 + 装备 + 饰品减免)
|
||||
sb.append(entry.getKey().getTag()).append("=")
|
||||
.append(getDiscountedVisCost(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
this.requiredAspectsData = sb.toString();
|
||||
} else {
|
||||
this.requiredAspectsData = "";
|
||||
}
|
||||
} else {
|
||||
if (level.isClientSide()) {
|
||||
return;
|
||||
}
|
||||
this.requiredAspectsData = "";
|
||||
this.hasValidRecipe = false;
|
||||
resultSlot.setRequiredAspects(null);
|
||||
resultSlot.setWandStack(ItemStack.EMPTY);
|
||||
var grid = craftingInventoryHost.getSubInventory(ArcaneCraftingTerminalPart.INV_CRAFTING);
|
||||
var wand = craftingInventoryHost.getSubInventory(ArcaneCraftingTerminalPart.INV_WAND).getStackInSlot(0);
|
||||
var match = ArcaneTerminalRecipeState.resolve(grid, wand, player);
|
||||
// 客户端不清空服务端同步的奥术结果。
|
||||
if (!player.level().isClientSide() || !match.output().isEmpty()) {
|
||||
resultSlot.setDisplayedCraftingOutput(match.output());
|
||||
}
|
||||
if (player.level().isClientSide()) return;
|
||||
hasValidRecipe = match.arcane();
|
||||
resultSlot.setRequiredAspects(match.cost());
|
||||
resultSlot.setWandStack(match.arcane() ? wand : ItemStack.EMPTY);
|
||||
requiredAspectsData = match.arcane()
|
||||
? ArcaneTerminalRecipeState.displayedCosts(wand, match.cost(), player) : "";
|
||||
}
|
||||
|
||||
public Map<String, Integer> getParsedAspects() {
|
||||
Map<String, Integer> map = new LinkedHashMap<>();
|
||||
if (requiredAspectsData.isEmpty()) return map;
|
||||
for (String part : requiredAspectsData.split(",")) {
|
||||
String[] kv = part.split("=");
|
||||
if (kv.length == 2) {
|
||||
try {
|
||||
map.put(kv[0], Integer.parseInt(kv[1]));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
return ArcaneTerminalRecipeState.parseCosts(requiredAspectsData);
|
||||
}
|
||||
|
||||
// ========== JEI 配方转移支持 ==========
|
||||
|
||||
@@ -44,14 +44,17 @@ public class ContainerKnowledgeInscriber extends AbstractContainerMenu {
|
||||
Enabled_Delete
|
||||
}
|
||||
|
||||
public static final int BUTTON_SAVE_DELETE = 0;
|
||||
public static final int BUTTON_CLEAR_GRID = 1;
|
||||
|
||||
private static final int MAXIMUM_PATTERNS = HandlerKnowledgeCore.MAXIMUM_STORED_PATTERNS;
|
||||
|
||||
private static final int PLAYER_INV_Y = 160;
|
||||
private static final int HOTBAR_Y = 218;
|
||||
private static final int PLAYER_INV_X = 8;
|
||||
|
||||
private static final int KCORE_SLOT_X = 186;
|
||||
private static final int KCORE_SLOT_Y = 8;
|
||||
private static final int KCORE_SLOT_X = 145;
|
||||
private static final int KCORE_SLOT_Y = 121;
|
||||
|
||||
private static final int PATTERN_SLOT_X = 26;
|
||||
private static final int PATTERN_SLOT_Y = 18;
|
||||
@@ -59,14 +62,14 @@ public class ContainerKnowledgeInscriber extends AbstractContainerMenu {
|
||||
private static final int PATTERN_COLS = 7;
|
||||
private static final int PATTERN_SPACING = 18;
|
||||
|
||||
private static final int CRAFTING_SLOT_X = 26;
|
||||
private static final int CRAFTING_SLOT_X = 16;
|
||||
private static final int CRAFTING_SLOT_Y = 90;
|
||||
private static final int CRAFTING_ROWS = 3;
|
||||
private static final int CRAFTING_COLS = 3;
|
||||
private static final int CRAFTING_GRID_SIZE = 9;
|
||||
private static final int CRAFTING_SPACING = 18;
|
||||
|
||||
private static final int RESULT_SLOT_X = 116;
|
||||
private static final int RESULT_SLOT_X = 105;
|
||||
private static final int RESULT_SLOT_Y = 108;
|
||||
|
||||
private final HandlerKnowledgeCore kCoreHandler = new HandlerKnowledgeCore();
|
||||
@@ -415,7 +418,8 @@ public class ContainerKnowledgeInscriber extends AbstractContainerMenu {
|
||||
}
|
||||
activeRecipe = null;
|
||||
resultInventory.setStackInSlot(0, ItemStack.EMPTY);
|
||||
sendSaveState();
|
||||
// Clearing the ghost recipe has the same predictable button state on both sides.
|
||||
saveStateSlot.set(getSaveState().ordinal());
|
||||
}
|
||||
|
||||
public CoreSaveState getCurrentSaveState() {
|
||||
@@ -517,11 +521,13 @@ public class ContainerKnowledgeInscriber extends AbstractContainerMenu {
|
||||
|
||||
@Override
|
||||
public boolean clickMenuButton(Player player, int id) {
|
||||
if (id == 0) {
|
||||
if (!stillValid(player)) return false;
|
||||
if (id == BUTTON_SAVE_DELETE) {
|
||||
onSaveDelete();
|
||||
return true;
|
||||
} else if (id == 1) {
|
||||
} else if (id == BUTTON_CLEAR_GRID) {
|
||||
onClearGrid();
|
||||
broadcastChanges();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -555,7 +561,11 @@ public class ContainerKnowledgeInscriber extends AbstractContainerMenu {
|
||||
|
||||
@Override
|
||||
public boolean stillValid(Player player) {
|
||||
return true;
|
||||
if (tile == null) return true; // Client menus do not carry the server block entity.
|
||||
return !tile.isRemoved() && tile.getLevel() == player.level()
|
||||
&& player.level().getBlockEntity(tile.getBlockPos()) == tile
|
||||
&& player.distanceToSqr(tile.getBlockPos().getX() + 0.5,
|
||||
tile.getBlockPos().getY() + 0.5, tile.getBlockPos().getZ() + 0.5) <= 64;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,224 +1,107 @@
|
||||
package thaumicenergistics.common.container;
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.networking.energy.IEnergySource;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.stacks.AEKey;
|
||||
import appeng.api.storage.MEStorage;
|
||||
import appeng.api.storage.StorageHelper;
|
||||
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import thaumcraft.api.aspects.IEssentiaContainerItem;
|
||||
import thaumcraft.common.items.JarBlockItem;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.tc.ThEEssentiaContainers;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaItemContainers;
|
||||
import thaumicenergistics.common.integration.tc.TCReflection;
|
||||
import net.minecraft.world.item.Item;
|
||||
import thaumicenergistics.common.integration.tc.ThEEssentiaContainers;
|
||||
|
||||
/**
|
||||
* 源质容器 ↔ ME 网络通用存取逻辑(服务端)。
|
||||
* <p>
|
||||
* 与具体菜单解耦:调用方(源质终端覆写、或 ME 终端 mixin)只需提供
|
||||
* storage / energySource / actionSource / player / 物品栈,本类完成
|
||||
* 罐子与安瓿的装罐、存入网络操作。
|
||||
* <ul>
|
||||
* <li>取出(装罐):网络有源质 → 装入手持空罐(有多少装多少,最多 64)/ 空安瓿(固定 8)。</li>
|
||||
* <li>存入:手持/点击的罐子或安瓿 → 源质注入网络;罐子留空罐,安瓿返回空 glass_phial(不消失)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
/** 服务端真实容器存取;实际转移多少就更新多少,不依赖网络反向回滚。 */
|
||||
public final class EssentiaFillHelper {
|
||||
|
||||
private EssentiaFillHelper() {}
|
||||
|
||||
/** 玻璃安瓿固定容量(TC 原版:8 源质/支)。 */
|
||||
public static final int PHIAL_CAPACITY = 8;
|
||||
/** 罐子容量(TC 原版:64 源质/罐)。 */
|
||||
public static final int JAR_CAPACITY = 64;
|
||||
|
||||
/**
|
||||
* 右键网络源质条目装罐:从网络提取源质,装入手持的源质罐子或玻璃安瓿。
|
||||
*
|
||||
* @return true = 处理成功(装罐/装安瓿),false = 无法处理
|
||||
*/
|
||||
private EssentiaFillHelper() {
|
||||
}
|
||||
|
||||
public static boolean fillContainerFromGrid(MEStorage storage, IEnergySource energySource,
|
||||
IActionSource actionSource, Player player,
|
||||
ItemStack carried, ResourceLocation aspectId) {
|
||||
if (carried.isEmpty() || aspectId == null) {
|
||||
IActionSource actionSource, Player player, ItemStack source, ResourceLocation aspectId) {
|
||||
var aspect = TCReflection.findAspectById(aspectId);
|
||||
if (source.isEmpty() || aspect == null || !ThEEssentiaContainers.isEssentiaContainer(source)
|
||||
|| !EssentiaItemContainers.contents(source).isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
AEKey key = AEssentiaKey.of(aspectId);
|
||||
if (key == null) {
|
||||
int capacity = ThEEssentiaContainers.isJar(source) ? JAR_CAPACITY : PHIAL_CAPACITY;
|
||||
var key = AEssentiaKey.of(aspectId);
|
||||
long available = StorageHelper.poweredExtraction(
|
||||
energySource, storage, key, capacity, actionSource, Actionable.SIMULATE);
|
||||
if (available <= 0 || (capacity == PHIAL_CAPACITY && available < capacity)) {
|
||||
return false;
|
||||
}
|
||||
long amountInGrid = storage.getAvailableStacks().get(key);
|
||||
if (amountInGrid <= 0) {
|
||||
// Keep the actual source item (including a void jar) and components across network callbacks.
|
||||
ItemStack template = source.copyWithCount(1);
|
||||
// 固定安瓿不能修改内容,先验证通用安瓿能够保存实际转移量。
|
||||
var planned = new AspectList().add(aspect, (int) available);
|
||||
if (EssentiaItemContainers.withContents(template, planned) == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 玻璃安瓿:消耗空安瓿 → 得到装满安瓿(固定 8 源质)
|
||||
if (carried.getItem() == BuiltInRegistries.ITEM.get(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", "glass_phial"))) {
|
||||
if (amountInGrid < PHIAL_CAPACITY) {
|
||||
return false;
|
||||
}
|
||||
long extracted = storage.extract(key, PHIAL_CAPACITY, Actionable.MODULATE, actionSource);
|
||||
if (extracted < PHIAL_CAPACITY) {
|
||||
if (extracted > 0) {
|
||||
storage.insert(key, extracted, Actionable.MODULATE, actionSource);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
carried.shrink(1);
|
||||
// 得到装满安瓿并放入背包(装好后自动放入背包)
|
||||
ItemStack filled = filledPhialStack(aspectId.getPath());
|
||||
if (!player.getInventory().add(filled)) {
|
||||
player.drop(filled, false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 罐子(JarBlockItem):每次只装 1 个空罐(手堆叠 -1,背包得 1 满罐)。
|
||||
// 其余 IEssentiaContainerItem(天域之华等)不参与装罐。
|
||||
if (!ThEEssentiaContainers.isJar(carried)) {
|
||||
return false;
|
||||
}
|
||||
IEssentiaContainerItem container = (IEssentiaContainerItem) carried.getItem();
|
||||
AspectList existing = container.getAspects(carried);
|
||||
if (existing != null && !existing.isEmpty()) {
|
||||
return false; // 罐子非空,不能装
|
||||
}
|
||||
// 部分取出:网络有多少装多少(最多 JAR_CAPACITY 64);不足 64 也能装,不再整组拒绝
|
||||
long toExtract = Math.min(amountInGrid, JAR_CAPACITY);
|
||||
long extracted = storage.extract(key, toExtract, Actionable.MODULATE, actionSource);
|
||||
long extracted = StorageHelper.poweredExtraction(
|
||||
energySource, storage, key, available, actionSource);
|
||||
if (extracted <= 0) {
|
||||
return false;
|
||||
}
|
||||
Aspect aspect = Aspect.getAspect(aspectId.getPath());
|
||||
if (aspect == null) {
|
||||
storage.insert(key, extracted, Actionable.MODULATE, actionSource);
|
||||
return false;
|
||||
}
|
||||
// 生成 1 个满罐:必须先 copy(在 shrink 之前),因为 count==1 的堆叠 shrink 后
|
||||
// 会变成空堆叠,ItemStack.copy() 对空堆叠直接返回全局 EMPTY 单例,setCount(1)
|
||||
// 会污染该常量产生"空气幽灵堆叠",罐子因此消失。copyWithCount(1) 生成独立副本,
|
||||
// setAspects 只影响这一个,不影响原堆叠。
|
||||
ItemStack filledJar = carried.copyWithCount(1);
|
||||
// 手堆叠 -1
|
||||
carried.shrink(1);
|
||||
AspectList newAspects = new AspectList();
|
||||
newAspects.add(aspect, (int) extracted);
|
||||
container.setAspects(filledJar, newAspects);
|
||||
if (!player.getInventory().add(filledJar)) {
|
||||
player.drop(filledJar, false);
|
||||
var filled = EssentiaItemContainers.withContents(template,
|
||||
new AspectList().add(aspect, (int) extracted));
|
||||
if (filled == null) {
|
||||
throw new IllegalStateException("Validated essentia container cannot retain extracted contents");
|
||||
}
|
||||
source.shrink(1);
|
||||
give(player, filled);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把源质容器物品中的源质注入 ME 原生存储,返回处理后的物品栈。
|
||||
* 堆叠中每个容器的源质相同(NBT 共享),按"单个量 × 堆叠数"一次注入;
|
||||
* 全部注入成功才消耗容器,否则保留原堆叠,避免源质凭空消失。
|
||||
* <p>
|
||||
* 罐子抽干后留空罐(可重复使用);安瓿抽干后返回空 glass_phial(不消失)。
|
||||
*
|
||||
* @return null = 非源质容器(未处理,调用方应走原逻辑);
|
||||
* 原 stack = 未注入(网络满/能量不足)或部分处理保留;
|
||||
* 空罐 = 罐子全部抽干(可重复使用);
|
||||
* glass_phial 空安瓿 = 安瓿全部抽干(返回空安瓿,不再消耗掉)
|
||||
*/
|
||||
@Nullable
|
||||
public static ItemStack extractContainerContent(MEStorage storage, IEnergySource energySource,
|
||||
IActionSource actionSource, ItemStack stack) {
|
||||
// 仅要素安瓿/要素罐子(天域之华、水晶等其他 IEssentiaContainerItem 一律不处理)
|
||||
if (!ThEEssentiaContainers.isEssentiaContainer(stack)) {
|
||||
return null;
|
||||
public static ItemStack depositContainerContent(MEStorage storage, IEnergySource energySource,
|
||||
IActionSource actionSource, Player player, ItemStack source) {
|
||||
while (!source.isEmpty()) {
|
||||
var remaining = EssentiaItemContainers.contents(source);
|
||||
if (remaining.isEmpty() || EssentiaItemContainers.withContents(source, remaining) == null) {
|
||||
break;
|
||||
}
|
||||
if (!(stack.getItem() instanceof IEssentiaContainerItem container)) {
|
||||
return stack; // 空玻璃安瓿:无源质可存
|
||||
}
|
||||
int count = stack.getCount();
|
||||
if (count <= 0) {
|
||||
return stack;
|
||||
}
|
||||
AspectList aspects = container.getAspects(stack);
|
||||
if (aspects == null || aspects.isEmpty()) {
|
||||
return stack;
|
||||
}
|
||||
|
||||
// 阶段1:预检(SIMULATE 无副作用)——网络必须能完整容纳全部源质才继续;
|
||||
// 任一项放不下则整个堆叠原样保留,避免"部分注入后罐子被消耗、剩余源质凭空消失"。
|
||||
Aspect[] aspectArr = aspects.getAspects();
|
||||
ResourceLocation[] ids = new ResourceLocation[aspectArr.length];
|
||||
long[] totals = new long[aspectArr.length];
|
||||
int n = 0;
|
||||
for (Aspect aspect : aspectArr) {
|
||||
if (aspect == null) {
|
||||
boolean moved = false;
|
||||
for (var aspect : remaining.getAspects()) {
|
||||
var id = TCReflection.getAspectId(aspect);
|
||||
if (id == null) {
|
||||
continue;
|
||||
}
|
||||
int perItem = aspects.getAmount(aspect);
|
||||
if (perItem <= 0) {
|
||||
continue;
|
||||
}
|
||||
ResourceLocation aspectId = TCReflection.getAspectId(aspect);
|
||||
if (aspectId == null) {
|
||||
continue;
|
||||
}
|
||||
long total = (long) perItem * count;
|
||||
if (storage.insert(AEssentiaKey.of(aspectId), total,
|
||||
Actionable.SIMULATE, actionSource) < total) {
|
||||
return stack; // 网络容量不足:完全不注入,罐子/安瓿原样保留
|
||||
}
|
||||
ids[n] = aspectId;
|
||||
totals[n] = total;
|
||||
n++;
|
||||
}
|
||||
if (n == 0) {
|
||||
return stack;
|
||||
}
|
||||
|
||||
// 阶段2:执行注入(预检已保证容量;若能量不足导致未完全注入,则回滚本次及此前
|
||||
// 已注入的量并保留罐子,保证网络数量与罐子状态一致——不丢源质也不复制源质)
|
||||
for (int i = 0; i < n; i++) {
|
||||
int offered = remaining.getAmount(aspect);
|
||||
long injected = StorageHelper.poweredInsert(
|
||||
energySource, storage, AEssentiaKey.of(ids[i]), totals[i], actionSource);
|
||||
if (injected < totals[i]) {
|
||||
energySource, storage, AEssentiaKey.of(id), offered, actionSource);
|
||||
if (injected > 0) {
|
||||
storage.insert(AEssentiaKey.of(ids[i]), injected,
|
||||
Actionable.MODULATE, actionSource);
|
||||
remaining.remove(aspect, (int) injected);
|
||||
moved = true;
|
||||
}
|
||||
for (int j = 0; j < i; j++) {
|
||||
storage.insert(AEssentiaKey.of(ids[j]), totals[j],
|
||||
Actionable.MODULATE, actionSource);
|
||||
}
|
||||
return stack;
|
||||
if (!moved) {
|
||||
break;
|
||||
}
|
||||
var replacement = EssentiaItemContainers.withContents(source, remaining);
|
||||
if (replacement == null) {
|
||||
throw new IllegalStateException("Validated essentia container cannot retain remaining contents");
|
||||
}
|
||||
if (source.getCount() == 1) {
|
||||
return replacement;
|
||||
}
|
||||
// 拆出内容不同的一个容器,其余堆叠保持原组件和数量。
|
||||
source.shrink(1);
|
||||
give(player, replacement);
|
||||
if (!remaining.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
// 全部注入成功则消耗整个堆叠(罐子留空罐、安瓿返回空 glass_phial)
|
||||
if (stack.getItem() instanceof JarBlockItem) {
|
||||
return new ItemStack(stack.getItem());
|
||||
private static void give(Player player, ItemStack stack) {
|
||||
if (!player.getInventory().add(stack)) {
|
||||
player.drop(stack, false);
|
||||
}
|
||||
// 安瓿:返回空安瓿(glass_phial),不直接消失
|
||||
ItemStack emptyPhial = new ItemStack(BuiltInRegistries.ITEM.get(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", "glass_phial")), count);
|
||||
return emptyPhial;
|
||||
}
|
||||
|
||||
/** 生成装满的安瓿(phial_of_essentia_<tag>),与 TC JarBlock.filledPhialStack 一致。 */
|
||||
private static ItemStack filledPhialStack(String aspectTag) {
|
||||
ResourceLocation id = ResourceLocation.fromNamespaceAndPath(
|
||||
"thaumcraft", "phial_of_essentia_" + aspectTag);
|
||||
Item item = BuiltInRegistries.ITEM.getOptional(id)
|
||||
.orElse(BuiltInRegistries.ITEM.get(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", "glass_phial")));
|
||||
return new ItemStack(item);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package thaumicenergistics.common.container;
|
||||
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
@@ -22,8 +23,8 @@ public class GuiKnowledgeInscriber extends AbstractContainerScreen<ContainerKnow
|
||||
private static final ResourceLocation BUTTON_TEX = ResourceLocation.fromNamespaceAndPath(
|
||||
ThaumicEnergistics.MODID, "textures/gui/button.png");
|
||||
|
||||
// 主区宽度 175(中轴线 87.5,主区对称居中);知识核心槽在右侧单独渲染(x=176~209 边栏),不计入主区宽度。
|
||||
private static final int GUI_WIDTH = 175;
|
||||
// All slots now fit inside the 176-pixel main panel, including the knowledge core.
|
||||
private static final int GUI_WIDTH = 176;
|
||||
private static final int GUI_HEIGHT = 244;
|
||||
|
||||
private Button saveButton;
|
||||
@@ -45,12 +46,10 @@ public class GuiKnowledgeInscriber extends AbstractContainerScreen<ContainerKnow
|
||||
int left = (width - imageWidth) / 2;
|
||||
int top = (height - imageHeight) / 2;
|
||||
|
||||
// 保存/删除样板按钮:放预览产物槽(结果槽 116,108)上方,等比 32×13。
|
||||
// 按钮中心与结果槽中心(x=125)关于同一 y 轴对称 → 按钮 x = 125-16 = 109。
|
||||
// 材质 button.png:常态 (0,0,32,13),悬停/按下 (0,15,32,12)。
|
||||
// Center the status/save/delete button above the knowledge core slot (145 + 8).
|
||||
saveButton = new Button(
|
||||
left + 109, top + 90, 32, 13, Component.empty(),
|
||||
btn -> this.minecraft.gameMode.handleInventoryButtonClick(this.menu.containerId, 0),
|
||||
left + 137, top + 103, 32, 13, Component.empty(),
|
||||
btn -> this.minecraft.gameMode.handleInventoryButtonClick(this.menu.containerId, ContainerKnowledgeInscriber.BUTTON_SAVE_DELETE),
|
||||
b -> Component.empty()) {
|
||||
@Override
|
||||
protected void renderWidget(GuiGraphics g, int mx, int my, float pt) {
|
||||
@@ -71,6 +70,25 @@ public class GuiKnowledgeInscriber extends AbstractContainerScreen<ContainerKnow
|
||||
}
|
||||
};
|
||||
addRenderableWidget(saveButton);
|
||||
|
||||
// The 8x8 cross is already part of the supplied texture; keep its exact appearance.
|
||||
Button clearButton = new Button(left + 71, top + 89, 8, 8,
|
||||
Component.translatable("thaumicenergistics.gui.knowledge_inscriber.clear_grid"), btn -> {
|
||||
menu.onClearGrid();
|
||||
saveState = menu.getCurrentSaveState();
|
||||
updateSaveButton();
|
||||
minecraft.gameMode.handleInventoryButtonClick(menu.containerId,
|
||||
ContainerKnowledgeInscriber.BUTTON_CLEAR_GRID);
|
||||
}, narration -> narration.get()) {
|
||||
@Override
|
||||
protected void renderWidget(GuiGraphics g, int mx, int my, float pt) {
|
||||
if (isHoveredOrFocused()) {
|
||||
g.fill(getX(), getY(), getX() + width, getY() + height, 0x40FFFFFF);
|
||||
}
|
||||
}
|
||||
};
|
||||
clearButton.setTooltip(Tooltip.create(Component.translatable("thaumicenergistics.gui.knowledge_inscriber.clear_grid")));
|
||||
addRenderableWidget(clearButton);
|
||||
// 立即设置按钮文字/激活(F11 全屏切换会重建按钮,init 里必须重设,否则文字丢失)
|
||||
updateSaveButton();
|
||||
}
|
||||
@@ -112,10 +130,7 @@ public class GuiKnowledgeInscriber extends AbstractContainerScreen<ContainerKnow
|
||||
protected void renderBg(GuiGraphics g, float pt, int mx, int my) {
|
||||
int x = (width - imageWidth) / 2;
|
||||
int y = (height - imageHeight) / 2;
|
||||
// 主区(0~175)对称居中
|
||||
g.blit(TEX, x, y, 0, 0, GUI_WIDTH, imageHeight);
|
||||
// 右侧知识核心槽边栏(x=176~209)单独渲染,不占主区宽度
|
||||
g.blit(TEX, x + 176, y, 176, 0, 34, imageHeight);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package thaumicenergistics.common.container;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
import appeng.api.inventories.ISegmentedInventory;
|
||||
import appeng.api.networking.IGridNode;
|
||||
import appeng.api.upgrades.IUpgradeInventory;
|
||||
|
||||
/**
|
||||
* 奥术终端宿主契约:统一独立无线奥术终端与 AE2WT 通用终端奥术模式两种宿主,
|
||||
* 供 {@code ContainerArcaneCraftingTerminal} 识别 vis 充能、奇点槽与法杖保存能力,
|
||||
* 替代对具体宿主类的 instanceof 判断。
|
||||
* <p>
|
||||
* 奇点子库存 id 由各宿主自报(独立宿主为本模组命名空间,AE2WT 宿主为
|
||||
* {@code ae2wtlib:singularity} 字符串软查,避免可选 API 类型泄漏到普通加载路径);
|
||||
* 返回 null 表示无奇点槽。
|
||||
*/
|
||||
public interface IArcaneTerminalInventoryHost extends ISegmentedInventory {
|
||||
|
||||
/** ae2wtlib modid(奇点准入等 ModList 守护用)。 */
|
||||
String AE2WTLIB_MODID = "ae2wtlib";
|
||||
|
||||
/** 升级卡库存(vis 连接卡检测;与 AE2 IUpgradeableObject 同名方法兼容)。 */
|
||||
IUpgradeInventory getUpgrades();
|
||||
|
||||
/** 网络操作节点(vis 充能源;与 AE2 IActionHost 同名方法兼容)。 */
|
||||
@Nullable
|
||||
IGridNode getActionableNode();
|
||||
|
||||
/** 法杖槽内容写回终端物品组件(菜单驱动充能后显式调用)。 */
|
||||
void saveWandInv();
|
||||
|
||||
/** Refresh a passive connection without charging menu idle power a second time. */
|
||||
void refreshConnection();
|
||||
|
||||
/** 奇点子库存 id(getSubInventory 寻址);null 表示本宿主无奇点槽。 */
|
||||
@Nullable
|
||||
ResourceLocation getSingularityInvId();
|
||||
|
||||
/**
|
||||
* 奇点槽语义分支:AE2WT 宿主返回 true——奇点槽挂 ae2wtlib 官方 SINGULARITY 组
|
||||
* (滚动升级面板取槽时要求奇点居首且独立成组,并自带量子桥卡门控显隐);
|
||||
* 独立无线宿主保持默认 false——奇点槽并入 UPGRADE 组由普通升级面板渲染。
|
||||
* 经契约虚调用分发,菜单侧不引用 ae2wtlib 类型(该宿主能实例化即证明 ae2wtlib 在场)。
|
||||
*/
|
||||
default boolean useAE2WTSingularitySemantics() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package thaumicenergistics.common.container;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import appeng.api.networking.energy.IEnergySource;
|
||||
import appeng.api.networking.security.IActionHost;
|
||||
import appeng.api.storage.MEStorage;
|
||||
import appeng.menu.me.common.MEStorageMenu;
|
||||
|
||||
/**
|
||||
* 从 {@link MEStorageMenu} 宿主的公开接口取得存储与能量源,
|
||||
* 替代原 MixinMEStorageMenuAccessors 注入的私有字段访问器。
|
||||
* 取得规则与 AE2 菜单构造器一致:存储=宿主 getInventory()(要求非空);
|
||||
* 能量源=宿主实现 IEnergySource 时优先用宿主(无线终端电池扣费语义),
|
||||
* 否则宿主实现 IActionHost 时动态代理——每次扣费重新查询节点与网格,
|
||||
* 不捕获首次结果,保证拆线/重连/网络合并后不使用旧网格;均不成立时用空源。
|
||||
* 不保存世界数据,不引入数据组件,不建立菜单缓存。
|
||||
*/
|
||||
public final class MenuResources {
|
||||
private MenuResources() {
|
||||
}
|
||||
|
||||
public static MEStorage getStorage(MEStorageMenu menu) {
|
||||
Objects.requireNonNull(menu, "menu");
|
||||
return Objects.requireNonNull(
|
||||
menu.getHost().getInventory(), "host inventory is null");
|
||||
}
|
||||
|
||||
public static IEnergySource getEnergySource(MEStorageMenu menu) {
|
||||
Objects.requireNonNull(menu, "menu");
|
||||
var host = menu.getHost();
|
||||
|
||||
if (host instanceof IEnergySource energySource) {
|
||||
return energySource;
|
||||
}
|
||||
|
||||
if (host instanceof IActionHost actionHost) {
|
||||
return (amount, mode, multiplier) -> {
|
||||
var node = actionHost.getActionableNode();
|
||||
if (node == null || !node.isActive()) {
|
||||
return 0.0;
|
||||
}
|
||||
var grid = node.getGrid();
|
||||
if (grid == null) {
|
||||
return 0.0;
|
||||
}
|
||||
return grid.getEnergyService().extractAEPower(
|
||||
amount, mode, multiplier);
|
||||
};
|
||||
}
|
||||
|
||||
return IEnergySource.empty();
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package thaumicenergistics.common.container;
|
||||
|
||||
import appeng.api.networking.energy.IEnergySource;
|
||||
import appeng.api.storage.MEStorage;
|
||||
|
||||
/**
|
||||
* 由 {@code MixinMEStorageMenuAccessors} 注入到 {@code MEStorageMenu} 的访问器接口。
|
||||
* <p>
|
||||
* 编译期接口存在、运行期目标类实现,调用方(如网络包处理)通过
|
||||
* {@code instanceof ThEEssentiaMenuAccess} 安全访问 ME 存储与能量源。
|
||||
* <p>
|
||||
* 注意:必须放在非 mixin 包(mixin 包 {@code thaumicenergistics.mixins.*} 的类
|
||||
* 禁止被普通类直接引用)。
|
||||
*/
|
||||
public interface ThEEssentiaMenuAccess {
|
||||
|
||||
/** ME 存储(对应 MEStorageMenu.storage)。 */
|
||||
MEStorage thE_getStorage();
|
||||
|
||||
/** 能量源(对应 MEStorageMenu.energySource)。 */
|
||||
IEnergySource thE_getEnergySource();
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package thaumicenergistics.common.crafting;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import appeng.api.crafting.IPatternDetails;
|
||||
import appeng.api.stacks.AEKey;
|
||||
import appeng.api.stacks.AEItemKey;
|
||||
import appeng.api.stacks.GenericStack;
|
||||
import appeng.api.stacks.KeyCounter;
|
||||
import thaumcraft.api.crafting.IArcaneRecipe;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
|
||||
public final class ArcaneAssemblerPattern implements IPatternDetails {
|
||||
private static final net.minecraft.resources.ResourceLocation PRIMORDIAL_PEARL_ID =
|
||||
net.minecraft.resources.ResourceLocation.fromNamespaceAndPath("thaumcraft", "primordial_pearl");
|
||||
private final AEItemKey definition;
|
||||
private final IArcaneRecipe recipe;
|
||||
private final AspectList aspects;
|
||||
private final ItemStack resultStack;
|
||||
private final IInput[] inputs;
|
||||
private final String research;
|
||||
/** 3×3 配方网格(知识核心存储的 9 格材料,GUI 配方预览用)。 */
|
||||
private final ItemStack[] grid;
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks) {
|
||||
this(definition, recipe, aspects, resultStack, inputStacks, null, null, null);
|
||||
}
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks, String research) {
|
||||
this(definition, recipe, aspects, resultStack, inputStacks, research, null, null);
|
||||
}
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks, String research, ItemStack[] grid) {
|
||||
this(definition, recipe, aspects, resultStack, inputStacks, research, grid, null);
|
||||
}
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks, String research, ItemStack[] grid,
|
||||
List<GenericStack[]> inputAlternatives) {
|
||||
this.definition = definition;
|
||||
this.recipe = recipe;
|
||||
this.aspects = aspects;
|
||||
this.resultStack = resultStack;
|
||||
this.research = research;
|
||||
this.grid = grid;
|
||||
this.inputs = new IInput[inputStacks.size()];
|
||||
for (int i = 0; i < inputStacks.size(); i++) {
|
||||
GenericStack stack = inputStacks.get(i);
|
||||
// 通配变体组(tag 展开结果);null/单元素退化为精确匹配(与旧行为一致)
|
||||
GenericStack[] alts = (inputAlternatives != null && i < inputAlternatives.size()
|
||||
&& inputAlternatives.get(i) != null)
|
||||
? inputAlternatives.get(i)
|
||||
: new GenericStack[]{stack};
|
||||
this.inputs[i] = new IInput() {
|
||||
@Override
|
||||
public GenericStack[] getPossibleInputs() {
|
||||
return alts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getMultiplier() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(AEKey input, Level level) {
|
||||
if (!(input instanceof AEItemKey itemKey)) return false;
|
||||
for (GenericStack alt : alts) {
|
||||
if (alt.what() instanceof AEItemKey altKey && altKey.equals(itemKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public AEKey getRemainingKey(AEKey what) {
|
||||
// 元始珍珠作为"催化"原料:声明合成后它会返回网络(AE2 原生容器机制)。
|
||||
// 规划端据此按"每次 1 单"顺序模拟、执行端把珍珠计入 CPU waitingFor,
|
||||
// 机器合成完成把珍珠退回网络后 CPU 自动捕获续下一单——1 颗珍珠可连续多单。
|
||||
if (what instanceof AEItemKey itemKey
|
||||
&& itemKey.getItem() == BuiltInRegistries.ITEM.get(PRIMORDIAL_PEARL_ID)) {
|
||||
return what;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AEItemKey getDefinition() { return definition; }
|
||||
|
||||
@Override
|
||||
public IInput[] getInputs() { return inputs; }
|
||||
|
||||
@Override
|
||||
public List<GenericStack> getOutputs() {
|
||||
return List.of(new GenericStack(AEItemKey.of(resultStack), resultStack.getCount()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPushInputsToExternalInventory() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof ArcaneAssemblerPattern other)) return false;
|
||||
return definition != null && definition.equals(other.definition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return definition != null ? definition.hashCode() : 0;
|
||||
}
|
||||
|
||||
public IArcaneRecipe getRecipe() { return recipe; }
|
||||
public AspectList getAspects() { return aspects; }
|
||||
public ItemStack getResultStack() { return resultStack; }
|
||||
/** 3×3 配方网格(可能为 null/短数组,GUI 预览用)。 */
|
||||
@Nullable
|
||||
public ItemStack[] getGrid() { return grid; }
|
||||
/** 对应 TC 奥术配方的研究键;无研究要求/老数据时可能为 null。 */
|
||||
@Nullable
|
||||
public String getResearch() { return research; }
|
||||
|
||||
/** 在接收任务前校验 CPU 的真实材料;失败时保持所有输入不变。 */
|
||||
@Nullable
|
||||
public ItemStack[] materializeInputs(KeyCounter[] holders, Level level) {
|
||||
if (grid == null || holders.length != inputs.length) return null;
|
||||
ItemStack[] actual = new ItemStack[9];
|
||||
java.util.Arrays.fill(actual, ItemStack.EMPTY);
|
||||
int inputIndex = 0;
|
||||
for (int slot = 0; slot < grid.length && slot < actual.length; slot++) {
|
||||
if (grid[slot] == null || grid[slot].isEmpty()) continue;
|
||||
if (inputIndex >= inputs.length) return null;
|
||||
IInput input = inputs[inputIndex];
|
||||
ItemStack selected = ItemStack.EMPTY;
|
||||
for (var entry : holders[inputIndex]) {
|
||||
if (entry.getLongValue() <= 0) continue;
|
||||
if (!selected.isEmpty() || !(entry.getKey() instanceof AEItemKey key)
|
||||
|| !input.isValid(key, level) || entry.getLongValue() != grid[slot].getCount()) {
|
||||
return null;
|
||||
}
|
||||
selected = key.toStack(grid[slot].getCount());
|
||||
}
|
||||
if (selected.isEmpty()) return null;
|
||||
actual[slot] = selected;
|
||||
inputIndex++;
|
||||
}
|
||||
return inputIndex == inputs.length ? actual : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package thaumicenergistics.common.crafting;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
|
||||
/** 装配器当前订单拥有的材料、产物和执行阶段;沿用原存档键。 */
|
||||
public final class ArcaneCraftJob {
|
||||
private AspectList aspects = new AspectList();
|
||||
private ItemStack result = ItemStack.EMPTY;
|
||||
private ItemStack[] inputs = emptyGrid();
|
||||
private boolean produced;
|
||||
private final List<ItemStack> outputs = new ArrayList<>();
|
||||
|
||||
public AspectList aspects() { return aspects; }
|
||||
public ItemStack result() { return result; }
|
||||
public ItemStack[] inputs() { return inputs; }
|
||||
public boolean produced() { return produced; }
|
||||
public List<ItemStack> outputs() { return outputs; }
|
||||
|
||||
public void start(AspectList cost, ItemStack output, ItemStack[] actualInputs) {
|
||||
clear();
|
||||
aspects = cost.copy();
|
||||
result = output.copy();
|
||||
for (int i = 0; i < inputs.length && i < actualInputs.length; i++) {
|
||||
if (actualInputs[i] != null) inputs[i] = actualInputs[i].copy();
|
||||
}
|
||||
}
|
||||
|
||||
public void produce(List<ItemStack> retainedInputs) {
|
||||
if (produced) throw new IllegalStateException("Arcane order was already produced");
|
||||
outputs.add(result.copy());
|
||||
for (var retained : retainedInputs) outputs.add(retained.copy());
|
||||
produced = true;
|
||||
}
|
||||
|
||||
public void clearPreview() { inputs = emptyGrid(); }
|
||||
|
||||
public void clear() {
|
||||
aspects = new AspectList();
|
||||
result = ItemStack.EMPTY;
|
||||
inputs = emptyGrid();
|
||||
produced = false;
|
||||
outputs.clear();
|
||||
}
|
||||
|
||||
public void load(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
clear();
|
||||
result = ItemStack.parseOptional(registries, tag.getCompound("CurrentCraftResult"));
|
||||
aspects.readFromNBT(tag.getCompound("CurrentCraftAspects"));
|
||||
var grid = tag.getCompound("PreviewGrid");
|
||||
for (int i = 0; i < inputs.length; i++) inputs[i] = ItemStack.parseOptional(registries, grid.getCompound("g" + i));
|
||||
produced = tag.getBoolean("ResultProduced");
|
||||
for (var output : tag.getList("PendingCraftOutputs", Tag.TAG_COMPOUND)) {
|
||||
var stack = ItemStack.parseOptional(registries, (CompoundTag) output);
|
||||
if (!stack.isEmpty()) outputs.add(stack);
|
||||
}
|
||||
}
|
||||
|
||||
public void save(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
tag.putBoolean("ResultProduced", produced);
|
||||
tag.remove("CurrentCraftResult");
|
||||
if (!result.isEmpty()) tag.put("CurrentCraftResult", result.save(registries));
|
||||
var cost = new CompoundTag();
|
||||
aspects.writeToNBT(cost);
|
||||
tag.put("CurrentCraftAspects", cost);
|
||||
var grid = new CompoundTag();
|
||||
for (int i = 0; i < inputs.length; i++) if (!inputs[i].isEmpty()) grid.put("g" + i, inputs[i].save(registries));
|
||||
tag.put("PreviewGrid", grid);
|
||||
var pending = new ListTag();
|
||||
for (var output : outputs) if (!output.isEmpty()) pending.add(output.save(registries));
|
||||
tag.put("PendingCraftOutputs", pending);
|
||||
}
|
||||
|
||||
private static ItemStack[] emptyGrid() {
|
||||
var grid = new ItemStack[9];
|
||||
Arrays.fill(grid, ItemStack.EMPTY);
|
||||
return grid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package thaumicenergistics.common.crafting;
|
||||
|
||||
import appeng.api.crafting.IPatternDetails;
|
||||
import appeng.api.crafting.IPatternDetailsDecoder;
|
||||
import appeng.api.stacks.AEItemKey;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.CustomData;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import thaumicenergistics.common.integration.tc.ArcaneCraftingPattern;
|
||||
import thaumicenergistics.common.tiles.TileArcaneAssembler;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/** CPU 持久化使用完整样板定义,不能用产物物品代替不同配方的身份。 */
|
||||
public final class ArcanePatternDecoder implements IPatternDetailsDecoder {
|
||||
private static final String PATTERN = "ThEEncodedArcanePattern";
|
||||
|
||||
public static AEItemKey definition(ArcaneCraftingPattern pattern) {
|
||||
var stack = new ItemStack(ModItems.KNOWLEDGE_CORE.get());
|
||||
var data = new CompoundTag();
|
||||
data.put(PATTERN, pattern.writeToNBT(new CompoundTag()));
|
||||
stack.set(DataComponents.CUSTOM_DATA, CustomData.of(data));
|
||||
return AEItemKey.of(stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEncodedPattern(ItemStack stack) {
|
||||
var data = stack.get(DataComponents.CUSTOM_DATA);
|
||||
return stack.is(ModItems.KNOWLEDGE_CORE.get()) && data != null
|
||||
&& data.copyTag().contains(PATTERN, Tag.TAG_COMPOUND);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public IPatternDetails decodePattern(AEItemKey key, Level level) {
|
||||
// 旧存档样板内引用已删除物品时,上游(如 AE2LT rebuild)可能传入 null key,
|
||||
// 抛异常会导致整个供应器 BE 被 Skipping 丢数据,此处必须返回 null 而非抛出。
|
||||
if (key == null) return null;
|
||||
var stack = key.toStack();
|
||||
if (stack.isEmpty() || !isEncodedPattern(stack)) return null;
|
||||
try {
|
||||
var data = stack.get(DataComponents.CUSTOM_DATA).copyTag();
|
||||
var pattern = new ArcaneCraftingPattern(data.getCompound(PATTERN));
|
||||
return pattern.isPatternValid() ? TileArcaneAssembler.buildArcanePattern(pattern) : null;
|
||||
} catch (Exception e) {
|
||||
// 损坏样板隔离:解析失败只禁用该样板配方,不清槽位、不改原始 NBT。
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package thaumicenergistics.common.crafting;
|
||||
|
||||
import net.minecraft.util.RandomSource;
|
||||
|
||||
/** 概率之脑的抽奖数值与随机规则,独立于网格和方块生命周期。 */
|
||||
public final class ProbabilityBrainRules {
|
||||
private ProbabilityBrainRules() { }
|
||||
|
||||
// ===== 骰子数值(CE GachaOdds 定稿,用户可调) =====
|
||||
/** 最快的一次转动,也是赔率最好的一次。 */
|
||||
public static final int MIN_SECONDS = 30;
|
||||
/** 无加速卡时最慢的转动。 */
|
||||
public static final int LONGEST_SECONDS = 180;
|
||||
/** 每张加速卡把最长转动缩短的秒数。 */
|
||||
public static final int SECONDS_PER_CARD = 25;
|
||||
/** 加速卡最多把最长转动压到的秒数(第五张起不再变化)。 */
|
||||
public static final int LONGEST_WITH_CARDS = 80;
|
||||
/** 最快转动的给奖赔率。 */
|
||||
public static final double CHANCE_AT_MIN_SECONDS = 0.75;
|
||||
/** 最慢转动的给奖赔率。 */
|
||||
public static final double CHANCE_AT_LONGEST_SECONDS = 0.45;
|
||||
/** 给奖转动抽取次数下限。 */
|
||||
public static final int MIN_DRAWS = 5;
|
||||
/** 给奖转动抽取次数上限。 */
|
||||
public static final int MAX_DRAWS = 7;
|
||||
/** 单次抽取点数上限(1~3)。 */
|
||||
public static final int MAX_POINTS_PER_DRAW = 3;
|
||||
|
||||
/** 装这么多张卡时可能掷出的最长转动。 */
|
||||
public static int longestSeconds(int cards) {
|
||||
return Math.max(LONGEST_WITH_CARDS, LONGEST_SECONDS - SECONDS_PER_CARD * cards);
|
||||
}
|
||||
|
||||
/** 这个时长的转动给奖的赔率,只看时长。 */
|
||||
public static double payoutChance(int seconds) {
|
||||
double along = (double) (seconds - MIN_SECONDS) / (LONGEST_SECONDS - MIN_SECONDS);
|
||||
return CHANCE_AT_MIN_SECONDS + (CHANCE_AT_LONGEST_SECONDS - CHANCE_AT_MIN_SECONDS) * along;
|
||||
}
|
||||
|
||||
/** 掷出的一次转动:跑多少秒,给不给奖。 */
|
||||
public record Turn(int seconds, boolean pays) {}
|
||||
|
||||
/** 一次抽取定下两半:落到的时长决定这次转动的赔率。 */
|
||||
public static Turn roll(RandomSource random, int cards) {
|
||||
int seconds = MIN_SECONDS + random.nextInt(longestSeconds(cards) - MIN_SECONDS + 1);
|
||||
return new Turn(seconds, random.nextDouble() < payoutChance(seconds));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -12,9 +12,12 @@ import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.CustomData;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.fml.common.EventBusSubscriber;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import thaumcraft.common.entities.golem.ThaumcraftGolemEntity;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.items.ItemGolemWirelessBackpack;
|
||||
@@ -37,6 +40,16 @@ public final class GolemBackpackHandler {
|
||||
private static final String NBT_KEY_SKIN = "ThEBackpackSkin";
|
||||
/** NBT 键:Facade 物品序列化 */
|
||||
private static final String NBT_KEY_FACADE = "ThEBackpackFacade";
|
||||
/** 物品侧打包键:GolemItems.saveGolem/loadGolem Mixin 携带三键的 CUSTOM_DATA 子树 */
|
||||
public static final String STACK_DATA_KEY = "ThEGolemBackpack";
|
||||
/** 子树内键:连接目标 */
|
||||
private static final String STACK_KEY_LINK = "Link";
|
||||
/** 子树内键:皮肤序号 */
|
||||
private static final String STACK_KEY_SKIN = "Skin";
|
||||
/** 子树内键:Facade 物品 */
|
||||
private static final String STACK_KEY_FACADE = "Facade";
|
||||
/** 无背包状态已同步标记(persistentData,防每 tick 重复发包) */
|
||||
private static final String NBT_KEY_NO_BACKPACK_SYNCED = "ThEWifiNoBackpackSynced";
|
||||
|
||||
/**
|
||||
* 傀儡 UUID → 解码后的 home 位置缓存,避免每 tick 重复 GlobalPos.CODEC.parse NBT 解码。
|
||||
@@ -133,16 +146,30 @@ public final class GolemBackpackHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
GlobalPos linkedPos = getBackpackLink(golem);
|
||||
if (linkedPos == null) {
|
||||
if (!hasBackpack(golem)) {
|
||||
return;
|
||||
}
|
||||
|
||||
dropAndClearBackpack(golem, player);
|
||||
|
||||
// 卸载成功:终止铃铛后续绑定逻辑,防止在同一交互中误触发
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
event.setCanceled(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 掉落背包与 Facade 附件并清除实体侧数据(服务端)。
|
||||
* 供铃铛拆卸事件与 Mixin packWithBell dismantle 分支共用;同步 STATUS_NO_BACKPACK
|
||||
* 使所有追踪玩家立即停止渲染背包。
|
||||
*/
|
||||
public static void dropAndClearBackpack(ThaumcraftGolemEntity golem, Player player) {
|
||||
GlobalPos linkedPos = getBackpackLink(golem);
|
||||
if (linkedPos != null) {
|
||||
ItemStack backpackStack = new ItemStack(ModItems.GOLEM_WIFI_BACKPACK.get());
|
||||
backpackStack.set(AEComponents.WIRELESS_LINK_TARGET, linkedPos);
|
||||
golem.spawnAtLocation(backpackStack);
|
||||
}
|
||||
|
||||
// 丢弃旧 Facade(如果有)
|
||||
ItemStack oldFacade = getFacadeItem(golem);
|
||||
if (!oldFacade.isEmpty() && !player.isCreative()) {
|
||||
golem.spawnAtLocation(oldFacade);
|
||||
@@ -151,8 +178,61 @@ public final class GolemBackpackHandler {
|
||||
clearBackpackLink(golem);
|
||||
clearBackpackSkin(golem);
|
||||
clearFacadeItem(golem);
|
||||
golem.getPersistentData().putBoolean(NBT_KEY_NO_BACKPACK_SYNCED, true);
|
||||
golem.level().playSound(null, golem.getX(), golem.getY(), golem.getZ(),
|
||||
SoundEvents.ARMOR_EQUIP_LEATHER, SoundSource.NEUTRAL, 0.5F, 1.0F);
|
||||
|
||||
GolemBackpackSyncPacket packet = new GolemBackpackSyncPacket(
|
||||
golem.getId(), GolemBackpackSyncPacket.STATUS_NO_BACKPACK, 0);
|
||||
PacketDistributor.sendToPlayersTrackingEntity(golem, packet);
|
||||
}
|
||||
|
||||
/**
|
||||
* 回收打包:将三键收拢进傀儡物品 CUSTOM_DATA 的 ThEGolemBackpack 子树。
|
||||
* 由 MixinGolemItems 在 saveGolem TAIL 调用;TC 白名单不覆盖 TE 字段,
|
||||
* 故在 TC 写完 ThaumcraftGolem 后补写本模组数据。
|
||||
*/
|
||||
public static void saveBackpackToStack(ItemStack stack, ThaumcraftGolemEntity golem) {
|
||||
var entityData = golem.getPersistentData();
|
||||
if (!entityData.contains(NBT_KEY_LINK) && !entityData.contains(NBT_KEY_SKIN)
|
||||
&& !entityData.contains(NBT_KEY_FACADE)) {
|
||||
return;
|
||||
}
|
||||
CompoundTag payload = new CompoundTag();
|
||||
if (entityData.contains(NBT_KEY_LINK)) {
|
||||
payload.put(STACK_KEY_LINK, entityData.get(NBT_KEY_LINK).copy());
|
||||
}
|
||||
if (entityData.contains(NBT_KEY_SKIN)) {
|
||||
payload.putInt(STACK_KEY_SKIN, entityData.getInt(NBT_KEY_SKIN));
|
||||
}
|
||||
if (entityData.contains(NBT_KEY_FACADE)) {
|
||||
payload.put(STACK_KEY_FACADE, entityData.get(NBT_KEY_FACADE).copy());
|
||||
}
|
||||
CustomData.update(DataComponents.CUSTOM_DATA, stack,
|
||||
root -> root.put(STACK_DATA_KEY, payload));
|
||||
}
|
||||
|
||||
/**
|
||||
* 放置恢复:从傀儡物品 ThEGolemBackpack 子树还原三键并失效解码缓存。
|
||||
* 由 MixinGolemItems 在 loadGolem TAIL 调用(PlacerItem 放置链)。
|
||||
*/
|
||||
public static void restoreBackpackFromStack(ItemStack stack, ThaumcraftGolemEntity golem) {
|
||||
CompoundTag root = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag();
|
||||
if (!root.contains(STACK_DATA_KEY, CompoundTag.TAG_COMPOUND)) {
|
||||
return;
|
||||
}
|
||||
CompoundTag payload = root.getCompound(STACK_DATA_KEY);
|
||||
var entityData = golem.getPersistentData();
|
||||
if (payload.contains(STACK_KEY_LINK)) {
|
||||
entityData.put(NBT_KEY_LINK, payload.getCompound(STACK_KEY_LINK).copy());
|
||||
}
|
||||
if (payload.contains(STACK_KEY_SKIN)) {
|
||||
entityData.putInt(NBT_KEY_SKIN, payload.getInt(STACK_KEY_SKIN));
|
||||
}
|
||||
if (payload.contains(STACK_KEY_FACADE)) {
|
||||
entityData.put(NBT_KEY_FACADE, payload.getCompound(STACK_KEY_FACADE).copy());
|
||||
}
|
||||
LINK_CACHE.remove(golem.getUUID());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -56,8 +56,18 @@ public final class GolemBackpackTickHandler {
|
||||
}
|
||||
|
||||
if (!GolemBackpackHandler.hasBackpack(golem)) {
|
||||
// 无背包:状态置位后补发一次 STATUS_NO_BACKPACK,清除客户端残留渲染
|
||||
var pd = golem.getPersistentData();
|
||||
if (!pd.getBoolean("ThEWifiNoBackpackSynced")) {
|
||||
pd.putBoolean("ThEWifiNoBackpackSynced", true);
|
||||
PacketDistributor.sendToPlayersTrackingEntity(golem,
|
||||
new GolemBackpackSyncPacket(golem.getId(),
|
||||
GolemBackpackSyncPacket.STATUS_NO_BACKPACK, 0));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 有背包:清除无背包标记,允许下次卸载后再同步
|
||||
golem.getPersistentData().remove("ThEWifiNoBackpackSynced");
|
||||
|
||||
GlobalPos linkTarget = GolemBackpackHandler.getBackpackLink(golem);
|
||||
if (linkTarget == null) {
|
||||
|
||||
+20
-5
@@ -33,10 +33,17 @@ public class EssentiaContainerStorage implements MEStorage {
|
||||
/** 每次实时解析相邻方块实体(总线朝向方块可被替换/移除)。 */
|
||||
private final Supplier<BlockEntity> target;
|
||||
private final Component description;
|
||||
private final Supplier<net.minecraft.core.Direction> accessSide;
|
||||
|
||||
public EssentiaContainerStorage(Supplier<BlockEntity> target, Component description) {
|
||||
this(target, description, () -> null);
|
||||
}
|
||||
|
||||
public EssentiaContainerStorage(Supplier<BlockEntity> target, Component description,
|
||||
Supplier<net.minecraft.core.Direction> accessSide) {
|
||||
this.target = target;
|
||||
this.description = description;
|
||||
this.accessSide = accessSide;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -52,6 +59,12 @@ public class EssentiaContainerStorage implements MEStorage {
|
||||
if (aspect == null) {
|
||||
return 0;
|
||||
}
|
||||
var side = thaumicenergistics.common.integration.tc.EssentiaEndpoints.accessSide(be, accessSide.get());
|
||||
var transport = thaumicenergistics.common.integration.tc.EssentiaEndpoints.transport(be, side);
|
||||
if (transport != null && side != null
|
||||
&& (!transport.isConnectable(side) || !transport.canInputFrom(side))) return 0;
|
||||
if (be instanceof thaumcraft.api.aspects.IAspectContainer container
|
||||
&& !container.doesContainerAccept(aspect)) return 0;
|
||||
|
||||
// TC 内部 AspectContainer(要素罐子 / 奥术蒸馏器 等):单方面储罐,容量可精确读取,
|
||||
// 因此 SIMULATE 能如实回答"还能装多少"。输入总线的预检依赖这一点:
|
||||
@@ -76,7 +89,7 @@ public class EssentiaContainerStorage implements MEStorage {
|
||||
if (mode == Actionable.SIMULATE) {
|
||||
return request;
|
||||
}
|
||||
int accepted = tank.insert(aspect, request);
|
||||
int accepted = thaumicenergistics.common.integration.tc.EssentiaEndpoints.insert(be, key.getId(), request, side);
|
||||
if (accepted > 0) {
|
||||
be.setChanged();
|
||||
}
|
||||
@@ -88,7 +101,8 @@ public class EssentiaContainerStorage implements MEStorage {
|
||||
if (mode == Actionable.SIMULATE) {
|
||||
return amount;
|
||||
}
|
||||
return TCReflection.insertEssentia(be, new AspectStack(key.getId(), amount));
|
||||
return thaumicenergistics.common.integration.tc.EssentiaEndpoints.insert(
|
||||
be, key.getId(), (int) Math.min(amount, Integer.MAX_VALUE), side);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -103,14 +117,15 @@ public class EssentiaContainerStorage implements MEStorage {
|
||||
int request = (int) Math.min(amount, Integer.MAX_VALUE);
|
||||
if (mode == Actionable.SIMULATE) {
|
||||
// 只统计、不动容器
|
||||
for (AspectStack stack : TCReflection.listEssentia(be)) {
|
||||
for (AspectStack stack : thaumicenergistics.common.integration.tc.EssentiaEndpoints.contents(be, accessSide.get())) {
|
||||
if (stack.aspectId().equals(key.getId())) {
|
||||
return Math.min(stack.amount(), request);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
AspectStack extracted = TCReflection.extractEssentia(be, key.getId(), request);
|
||||
AspectStack extracted = thaumicenergistics.common.integration.tc.EssentiaEndpoints.extract(
|
||||
be, key.getId(), request, accessSide.get());
|
||||
return extracted == null ? 0 : extracted.amount();
|
||||
}
|
||||
|
||||
@@ -120,7 +135,7 @@ public class EssentiaContainerStorage implements MEStorage {
|
||||
if (be == null) {
|
||||
return;
|
||||
}
|
||||
List<AspectStack> stacks = TCReflection.listEssentia(be);
|
||||
List<AspectStack> stacks = thaumicenergistics.common.integration.tc.EssentiaEndpoints.contents(be, accessSide.get());
|
||||
for (AspectStack stack : stacks) {
|
||||
if (stack.amount() <= 0) continue;
|
||||
AEssentiaKey key = AEssentiaKey.of(stack.aspectId());
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package thaumicenergistics.common.essentia.capability;
|
||||
|
||||
import java.util.function.LongUnaryOperator;
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.PowerMultiplier;
|
||||
import appeng.api.networking.IGrid;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaConversionHelper;
|
||||
|
||||
public final class EssentiaEnergy {
|
||||
private EssentiaEnergy() {
|
||||
}
|
||||
|
||||
public static long transfer(IGrid grid, long requested, LongUnaryOperator operation) {
|
||||
var energy = grid.getEnergyService();
|
||||
return TransferBudget.transfer(requested, EssentiaConversionHelper.AE_PER_ESSENTIA,
|
||||
cost -> energy.extractAEPower(cost, Actionable.MODULATE, PowerMultiplier.CONFIG),
|
||||
unused -> energy.injectPower(PowerMultiplier.CONFIG.multiply(unused), Actionable.MODULATE),
|
||||
operation);
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,13 @@ package thaumicenergistics.common.essentia.capability;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.networking.IGrid;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.IEssentiaTransport;
|
||||
import thaumicenergistics.api.storage.AspectStack;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.tc.TCReflection;
|
||||
@@ -26,6 +26,21 @@ public final class EssentiaTransfer {
|
||||
|
||||
private EssentiaTransfer() {}
|
||||
|
||||
public record Push(long moved, AspectStack leftover) {
|
||||
public static final Push NONE = new Push(0, AspectStack.EMPTY);
|
||||
}
|
||||
|
||||
/** 供应器输入已由 CPU 交付,此入口只向目标交付,不再从网络抽取。 */
|
||||
public static long insertOwned(AEssentiaKey key, long amount, BlockEntity container,
|
||||
@Nullable Direction accessSide) {
|
||||
if (container == null || key == null || amount <= 0) return 0;
|
||||
var aspect = TCReflection.findAspectById(key.getId());
|
||||
if (aspect == null) return 0;
|
||||
int wanted = (int) Math.min(amount, Integer.MAX_VALUE);
|
||||
return thaumicenergistics.common.integration.tc.EssentiaEndpoints.insert(
|
||||
container, key.getId(), wanted, accessSide);
|
||||
}
|
||||
|
||||
/**
|
||||
* 容器 → 网络 的搬运产物。
|
||||
*
|
||||
@@ -49,32 +64,44 @@ public final class EssentiaTransfer {
|
||||
* @param rate 单次最大搬运量
|
||||
* @return 搬运产物;无搬运时为 {@link Pull#NONE}
|
||||
*/
|
||||
public static Pull pull(@Nullable BlockEntity container, IGrid grid, IActionSource source, int rate) {
|
||||
public static Pull pull(@Nullable BlockEntity container, IGrid grid, IActionSource source, int rate,
|
||||
@Nullable Direction accessSide) {
|
||||
return pull(container, grid, source, rate, accessSide, id -> true);
|
||||
}
|
||||
|
||||
public static Pull pull(@Nullable BlockEntity container, IGrid grid, IActionSource source, int rate,
|
||||
@Nullable Direction accessSide, Predicate<ResourceLocation> filter) {
|
||||
if (container == null || rate <= 0) return Pull.NONE;
|
||||
|
||||
// 1) 非破坏性预检:先窥视容器能给什么(无源质直接退出)
|
||||
AspectStack available = TCReflection.peekEssentia(container, rate);
|
||||
if (available == null || available.isEmpty()) return Pull.NONE;
|
||||
AEssentiaKey key = AEssentiaKey.of(available.aspectId());
|
||||
if (key == null) return Pull.NONE;
|
||||
|
||||
// 2) 预检网络能接收多少;为 0(无源质存储 / 已满)则完全不抽取
|
||||
// 多要素容器不能因首项被过滤或网络已满而饿死后续可接收项。
|
||||
for (var available : thaumicenergistics.common.integration.tc.EssentiaEndpoints.contents(container, accessSide)) {
|
||||
if (available.isEmpty() || !filter.test(available.aspectId())) continue;
|
||||
var key = AEssentiaKey.of(available.aspectId());
|
||||
long acceptable = grid.getStorageService().getInventory().insert(
|
||||
key, available.amount(), Actionable.SIMULATE, source);
|
||||
if (acceptable <= 0) return Pull.NONE;
|
||||
key, Math.min(rate, available.amount()), Actionable.SIMULATE, source);
|
||||
if (acceptable <= 0) continue;
|
||||
return pullAvailable(container, grid, source, rate, accessSide, available, key, acceptable);
|
||||
}
|
||||
return Pull.NONE;
|
||||
}
|
||||
|
||||
private static Pull pullAvailable(BlockEntity container, IGrid grid, IActionSource source, int rate,
|
||||
@Nullable Direction accessSide, AspectStack available, AEssentiaKey key, long acceptable) {
|
||||
|
||||
// 3) 定向抽取(取「容器能给」与「网络能收」的较小值)
|
||||
int toExtract = (int) Math.min(available.amount(), acceptable);
|
||||
AspectStack extracted = TCReflection.extractEssentia(container, available.aspectId(), toExtract);
|
||||
if (extracted == null || extracted.isEmpty()) return Pull.NONE;
|
||||
|
||||
// 4) 实插;模拟与实插不一致时残留交回调用方缓冲重试,绝不归还 / 丢弃
|
||||
long injected = grid.getStorageService().getInventory().insert(
|
||||
int toExtract = (int) Math.min(rate, Math.min(available.amount(), acceptable));
|
||||
AspectStack[] leftover = {AspectStack.EMPTY};
|
||||
long injected = EssentiaEnergy.transfer(grid, toExtract, allowed -> {
|
||||
var extracted = thaumicenergistics.common.integration.tc.EssentiaEndpoints.extract(
|
||||
container, available.aspectId(), (int) allowed, accessSide);
|
||||
if (extracted == null || extracted.isEmpty()) return 0;
|
||||
long inserted = grid.getStorageService().getInventory().insert(
|
||||
key, extracted.amount(), Actionable.MODULATE, source);
|
||||
AspectStack leftover = injected < extracted.amount()
|
||||
? new AspectStack(extracted.aspectId(), extracted.amount() - injected)
|
||||
: AspectStack.EMPTY;
|
||||
return new Pull(injected, leftover);
|
||||
if (inserted < extracted.amount()) {
|
||||
leftover[0] = new AspectStack(extracted.aspectId(), extracted.amount() - inserted);
|
||||
}
|
||||
return inserted;
|
||||
});
|
||||
return new Pull(injected, leftover[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,28 +113,23 @@ public final class EssentiaTransfer {
|
||||
* @param accessSide 容器接收面的朝向(TC 管道 {@code addEssentia} 需要;可空)
|
||||
* @return 实际注入容器的源质量;0 表示本次无搬运(调用方据此判「无所作为」)
|
||||
*/
|
||||
public static long push(IGrid grid, IActionSource source, @Nullable AEssentiaKey key, long amount,
|
||||
public static Push push(IGrid grid, IActionSource source, @Nullable AEssentiaKey key, long amount,
|
||||
@Nullable BlockEntity container, @Nullable Direction accessSide) {
|
||||
if (container == null || key == null || amount <= 0) return 0;
|
||||
|
||||
long extracted = grid.getStorageService().getInventory().extract(
|
||||
key, amount, Actionable.MODULATE, source);
|
||||
if (extracted <= 0) return 0;
|
||||
|
||||
// 先按 IAspectContainer 注入,失败再回退 TC 源质管道接口
|
||||
int injected = TCReflection.insertEssentia(container, new AspectStack(key.getId(), extracted));
|
||||
if (injected <= 0 && container instanceof IEssentiaTransport transport) {
|
||||
Aspect aspect = TCReflection.findAspectById(key.getId());
|
||||
if (aspect != null) {
|
||||
int want = (int) Math.min(extracted, Integer.MAX_VALUE);
|
||||
injected = transport.addEssentia(aspect, want, accessSide);
|
||||
if (container == null || key == null || amount <= 0) return Push.NONE;
|
||||
AspectStack[] pending = {AspectStack.EMPTY};
|
||||
long moved = EssentiaEnergy.transfer(grid, amount, allowed -> {
|
||||
var inventory = grid.getStorageService().getInventory();
|
||||
long extracted = inventory.extract(key, allowed, Actionable.MODULATE, source);
|
||||
long inserted = insertOwned(key, extracted, container, accessSide);
|
||||
long remaining = extracted - inserted;
|
||||
if (remaining > 0) {
|
||||
long returned = inventory.insert(key, remaining, Actionable.MODULATE, source);
|
||||
if (returned < remaining) {
|
||||
pending[0] = new AspectStack(key.getId(), remaining - returned);
|
||||
}
|
||||
}
|
||||
if (injected < extracted) {
|
||||
// 退回未注入的部分
|
||||
grid.getStorageService().getInventory().insert(
|
||||
key, extracted - injected, Actionable.MODULATE, source);
|
||||
}
|
||||
return injected;
|
||||
return inserted;
|
||||
});
|
||||
return new Push(moved, pending[0]);
|
||||
}
|
||||
}
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package thaumicenergistics.common.essentia.capability;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.RedstoneMode;
|
||||
import appeng.api.config.PowerMultiplier;
|
||||
import appeng.blockentity.networking.CableBusBlockEntity;
|
||||
import appeng.core.definitions.AEItems;
|
||||
import appeng.parts.automation.ExportBusPart;
|
||||
import net.minecraft.core.Direction;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.IEssentiaTransport;
|
||||
import thaumicenergistics.api.storage.AspectStack;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.tc.AspectIds;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaEndpoints;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaConversionHelper;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/**
|
||||
* Sided cable-bus endpoint for pull-only TC consumers. Only advertises the export bus's
|
||||
* owned buffer, never the entire ME inventory. Resolve the part on every call so removal,
|
||||
* rotation and card changes cannot leave a cached capability pointing at an old part.
|
||||
*/
|
||||
public final class ExportBusEssentiaTransport implements IEssentiaTransport {
|
||||
private final CableBusBlockEntity host;
|
||||
private final Direction face;
|
||||
|
||||
public ExportBusEssentiaTransport(CableBusBlockEntity host, Direction face) {
|
||||
this.host = host;
|
||||
this.face = face;
|
||||
}
|
||||
|
||||
private ExportBusPart bus(Direction side) {
|
||||
if (side != face || host.isRemoved() || host.getLevel() == null || host.getLevel().isClientSide()
|
||||
|| !(host.getPart(face) instanceof ExportBusPart bus)
|
||||
|| !bus.getUpgrades().isInstalled(ModItems.ESSENTIA_UPGRADE_CARD.get())
|
||||
|| !bus.getMainNode().isActive()) return null;
|
||||
var mode = bus.getRSMode();
|
||||
if (bus.getUpgrades().isInstalled(AEItems.REDSTONE_CARD)
|
||||
&& ((mode == RedstoneMode.HIGH_SIGNAL && !host.hasRedstone())
|
||||
|| (mode == RedstoneMode.LOW_SIGNAL && host.hasRedstone()))) return null;
|
||||
// Pulse mode only exposes stock reserved by an authorized doBusWork invocation.
|
||||
return bus;
|
||||
}
|
||||
|
||||
private AspectStack stock(Direction side) {
|
||||
var bus = bus(side);
|
||||
if (!(bus instanceof EssentiaTransferBuffer buffer)) return AspectStack.EMPTY;
|
||||
var pending = buffer.thE$getTransferBuffer();
|
||||
return !pending.isEmpty() && bus.getConfig().keySet().contains(AEssentiaKey.of(pending.aspectId()))
|
||||
? pending : AspectStack.EMPTY;
|
||||
}
|
||||
|
||||
/** Called only during the bus's normal, power/channel/redstone-controlled work tick. */
|
||||
public static boolean reserveForConsumer(ExportBusPart bus, AEssentiaKey key, int rate,
|
||||
net.minecraft.world.level.block.entity.BlockEntity consumer, Direction consumerSide,
|
||||
appeng.api.networking.IGrid grid, appeng.api.networking.security.IActionSource source) {
|
||||
if (!(bus instanceof EssentiaTransferBuffer buffer) || !buffer.thE$getTransferBuffer().isEmpty()) return false;
|
||||
var transport = EssentiaEndpoints.transport(consumer, consumerSide);
|
||||
var aspect = AspectIds.findAspectById(key.getId());
|
||||
if (aspect == null || transport == null || !transport.isConnectable(consumerSide)
|
||||
|| !transport.canInputFrom(consumerSide) || transport.getSuctionAmount(consumerSide) <= 0) return false;
|
||||
var requested = transport.getSuctionType(consumerSide);
|
||||
if (requested != null && requested != aspect) return false;
|
||||
// Small, persisted stock replaces the intermediary jar without hoarding network resources.
|
||||
long extracted = grid.getStorageService().getInventory().extract(
|
||||
key, Math.min(rate, 8), Actionable.MODULATE, source);
|
||||
if (extracted <= 0) return false;
|
||||
buffer.thE$setTransferBuffer(new AspectStack(key.getId(), extracted));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override public boolean isConnectable(Direction side) { return bus(side) != null; }
|
||||
@Override public boolean canInputFrom(Direction side) { return false; }
|
||||
@Override public boolean canOutputTo(Direction side) { return !stock(side).isEmpty(); }
|
||||
@Override public void setSuction(Aspect aspect, int amount) { }
|
||||
@Override public Aspect getSuctionType(Direction side) { return null; }
|
||||
@Override public int getSuctionAmount(Direction side) { return 0; }
|
||||
@Override public int getMinimumSuction() { return 0; }
|
||||
@Override public Aspect getEssentiaType(Direction side) {
|
||||
var stock = stock(side);
|
||||
return stock.isEmpty() ? null : AspectIds.findAspectById(stock.aspectId());
|
||||
}
|
||||
@Override public int getEssentiaAmount(Direction side) { return (int) Math.min(stock(side).amount(), Integer.MAX_VALUE); }
|
||||
@Override public int addEssentia(Aspect aspect, int amount, Direction side) { return 0; }
|
||||
|
||||
@Override
|
||||
public int simulateTakeEssentia(Aspect aspect, int amount, Direction side) {
|
||||
if (aspect == null || amount <= 0) return 0;
|
||||
var bus = bus(side);
|
||||
var stock = stock(side);
|
||||
if (bus == null || stock.isEmpty() || aspect != AspectIds.findAspectById(stock.aspectId())) return 0;
|
||||
var grid = bus.getMainNode().getGrid();
|
||||
if (grid == null) return 0;
|
||||
long wanted = Math.min(amount, stock.amount());
|
||||
double power = grid.getEnergyService().extractAEPower(wanted * EssentiaConversionHelper.AE_PER_ESSENTIA,
|
||||
Actionable.SIMULATE, PowerMultiplier.CONFIG);
|
||||
return (int) Math.min(wanted, (long) Math.floor((power + 1.0e-9) / EssentiaConversionHelper.AE_PER_ESSENTIA));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int takeEssentia(Aspect aspect, int amount, Direction side) {
|
||||
if (aspect == null || amount <= 0) return 0;
|
||||
var bus = bus(side);
|
||||
var stock = stock(side);
|
||||
if (bus == null || stock.isEmpty() || aspect != AspectIds.findAspectById(stock.aspectId())) return 0;
|
||||
var grid = bus.getMainNode().getGrid();
|
||||
if (grid == null) return 0;
|
||||
var buffer = (EssentiaTransferBuffer) bus;
|
||||
return (int) EssentiaEnergy.transfer(grid, Math.min(amount, stock.amount()), allowed -> {
|
||||
long remaining = stock.amount() - allowed;
|
||||
buffer.thE$setTransferBuffer(remaining == 0 ? AspectStack.EMPTY : new AspectStack(stock.aspectId(), remaining));
|
||||
return allowed;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package thaumicenergistics.common.essentia.capability;
|
||||
|
||||
import java.util.function.DoubleConsumer;
|
||||
import java.util.function.DoubleUnaryOperator;
|
||||
import java.util.function.LongUnaryOperator;
|
||||
|
||||
/** 先取得能量预算再搬运,部分接收只结算实际量,退回未使用的预算。 */
|
||||
public final class TransferBudget {
|
||||
private TransferBudget() {
|
||||
}
|
||||
|
||||
public static long transfer(long requested, double unitCost, DoubleUnaryOperator reserve,
|
||||
DoubleConsumer refund, LongUnaryOperator operation) {
|
||||
if (requested <= 0 || !Double.isFinite(unitCost) || unitCost <= 0) {
|
||||
return 0;
|
||||
}
|
||||
double reserved = reserve.applyAsDouble(requested * unitCost);
|
||||
long allowed = Math.min(requested, (long) Math.floor((reserved + 1.0e-9) / unitCost));
|
||||
long moved = 0;
|
||||
try {
|
||||
if (allowed > 0) {
|
||||
long transferred = operation.applyAsLong(allowed);
|
||||
if (transferred < 0 || transferred > allowed) {
|
||||
throw new IllegalStateException("Transfer exceeded its reserved resource budget");
|
||||
}
|
||||
moved = transferred;
|
||||
}
|
||||
return moved;
|
||||
} finally {
|
||||
double unused = reserved - moved * unitCost;
|
||||
if (unused > 1.0e-9) {
|
||||
refund.accept(unused);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,12 @@ public final class RecipeRegistration {
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_4K;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_16K;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_64K;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_256K;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_1M;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_4M;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_16M;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_64M;
|
||||
public static ShapedArcaneRecipe STORAGE_COMPONENT_256M;
|
||||
public static ShapedArcaneRecipe KNOWLEDGE_CORE_ITEM;
|
||||
public static ShapedArcaneRecipe FOCUS_AEWRENCH_RECIPE;
|
||||
public static ShapedArcaneRecipe GOLEM_WIFI_BACKPACK_RECIPE;
|
||||
@@ -64,6 +70,8 @@ public final class RecipeRegistration {
|
||||
private static final TagKey<Item> WISP_ESSENCES = tag("thaumicenergistics", "wisp_essences");
|
||||
/** AE2 三种显示器(普通/暗/半暗)任一可用。 */
|
||||
private static final TagKey<Item> MONITORS = tag("thaumicenergistics", "monitors");
|
||||
/** Optional exact-item ingredient: an empty tag keeps these recipes unavailable without Thaumic Tinkerer. */
|
||||
private static final TagKey<Item> ICHOR = tag("thaumicenergistics", "ichor");
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
private static TagKey<Item> tag(String ns, String path) {
|
||||
@@ -131,6 +139,54 @@ public final class RecipeRegistration {
|
||||
'6', stack(ModItems.STORAGE_COMPONENT_16K),
|
||||
'G', ae("quartz_glass"));
|
||||
|
||||
STORAGE_COMPONENT_256K = ThaumcraftApi.addArcaneCraftingRecipe("ESSENTIASTORAGE", stack(ModItems.STORAGE_COMPONENT_256K),
|
||||
new AspectList().add(Aspect.FIRE, 3).add(Aspect.ORDER, 8),
|
||||
"SPS", "CGC", "SCS",
|
||||
'S', tc("salis_mundus"),
|
||||
'P', ae("engineering_processor"),
|
||||
'C', stack(ModItems.STORAGE_COMPONENT_64K),
|
||||
'G', tc("warded_glass"));
|
||||
|
||||
STORAGE_COMPONENT_1M = ThaumcraftApi.addArcaneCraftingRecipe("ESSENTIASTORAGE", stack(ModItems.STORAGE_COMPONENT_1M),
|
||||
new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 24),
|
||||
"SPS", "CGC", "SCS",
|
||||
'S', tc("salis_mundus"),
|
||||
'P', ae("engineering_processor"),
|
||||
'C', stack(ModItems.STORAGE_COMPONENT_256K),
|
||||
'G', tc("warded_glass"));
|
||||
|
||||
STORAGE_COMPONENT_4M = ThaumcraftApi.addArcaneCraftingRecipe("ESSENTIASTORAGE", stack(ModItems.STORAGE_COMPONENT_4M),
|
||||
new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 24),
|
||||
"SPS", "CGC", "SCS",
|
||||
'S', tc("salis_mundus"),
|
||||
'P', ae("engineering_processor"),
|
||||
'C', stack(ModItems.STORAGE_COMPONENT_1M),
|
||||
'G', tc("warded_glass"));
|
||||
|
||||
STORAGE_COMPONENT_16M = ThaumcraftApi.addArcaneCraftingRecipe("ESSENTIASTORAGE", stack(ModItems.STORAGE_COMPONENT_16M),
|
||||
new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 24),
|
||||
"SPS", "CGC", "SCS",
|
||||
'S', tc("salis_mundus"),
|
||||
'P', ae("engineering_processor"),
|
||||
'C', stack(ModItems.STORAGE_COMPONENT_4M),
|
||||
'G', tc("warded_glass"));
|
||||
|
||||
STORAGE_COMPONENT_64M = ThaumcraftApi.addArcaneCraftingRecipe("ESSENTIASTORAGE", stack(ModItems.STORAGE_COMPONENT_64M),
|
||||
new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 24),
|
||||
"SPS", "CGC", "SCS",
|
||||
'S', ICHOR,
|
||||
'P', ae("engineering_processor"),
|
||||
'C', stack(ModItems.STORAGE_COMPONENT_16M),
|
||||
'G', tc("warded_glass"));
|
||||
|
||||
STORAGE_COMPONENT_256M = ThaumcraftApi.addArcaneCraftingRecipe("ESSENTIASTORAGE", stack(ModItems.STORAGE_COMPONENT_256M),
|
||||
new AspectList().add(Aspect.FIRE, 10).add(Aspect.ORDER, 24),
|
||||
"SPS", "CGC", "SCS",
|
||||
'S', ICHOR,
|
||||
'P', ae("engineering_processor"),
|
||||
'C', stack(ModItems.STORAGE_COMPONENT_64M),
|
||||
'G', tc("warded_glass"));
|
||||
|
||||
KNOWLEDGE_CORE_ITEM = ThaumcraftApi.addArcaneCraftingRecipe("KNOWLEDGEINSCRIBER", stack(ModItems.KNOWLEDGE_CORE),
|
||||
new AspectList().add(Aspect.WATER, 3).add(Aspect.ORDER, 3).add(Aspect.EARTH, 1),
|
||||
"QlQ",
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package thaumicenergistics.common.features;
|
||||
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.NonNullList;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.CraftingBookCategory;
|
||||
import net.minecraft.world.item.crafting.CraftingInput;
|
||||
import net.minecraft.world.item.crafting.CustomRecipe;
|
||||
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.neoforged.fml.ModList;
|
||||
import thaumicenergistics.common.integration.ae2wt.SafeTerminalMerge;
|
||||
import thaumicenergistics.common.integration.ae2wt.AE2WTCompat;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
import thaumicenergistics.init.ModRecipeSerializers;
|
||||
|
||||
public final class SafeTerminalMergeRecipe extends CustomRecipe {
|
||||
private final String partner;
|
||||
|
||||
public SafeTerminalMergeRecipe(String partner) {
|
||||
super(CraftingBookCategory.EQUIPMENT);
|
||||
this.partner = partner;
|
||||
}
|
||||
|
||||
private ItemStack merge(CraftingInput input) {
|
||||
if (!ModList.get().isLoaded("ae2wtlib") || input.ingredientCount() != 2) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
ItemStack arcane = ItemStack.EMPTY;
|
||||
ItemStack other = ItemStack.EMPTY;
|
||||
for (int i = 0; i < input.size(); i++) {
|
||||
var stack = input.getItem(i);
|
||||
if (stack.isEmpty()) continue;
|
||||
if (stack.is(ModItems.WIRELESS_ARCANE_CRAFTING_TERMINAL.get())) {
|
||||
if (!arcane.isEmpty()) return ItemStack.EMPTY;
|
||||
arcane = stack;
|
||||
} else {
|
||||
other = stack;
|
||||
}
|
||||
}
|
||||
return arcane.isEmpty() || other.isEmpty() ? ItemStack.EMPTY
|
||||
: SafeTerminalMerge.merge(arcane, other, partner);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(CraftingInput input, Level level) {
|
||||
return !merge(input).isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack assemble(CraftingInput input, HolderLookup.Provider registries) {
|
||||
return merge(input);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canCraftInDimensions(int width, int height) {
|
||||
return width * height >= 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecipeSerializer<?> getSerializer() {
|
||||
return ModRecipeSerializers.SAFE_TERMINAL_MERGE.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public NonNullList<Ingredient> getIngredients() {
|
||||
var ingredients = NonNullList.<Ingredient>create();
|
||||
if (ModList.get().isLoaded("ae2wtlib")) {
|
||||
var other = AE2WTCompat.displayPartner(partner);
|
||||
if (!other.isEmpty()) {
|
||||
ingredients.add(Ingredient.of(ModItems.WIRELESS_ARCANE_CRAFTING_TERMINAL.get()));
|
||||
ingredients.add(Ingredient.of(other));
|
||||
}
|
||||
}
|
||||
return ingredients;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getResultItem(HolderLookup.Provider registries) {
|
||||
return displayResult();
|
||||
}
|
||||
|
||||
public ItemStack displayResult() {
|
||||
if (!ModList.get().isLoaded("ae2wtlib")) return ItemStack.EMPTY;
|
||||
return SafeTerminalMerge.merge(new ItemStack(ModItems.WIRELESS_ARCANE_CRAFTING_TERMINAL.get()),
|
||||
AE2WTCompat.displayPartner(partner), partner);
|
||||
}
|
||||
|
||||
public static final class Serializer implements RecipeSerializer<SafeTerminalMergeRecipe> {
|
||||
private static final MapCodec<SafeTerminalMergeRecipe> CODEC = RecordCodecBuilder.mapCodec(instance ->
|
||||
instance.group(com.mojang.serialization.Codec.STRING.optionalFieldOf("partner", "")
|
||||
.forGetter(recipe -> recipe.partner)).apply(instance, SafeTerminalMergeRecipe::new));
|
||||
private static final StreamCodec<RegistryFriendlyByteBuf, SafeTerminalMergeRecipe> STREAM_CODEC =
|
||||
StreamCodec.composite(ByteBufCodecs.STRING_UTF8, recipe -> recipe.partner,
|
||||
SafeTerminalMergeRecipe::new);
|
||||
|
||||
@Override
|
||||
public MapCodec<SafeTerminalMergeRecipe> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StreamCodec<RegistryFriendlyByteBuf, SafeTerminalMergeRecipe> streamCodec() {
|
||||
return STREAM_CODEC;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public class EssentiaGridService implements IEssentiaGrid, IGridServiceProvider
|
||||
if (key == null) return 0;
|
||||
return StorageHelper.poweredExtraction(
|
||||
grid.getEnergyService(), storage, key, amount,
|
||||
IActionSource.empty());
|
||||
IActionSource.empty(), simulate ? Actionable.SIMULATE : Actionable.MODULATE);
|
||||
}
|
||||
|
||||
private MEStorage getNativeStorage() {
|
||||
@@ -74,6 +74,7 @@ public class EssentiaGridService implements IEssentiaGrid, IGridServiceProvider
|
||||
|
||||
@Override
|
||||
public long extractEssentia(ResourceLocation aspectId, long amount, boolean simulate) {
|
||||
if (amount <= 0) return 0;
|
||||
// 优先从 monitor 提取
|
||||
long monitorAmt = monitor.get(aspectId);
|
||||
if (monitorAmt >= amount) {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package thaumicenergistics.common.integration.advancedae;
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.Items;
|
||||
|
||||
import appeng.api.upgrades.Upgrades;
|
||||
|
||||
import net.neoforged.fml.ModList;
|
||||
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/**
|
||||
* AdvancedAE 可选兼容:源质访问卡准入其高级样板供应器(方块/部件双形态、
|
||||
* 两种容量一起覆盖,避免玩家升级供应器后卡失效)。
|
||||
* <p>
|
||||
* AAE 的 {@code AdvPatternProviderLogic} 为独立实现(不继承 AE2 原版供应器逻辑),
|
||||
* 本类仅完成升级卡准入注册;卡槽组与源质能力的 Mixin 由独立兼容配置另行挂载。
|
||||
* 零 AAE 编译引用,ID 缺失时输出日志并跳过。
|
||||
*/
|
||||
public final class AdvancedAECompat {
|
||||
|
||||
/** AdvancedAE modid。 */
|
||||
public static final String MODID = "advanced_ae";
|
||||
|
||||
private AdvancedAECompat() {
|
||||
}
|
||||
|
||||
public static void registerEssentiaUpgrades() {
|
||||
if (!ModList.get().isLoaded(MODID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Item card = ModItems.ESSENTIA_UPGRADE_CARD.get();
|
||||
|
||||
// 高级扩展样板供应器(大容量):方块键统一 part/block 提示分组。
|
||||
registerHost(card, "adv_pattern_provider",
|
||||
"block.advanced_ae.adv_pattern_provider");
|
||||
registerHost(card, "adv_pattern_provider_part",
|
||||
"block.advanced_ae.adv_pattern_provider");
|
||||
// 高级样板供应器(小容量)。
|
||||
registerHost(card, "small_adv_pattern_provider",
|
||||
"block.advanced_ae.small_adv_pattern_provider");
|
||||
registerHost(card, "small_adv_pattern_provider_part",
|
||||
"block.advanced_ae.small_adv_pattern_provider");
|
||||
}
|
||||
|
||||
private static void registerHost(Item card, String path, String tooltipGroup) {
|
||||
ResourceLocation id = ResourceLocation.fromNamespaceAndPath(MODID, path);
|
||||
|
||||
Item host = BuiltInRegistries.ITEM.getOptional(id).orElse(null);
|
||||
|
||||
if (host == null || host == Items.AIR) {
|
||||
ThaumicEnergistics.LOG.warn(
|
||||
"Skipping AdvancedAE essentia upgrade registration: missing host item {}", id);
|
||||
return;
|
||||
}
|
||||
|
||||
Upgrades.add(card, host, 1, tooltipGroup);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package thaumicenergistics.common.integration.ae2lt;
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.Items;
|
||||
|
||||
import appeng.api.upgrades.Upgrades;
|
||||
|
||||
import net.neoforged.fml.ModList;
|
||||
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/**
|
||||
* AE2 Lightning Tech 可选兼容:源质访问卡准入其过载样板供应器(方块与扩展过载两形态,
|
||||
* 发布 jar 2.1.2-beta3 实证仅方块形态、无部件注册)。
|
||||
* <p>
|
||||
* 其 {@code OverloadedPatternProviderLogic}/{@code OverloadedPatternProviderBlockEntity}
|
||||
* 与菜单均直接继承 AE2 原版供应器体系(字节码实证),升级卡库存、菜单升级槽与
|
||||
* 普通相邻输出的源质路径由既有注入自动生效;定向/无线/批量等独立派发路径的
|
||||
* 源质门控由独立兼容配置另行挂载。零 AE2LT 编译引用,ID 缺失时输出日志并跳过。
|
||||
*/
|
||||
public final class AE2LTCompat {
|
||||
|
||||
/** AE2 Lightning Tech modid。 */
|
||||
public static final String MODID = "ae2lt";
|
||||
|
||||
private AE2LTCompat() {
|
||||
}
|
||||
|
||||
public static void registerEssentiaUpgrades() {
|
||||
if (!ModList.get().isLoaded(MODID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Item card = ModItems.ESSENTIA_UPGRADE_CARD.get();
|
||||
|
||||
// 过载样板供应器(基础形态)。
|
||||
registerHost(card, "overloaded_pattern_provider",
|
||||
"block.ae2lt.overloaded_pattern_provider");
|
||||
// 扩展过载样板供应器(扩展容量形态)。
|
||||
registerHost(card, "extended_overloaded_pattern_provider",
|
||||
"block.ae2lt.extended_overloaded_pattern_provider");
|
||||
}
|
||||
|
||||
private static void registerHost(Item card, String path, String tooltipGroup) {
|
||||
ResourceLocation id = ResourceLocation.fromNamespaceAndPath(MODID, path);
|
||||
|
||||
Item host = BuiltInRegistries.ITEM.getOptional(id).orElse(null);
|
||||
|
||||
if (host == null || host == Items.AIR) {
|
||||
ThaumicEnergistics.LOG.warn(
|
||||
"Skipping AE2LT essentia upgrade registration: missing host item {}", id);
|
||||
return;
|
||||
}
|
||||
|
||||
Upgrades.add(card, host, 1, tooltipGroup);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package thaumicenergistics.common.integration.ae2wt;
|
||||
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
|
||||
import appeng.menu.locator.ItemMenuHostLocator;
|
||||
|
||||
import de.mari_023.ae2wtlib.api.terminal.ItemWT;
|
||||
|
||||
import thaumicenergistics.init.ModMenuTypes;
|
||||
|
||||
/**
|
||||
* AE2WT 体系下的无线奥术终端物品:继承 {@code ItemWT} 纳入通用终端合并/模式切换
|
||||
* 体系({@code WTDefinition} 类型硬绑定 ItemWT),奥术模式打开本模组同一奥术菜单。
|
||||
* <p>
|
||||
* 仅 ae2wtlib 存在时由注册工厂实例化(注册 ID 不变),能量容量与独立实现一致——
|
||||
* {@code ItemWT} 无参构造内部即 AEConfig 无线终端电池 + stacksTo(1)。宿主创建由
|
||||
* {@code ItemWT.getMenuHost} 按 WTDefinition 的工厂自动分派,无需覆写。
|
||||
*/
|
||||
public class AE2WTArcaneTerminalItem extends ItemWT {
|
||||
|
||||
@Override
|
||||
public MenuType<?> getMenuType(ItemMenuHostLocator locator, Player player) {
|
||||
return ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL_TYPE;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package thaumicenergistics.common.integration.ae2wt;
|
||||
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
|
||||
import appeng.api.ids.AEComponents;
|
||||
import appeng.api.inventories.InternalInventory;
|
||||
import appeng.menu.ISubMenu;
|
||||
import appeng.menu.locator.ItemMenuHostLocator;
|
||||
import appeng.util.inv.AppEngInternalInventory;
|
||||
|
||||
import de.mari_023.ae2wtlib.api.terminal.ItemWT;
|
||||
import de.mari_023.ae2wtlib.api.terminal.WTMenuHost;
|
||||
|
||||
import thaumicenergistics.common.container.IArcaneTerminalInventoryHost;
|
||||
import thaumicenergistics.common.parts.ArcaneCraftingTerminalPart;
|
||||
import thaumicenergistics.init.ModComponents;
|
||||
|
||||
/**
|
||||
* AE2WT 通用终端的奥术模式宿主:继承 {@code WTMenuHost} 复用其模式切换、升级卡库存、
|
||||
* 奇点库存与量子连接/充电全套机制(不在本类重复实现,避免双库存与重复扣费),
|
||||
* 只补齐奥术合成所需的合成格与法杖槽——持久化进终端物品组件,与独立无线奥术终端同一范式。
|
||||
* <p>
|
||||
* 仅 ae2wtlib 存在时由 {@code AE2WTCompat} 注册链路加载;奇点子库存 id 用字符串软查
|
||||
* ({@code ae2wtlib:singularity},WTMenuHost.INV_SINGULARITY 实证值),不暴露可选 API 类型。
|
||||
*/
|
||||
public class AE2WTArcaneTerminalMenuHost extends WTMenuHost implements IArcaneTerminalInventoryHost {
|
||||
|
||||
/** WTMenuHost 奇点子库存 id(AE2wtlibAPI.id("singularity") 字节码实证,软查免编译暴露)。 */
|
||||
public static final ResourceLocation SINGULARITY_INV_ID =
|
||||
ResourceLocation.fromNamespaceAndPath("ae2wtlib", "singularity");
|
||||
|
||||
private final AppEngInternalInventory craftingGrid;
|
||||
private final AppEngInternalInventory wandInv;
|
||||
|
||||
public AE2WTArcaneTerminalMenuHost(
|
||||
ItemWT item,
|
||||
Player player,
|
||||
ItemMenuHostLocator locator,
|
||||
BiConsumer<Player, ISubMenu> returnToMainMenu) {
|
||||
super(item, player, locator, returnToMainMenu);
|
||||
// WTMenuHost 构造器会触发连接状态更新,但只依赖终端物品;子库存在此之后创建。
|
||||
this.craftingGrid = thaumicenergistics.common.inventory.PersistedTerminalInventories.createPersistedInv(
|
||||
player, this.getItemStack(), 9, AEComponents.CRAFTING_INV);
|
||||
this.wandInv = thaumicenergistics.common.inventory.PersistedTerminalInventories.createPersistedInv(
|
||||
player, this.getItemStack(), 1, ModComponents.WAND_INV.get());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public InternalInventory getSubInventory(ResourceLocation id) {
|
||||
if (id.equals(ArcaneCraftingTerminalPart.INV_CRAFTING)) {
|
||||
return craftingGrid;
|
||||
} else if (id.equals(ArcaneCraftingTerminalPart.INV_WAND)) {
|
||||
return wandInv;
|
||||
}
|
||||
// 奇点(ae2wtlib:singularity)等其余子库存由 WTMenuHost 基类处理。
|
||||
return super.getSubInventory(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveWandInv() {
|
||||
this.getItemStack().set(ModComponents.WAND_INV.get(), this.wandInv.toItemContainerContents());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refreshConnection() {
|
||||
updateConnectedAccessPoint();
|
||||
updateLinkStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceLocation getSingularityInvId() {
|
||||
return SINGULARITY_INV_ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAE2WTSingularitySemantics() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package thaumicenergistics.common.integration.ae2wt;
|
||||
|
||||
import net.neoforged.fml.ModList;
|
||||
|
||||
import de.mari_023.ae2wtlib.api.gui.Icon;
|
||||
import de.mari_023.ae2wtlib.api.registration.AddTerminalEvent;
|
||||
import de.mari_023.ae2wtlib.api.registration.UpgradeHelper;
|
||||
import de.mari_023.ae2wtlib.api.terminal.ItemWT;
|
||||
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
import thaumicenergistics.init.ModMenuTypes;
|
||||
|
||||
/**
|
||||
* AE2WT(无线终端库)可选兼容注册:把无线奥术终端注册为通用终端的奥术功能
|
||||
* (功能名 {@code thaumicenergistics_arcane}),合并进 ae2wtlib 无线通用终端后
|
||||
* 可切换奥术模式;模式切换、奇点库存与量子连接由 AE2WT 体系自理。
|
||||
* <p>
|
||||
* 注册时机为模组构造阶段——{@code AddTerminalEvent.register} 登记的一次性回调
|
||||
* 在 RegisterEvent(ITEM) 由 API 的入口监听器统一执行(随后 {@code UpgradeHelper.addUpgrades}
|
||||
* 应用全终端升级卡准入),构造期登记必然早于执行。完整 ae2wtlib 缺席时本类
|
||||
* 不被加载(唯一调用点在主类构造器 ModList 守护之后),不产生缺类问题。
|
||||
*/
|
||||
public final class AE2WTCompat {
|
||||
|
||||
/** 通用终端功能名(WTDefinition 键)。 */
|
||||
public static final String ARCANE_TERMINAL_NAME = "thaumicenergistics_arcane";
|
||||
|
||||
private AE2WTCompat() {
|
||||
}
|
||||
|
||||
/** 返回公共 Item 类型,避免普通注册类的字节码验证提前解析 ItemWT 子类。 */
|
||||
public static net.minecraft.world.item.Item createTerminalItem() {
|
||||
return new AE2WTArcaneTerminalItem();
|
||||
}
|
||||
|
||||
/** 不切换通用终端当前模式,解析其奥术附件供后台充能。 */
|
||||
public static appeng.helpers.WirelessTerminalMenuHost<?> createPassiveArcaneHost(
|
||||
net.minecraft.server.level.ServerPlayer player, appeng.menu.locator.ItemMenuHostLocator locator) {
|
||||
var stack = locator.locateItem(player);
|
||||
if (!(stack.getItem() instanceof ItemWT item)
|
||||
|| !de.mari_023.ae2wtlib.api.registration.WTDefinition.exists(ARCANE_TERMINAL_NAME)) return null;
|
||||
var definition = de.mari_023.ae2wtlib.api.registration.WTDefinition.of(ARCANE_TERMINAL_NAME);
|
||||
if (item != definition.item() && !stack.has(definition.componentType())) return null;
|
||||
return new AE2WTArcaneTerminalMenuHost(item, player, locator, (p, menu) -> { });
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回官方奇点槽语义({@code AE2wtlibSlotSemantics.SINGULARITY})。菜单侧经本方法
|
||||
* 隔离解析,防止 ae2wtlib 缺席时普通加载路径触发缺类;调用点均被宿主分支守护
|
||||
* (仅 AE2WT 宿主可达,分支条件成立即证明 ae2wtlib 在场)。
|
||||
*/
|
||||
public static appeng.menu.SlotSemantic singularitySemantic() {
|
||||
return de.mari_023.ae2wtlib.api.gui.AE2wtlibSlotSemantics.SINGULARITY;
|
||||
}
|
||||
|
||||
public static net.minecraft.world.item.ItemStack displayPartner(String partner) {
|
||||
var name = partner.isEmpty() ? "crafting" : partner;
|
||||
var definition = de.mari_023.ae2wtlib.api.registration.WTDefinition.wirelessTerminals().stream()
|
||||
.filter(terminal -> name.equals(terminal.terminalName())).findFirst().orElse(null);
|
||||
if (definition == null) return net.minecraft.world.item.ItemStack.EMPTY;
|
||||
return partner.isEmpty() ? definition.universalTerminal().copy()
|
||||
: new net.minecraft.world.item.ItemStack(definition.item());
|
||||
}
|
||||
|
||||
public static void registerArcaneTerminal() {
|
||||
AddTerminalEvent.register(event -> {
|
||||
var item = ModItems.WIRELESS_ARCANE_CRAFTING_TERMINAL.get();
|
||||
if (!(item instanceof ItemWT arcaneItem)) {
|
||||
// ae2wtlib 存在但注册工厂走了独立实现(版本守卫分支),不注册避免半残功能。
|
||||
ThaumicEnergistics.LOG.warn(
|
||||
"Skipping AE2WT arcane terminal registration: item is not an ItemWT implementation");
|
||||
return;
|
||||
}
|
||||
event.builder(ARCANE_TERMINAL_NAME,
|
||||
AE2WTArcaneTerminalMenuHost::new,
|
||||
ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL_TYPE,
|
||||
arcaneItem,
|
||||
Icon.CRAFTING)
|
||||
.addTerminal();
|
||||
// vis 连接卡准入全部通用终端功能(对齐 AE2WT 桥卡先例):奥术模式生效,
|
||||
// 其余模式装卡无作用但可随库存保留(卡片提示由 AE2WT 全终端机制统一处理)。
|
||||
UpgradeHelper.addUpgradeToAllTerminals(ModItems.VIS_CONNECTOR_CARD.get(), 1);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package thaumicenergistics.common.integration.ae2wt;
|
||||
|
||||
import java.util.Objects;
|
||||
import com.mojang.datafixers.util.Unit;
|
||||
import net.minecraft.core.component.DataComponentType;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.ItemContainerContents;
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.ids.AEComponents;
|
||||
import de.mari_023.ae2wtlib.api.AE2wtlibAPI;
|
||||
import de.mari_023.ae2wtlib.api.AE2wtlibComponents;
|
||||
import de.mari_023.ae2wtlib.api.registration.WTDefinition;
|
||||
import de.mari_023.ae2wtlib.api.terminal.ItemWT;
|
||||
import de.mari_023.ae2wtlib.api.terminal.ItemWUT;
|
||||
|
||||
/** 在副本中完整预演合并;组件冲突或卡片不能全部安装时拒绝,绝不丢弃尾量。 */
|
||||
public final class SafeTerminalMerge {
|
||||
private SafeTerminalMerge() {
|
||||
}
|
||||
|
||||
public static ItemStack merge(ItemStack arcane, ItemStack other, String partner) {
|
||||
var definition = WTDefinition.ofOrNull(arcane);
|
||||
if (definition == null || !AE2WTCompat.ARCANE_TERMINAL_NAME.equals(definition.terminalName())
|
||||
|| !(arcane.getItem() instanceof ItemWT arcaneItem)) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
var otherDefinition = WTDefinition.ofOrNull(other);
|
||||
if (otherDefinition == null || !(other.getItem() instanceof ItemWT otherItem)) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
boolean universal = AE2wtlibAPI.isUniversalTerminal(other);
|
||||
if (partner.isEmpty() ? !universal : universal || !partner.equals(otherDefinition.terminalName())) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
if (universal && other.has(definition.componentType())) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
ItemStack result = universal ? other.copyWithCount(1) : new ItemStack(AE2wtlibAPI.getWUT());
|
||||
if (!(result.getItem() instanceof ItemWUT output)) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
if (!universal && !copyComponents(other, result)) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
if (!copyComponents(arcane, result)) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
result.set(definition.componentType(), Unit.INSTANCE);
|
||||
if (!universal) {
|
||||
result.set(otherDefinition.componentType(), Unit.INSTANCE);
|
||||
}
|
||||
result.remove(AEComponents.UPGRADES);
|
||||
result.remove(AEComponents.STORED_ENERGY);
|
||||
result.remove(AEComponents.ENERGY_CAPACITY);
|
||||
var upgrades = output.getUpgrades(result);
|
||||
for (ItemStack input : new ItemStack[]{other.copy(), arcane.copy()}) {
|
||||
var item = (ItemWT) input.getItem();
|
||||
for (var card : item.getUpgrades(input)) {
|
||||
if (!card.isEmpty() && !upgrades.addItems(card.copy()).isEmpty()) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
}
|
||||
}
|
||||
output.onUpgradesChanged(result, upgrades);
|
||||
double power = arcaneItem.getAECurrentPower(arcane) + otherItem.getAECurrentPower(other);
|
||||
if (!Double.isFinite(power) || power < 0) return ItemStack.EMPTY;
|
||||
output.injectAEPower(result, power, Actionable.MODULATE);
|
||||
if (output.getAECurrentPower(result) + 1.0e-6 < power) return ItemStack.EMPTY;
|
||||
return result;
|
||||
}
|
||||
|
||||
private static boolean copyComponents(ItemStack source, ItemStack target) {
|
||||
for (var entry : source.getComponentsPatch().entrySet()) {
|
||||
var type = entry.getKey();
|
||||
if (type == AEComponents.UPGRADES || type == AEComponents.STORED_ENERGY
|
||||
|| type == AEComponents.ENERGY_CAPACITY || type == AE2wtlibComponents.CURRENT_TERMINAL) {
|
||||
continue;
|
||||
}
|
||||
// 空组件不能覆盖通用终端已有的法杖、材料或奇点。
|
||||
var value = entry.getValue().orElse(null);
|
||||
if (empty(value)) {
|
||||
continue;
|
||||
}
|
||||
var previous = target.get(type);
|
||||
if (!empty(previous) && !Objects.equals(previous, value)) {
|
||||
// 终端偏好以已有通用终端/另一终端为准;物品、奇点和绑定等资源数据仍拒绝冲突。
|
||||
if (preference(type)) continue;
|
||||
return false;
|
||||
}
|
||||
copyComponent(target, type, value);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean preference(DataComponentType<?> type) {
|
||||
return type == DataComponents.CUSTOM_NAME || type == DataComponents.LORE
|
||||
|| type == AE2wtlibComponents.PICKUP_CONFIG || type == AE2wtlibComponents.INSERT_CONFIG
|
||||
|| type == AE2wtlibComponents.PICKUP_MODE || type == AE2wtlibComponents.INSERT_MODE
|
||||
|| type == AE2wtlibComponents.RESTOCK || type == AE2wtlibComponents.PICK_BLOCK
|
||||
|| type == AE2wtlibComponents.CRAFT_IF_MISSING;
|
||||
}
|
||||
|
||||
private static boolean empty(Object value) {
|
||||
if (value == null) return true;
|
||||
if (value instanceof ItemStack stack) return stack.isEmpty();
|
||||
if (value instanceof ItemContainerContents contents) return contents.stream().allMatch(ItemStack::isEmpty);
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> void copyComponent(ItemStack target, DataComponentType<T> type, Object value) {
|
||||
target.set(type, (T) value);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import appeng.api.stacks.AEKey;
|
||||
import appeng.api.stacks.AEKeyType;
|
||||
import appeng.api.stacks.GenericStack;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
@@ -65,7 +66,10 @@ public final class AEssentiaKey extends AEKey {
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addDrops(long amount, List<ItemStack> drops, Level level, BlockPos pos) {
|
||||
// AE2 的包装物品保留精确的 long 数量,可用容器取回或在终端抽空。
|
||||
if (amount > 0) drops.add(GenericStack.wrapInItemStack(this, amount));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package thaumicenergistics.common.integration.appeng;
|
||||
|
||||
import appeng.api.behaviors.ContainerItemStrategy;
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.stacks.GenericStack;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaItemContainers;
|
||||
import thaumicenergistics.common.integration.tc.TCReflection;
|
||||
import thaumicenergistics.common.integration.tc.ThEEssentiaContainers;
|
||||
|
||||
/** 标准 AE2 填充/抽空和幽灵槽转换共用真实容器上下文。 */
|
||||
public final class EssentiaContainerItemStrategy
|
||||
implements ContainerItemStrategy<AEssentiaKey, EssentiaContainerItemStrategy.Context> {
|
||||
public record Context(Player player, @Nullable AbstractContainerMenu menu, int slot) {
|
||||
ItemStack stack() {
|
||||
return menu != null ? menu.getCarried() : player.getInventory().getItem(slot);
|
||||
}
|
||||
|
||||
void replace(ItemStack replacement) {
|
||||
var source = stack();
|
||||
if (source.getCount() == 1) {
|
||||
if (menu != null) menu.setCarried(replacement);
|
||||
else player.getInventory().setItem(slot, replacement);
|
||||
} else {
|
||||
source.shrink(1);
|
||||
if (!player.getInventory().add(replacement)) player.drop(replacement, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public GenericStack getContainedStack(ItemStack stack) {
|
||||
var recovered = recoveredContent(stack);
|
||||
if (recovered != null) return recovered;
|
||||
var contents = EssentiaItemContainers.contents(stack);
|
||||
for (var aspect : contents.getAspects()) {
|
||||
var id = TCReflection.getAspectId(aspect);
|
||||
if (id != null && contents.getAmount(aspect) > 0) {
|
||||
return new GenericStack(AEssentiaKey.of(id), contents.getAmount(aspect));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public Context findCarriedContext(Player player, AbstractContainerMenu menu) {
|
||||
return supported(menu.getCarried())
|
||||
? new Context(player, menu, -1) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public Context findPlayerSlotContext(Player player, int slot) {
|
||||
return slot >= 0 && slot < player.getInventory().getContainerSize()
|
||||
&& supported(player.getInventory().getItem(slot))
|
||||
? new Context(player, null, slot) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long extract(Context context, AEssentiaKey key, long amount, Actionable mode) {
|
||||
var recovered = recoveredContent(context.stack());
|
||||
if (recovered != null) {
|
||||
if (!recovered.what().equals(key) || amount <= 0) return 0;
|
||||
long extracted = Math.min(amount, recovered.amount());
|
||||
if (mode == Actionable.MODULATE) {
|
||||
long left = recovered.amount() - extracted;
|
||||
context.replace(left > 0 ? GenericStack.wrapInItemStack(key, left) : ItemStack.EMPTY);
|
||||
}
|
||||
return extracted;
|
||||
}
|
||||
var aspect = TCReflection.findAspectById(key.getId());
|
||||
if (aspect == null || amount <= 0) return 0;
|
||||
var contents = EssentiaItemContainers.contents(context.stack());
|
||||
int extracted = (int) Math.min(amount, contents.getAmount(aspect));
|
||||
if (extracted <= 0) return 0;
|
||||
contents.remove(aspect, extracted);
|
||||
var replacement = EssentiaItemContainers.withContents(context.stack(), contents);
|
||||
if (replacement == null) return 0;
|
||||
if (mode == Actionable.MODULATE) context.replace(replacement);
|
||||
return extracted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long insert(Context context, AEssentiaKey key, long amount, Actionable mode) {
|
||||
if (!ThEEssentiaContainers.isEssentiaContainer(context.stack())) return 0;
|
||||
var aspect = TCReflection.findAspectById(key.getId());
|
||||
if (aspect == null || amount <= 0) return 0;
|
||||
var contents = EssentiaItemContainers.contents(context.stack());
|
||||
for (var existing : contents.getAspects()) {
|
||||
if (existing != aspect) return 0;
|
||||
}
|
||||
int capacity = ThEEssentiaContainers.isJar(context.stack()) ? 64 : 8;
|
||||
int inserted = (int) Math.min(amount, Math.max(0, capacity - contents.getAmount(aspect)));
|
||||
if (inserted <= 0) return 0;
|
||||
contents.add(aspect, inserted);
|
||||
var replacement = EssentiaItemContainers.withContents(context.stack(), contents);
|
||||
if (replacement == null) return 0;
|
||||
if (mode == Actionable.MODULATE) context.replace(replacement);
|
||||
return inserted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playFillSound(Player player, AEssentiaKey key) {
|
||||
player.playSound(net.minecraft.sounds.SoundEvents.BOTTLE_FILL, 1, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playEmptySound(Player player, AEssentiaKey key) {
|
||||
player.playSound(net.minecraft.sounds.SoundEvents.BOTTLE_EMPTY, 1, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public GenericStack getExtractableContent(Context context) {
|
||||
return getContainedStack(context.stack());
|
||||
}
|
||||
|
||||
private static boolean supported(ItemStack stack) {
|
||||
return ThEEssentiaContainers.isEssentiaContainer(stack) || recoveredContent(stack) != null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static GenericStack recoveredContent(ItemStack stack) {
|
||||
var wrapped = GenericStack.unwrapItemStack(stack);
|
||||
return wrapped != null && wrapped.what() instanceof AEssentiaKey && wrapped.amount() > 0
|
||||
? wrapped : null;
|
||||
}
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
package thaumicenergistics.common.integration.appeng;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
import appeng.helpers.externalstorage.GenericStackInv;
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.networking.IGrid;
|
||||
import appeng.api.networking.IGridNode;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.stacks.GenericStack;
|
||||
import appeng.api.storage.MEStorage;
|
||||
import appeng.api.upgrades.IUpgradeInventory;
|
||||
import appeng.core.definitions.AEItems;
|
||||
import appeng.helpers.InterfaceLogic;
|
||||
import appeng.helpers.InterfaceLogicHost;
|
||||
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
|
||||
import thaumicenergistics.api.storage.AspectStack;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.appeng.IEssentiaInterfaceLogic;
|
||||
import thaumicenergistics.common.integration.tc.AspectIds;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
|
||||
/** ME 接口的源质业务状态;Mixin 仅负责转发宿主字段和生命周期。 */
|
||||
public final class EssentiaInterfaceState implements IEssentiaInterfaceLogic {
|
||||
private final Supplier<MEStorage> networkStorage;
|
||||
private final Supplier<GenericStackInv> storage;
|
||||
private final Supplier<IUpgradeInventory> upgrades;
|
||||
private final Supplier<IActionSource> actionSource;
|
||||
private final Supplier<IGridNode> node;
|
||||
private AspectStack thE$essentiaBuffer = AspectStack.EMPTY;
|
||||
|
||||
public EssentiaInterfaceState(Supplier<MEStorage> networkStorage, Supplier<GenericStackInv> storage,
|
||||
Supplier<IUpgradeInventory> upgrades, Supplier<IActionSource> actionSource, Supplier<IGridNode> node) {
|
||||
this.networkStorage = networkStorage;
|
||||
this.storage = storage;
|
||||
this.upgrades = upgrades;
|
||||
this.actionSource = actionSource;
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
private boolean thE$hasEssentiaCard() {
|
||||
return upgrades.get().isInstalled(ModItems.ESSENTIA_UPGRADE_CARD.get());
|
||||
}
|
||||
|
||||
public boolean hasBuffered() {
|
||||
return !thE$essentiaBuffer.isEmpty();
|
||||
}
|
||||
|
||||
public void save(CompoundTag tag) {
|
||||
tag.remove("ThEEssentiaInterfaceBufferAspect");
|
||||
tag.remove("ThEEssentiaInterfaceBufferAmount");
|
||||
if (hasBuffered()) {
|
||||
tag.putString("ThEEssentiaInterfaceBufferAspect", thE$essentiaBuffer.aspectId().toString());
|
||||
tag.putLong("ThEEssentiaInterfaceBufferAmount", thE$essentiaBuffer.amount());
|
||||
}
|
||||
}
|
||||
|
||||
public void load(CompoundTag tag) {
|
||||
clear();
|
||||
var id = ResourceLocation.tryParse(tag.getString("ThEEssentiaInterfaceBufferAspect"));
|
||||
long amount = tag.getLong("ThEEssentiaInterfaceBufferAmount");
|
||||
if (id != null && amount > 0) thE$essentiaBuffer = new AspectStack(id, amount);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
thE$essentiaBuffer = AspectStack.EMPTY;
|
||||
}
|
||||
|
||||
public void addBufferedDrops(List<ItemStack> drops) {
|
||||
if (hasBuffered()) {
|
||||
var key = AEssentiaKey.of(thE$essentiaBuffer.aspectId());
|
||||
drops.add(GenericStack.wrapInItemStack(key, thE$essentiaBuffer.amount()));
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public boolean thE$essentiaActive() {
|
||||
// 联网判据用 networkStorage(InterfaceLogic 自身即以它作「是否挂网」的判断,见 getInventory())
|
||||
return thE$hasEssentiaCard() && networkStorage.get() != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int thE$simulateAcceptEssentia(Aspect aspect, int amount) {
|
||||
if (!thE$essentiaActive() || aspect == null || amount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
AEssentiaKey key = thE$essentiaKey(aspect);
|
||||
if (key == null) {
|
||||
return 0;
|
||||
}
|
||||
// 模拟只检查容量,不搬动缓冲中的资源。
|
||||
if (!this.thE$essentiaBuffer.isEmpty() && !this.thE$essentiaBuffer.aspectId().equals(key.getId())) {
|
||||
return 0;
|
||||
}
|
||||
int want = Math.min(amount, thE$transportLimit());
|
||||
long room = networkStorage.get().insert(key, want, Actionable.SIMULATE, actionSource.get());
|
||||
return (int) Math.min(room, want);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int thE$acceptEssentia(Aspect aspect, int amount) {
|
||||
if (!thE$essentiaActive() || aspect == null || amount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
AEssentiaKey key = thE$essentiaKey(aspect);
|
||||
if (key == null) {
|
||||
return 0;
|
||||
}
|
||||
// 缓冲被异类占用 → 先冲;仍占用则拒收(源质留在外部,绝不丢弃)
|
||||
if (!this.thE$essentiaBuffer.isEmpty() && !this.thE$essentiaBuffer.aspectId().equals(key.getId())) {
|
||||
thE$flushEssentiaBuffer();
|
||||
if (!this.thE$essentiaBuffer.isEmpty() && !this.thE$essentiaBuffer.aspectId().equals(key.getId())) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int want = Math.min(amount, thE$transportLimit());
|
||||
long room = networkStorage.get().insert(key, want, Actionable.SIMULATE, actionSource.get());
|
||||
if (room <= 0) {
|
||||
return 0;
|
||||
}
|
||||
int accepted = (int) Math.min(room, want);
|
||||
long existing = this.thE$essentiaBuffer.isEmpty() ? 0 : this.thE$essentiaBuffer.amount();
|
||||
this.thE$essentiaBuffer = new AspectStack(key.getId(), existing + accepted);
|
||||
thE$saveHost();
|
||||
// 尽力立即注入(残留留缓冲,交 tick 循环下轮冲)
|
||||
thE$flushEssentiaBuffer();
|
||||
return accepted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Aspect thE$stockAspect() {
|
||||
if (!thE$essentiaActive()) {
|
||||
return null;
|
||||
}
|
||||
// TC 传输面是单要素契约;遍历实际库存大小以覆盖扩展接口。
|
||||
for (int i = 0; i < storage.get().size(); i++) {
|
||||
if (storage.get().getKey(i) instanceof AEssentiaKey key) {
|
||||
return AspectIds.findAspectById(key.getId());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int thE$stockAmount(Aspect aspect) {
|
||||
if (!thE$essentiaActive() || aspect == null) {
|
||||
return 0;
|
||||
}
|
||||
AEssentiaKey key = thE$essentiaKey(aspect);
|
||||
if (key == null) {
|
||||
return 0;
|
||||
}
|
||||
long sum = 0;
|
||||
for (int i = 0; i < storage.get().size(); i++) {
|
||||
if (storage.get().getKey(i) instanceof AEssentiaKey k && k.equals(key)) {
|
||||
sum += storage.get().getAmount(i);
|
||||
}
|
||||
}
|
||||
return (int) Math.min(sum, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int thE$simulateTakeFromStock(Aspect aspect, int amount) {
|
||||
if (!thE$essentiaActive() || aspect == null || amount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
AEssentiaKey key = thE$essentiaKey(aspect);
|
||||
if (key == null) {
|
||||
return 0;
|
||||
}
|
||||
long canTake = storage.get().extract(key, amount, Actionable.SIMULATE, actionSource.get());
|
||||
return (int) Math.min(canTake, amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int thE$takeFromStock(Aspect aspect, int amount) {
|
||||
if (!thE$essentiaActive() || aspect == null || amount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
AEssentiaKey key = thE$essentiaKey(aspect);
|
||||
if (key == null) {
|
||||
return 0;
|
||||
}
|
||||
// 仅从缓存格(stock 槽)取出——禁止直取网络
|
||||
long taken = storage.get().extract(key, amount, Actionable.MODULATE, actionSource.get());
|
||||
return (int) taken;
|
||||
}
|
||||
|
||||
/** 把缓冲里的源质注入网络(成功即落盘 + 按实际入网量 double 记账)。@return 本次注入量 */
|
||||
public long thE$flushEssentiaBuffer() {
|
||||
if (this.thE$essentiaBuffer.isEmpty() || networkStorage.get() == null) {
|
||||
return 0;
|
||||
}
|
||||
AEssentiaKey key = AEssentiaKey.of(this.thE$essentiaBuffer.aspectId());
|
||||
if (key == null) {
|
||||
this.thE$essentiaBuffer = AspectStack.EMPTY;
|
||||
return 0;
|
||||
}
|
||||
var grid = thE$grid();
|
||||
if (grid == null) return 0;
|
||||
long injected = thaumicenergistics.common.essentia.capability.EssentiaEnergy.transfer(
|
||||
grid, this.thE$essentiaBuffer.amount(), allowed -> networkStorage.get().insert(
|
||||
key, allowed, Actionable.MODULATE, actionSource.get()));
|
||||
if (injected <= 0) {
|
||||
return 0;
|
||||
}
|
||||
long left = this.thE$essentiaBuffer.amount() - injected;
|
||||
this.thE$essentiaBuffer = left > 0
|
||||
? new AspectStack(this.thE$essentiaBuffer.aspectId(), left)
|
||||
: AspectStack.EMPTY;
|
||||
thE$saveHost();
|
||||
return injected;
|
||||
}
|
||||
|
||||
/** 通知宿主保存(缓冲为新增字段,需显式落盘)。经节点 owner 取得宿主,不新增 @Shadow。 */
|
||||
private void thE$saveHost() {
|
||||
IGridNode node = thE$actionableNode();
|
||||
Object owner = node != null ? node.getOwner() : null;
|
||||
if (owner instanceof InterfaceLogicHost host) {
|
||||
host.saveChanges();
|
||||
}
|
||||
}
|
||||
|
||||
/** 本逻辑所在网格(未挂网 → null)。经公开 getActionableNode() 取得,避开父类陷阱。 */
|
||||
private IGrid thE$grid() {
|
||||
IGridNode node = thE$actionableNode();
|
||||
return node != null ? node.getGrid() : null;
|
||||
}
|
||||
|
||||
private IGridNode thE$actionableNode() {
|
||||
return node.get();
|
||||
}
|
||||
|
||||
/** 单次搬运上限 = 8 × 每 tick 操作次数(仅计 AE2 加速卡,与供应器同口径)。 */
|
||||
private int thE$transportLimit() {
|
||||
int installed = upgrades.get().getInstalledUpgrades(AEItems.SPEED_CARD);
|
||||
int ops = switch (installed) {
|
||||
default -> 1;
|
||||
case 1 -> 8;
|
||||
case 2 -> 32;
|
||||
case 3 -> 64;
|
||||
case 4 -> 96;
|
||||
};
|
||||
return 8 * Math.max(1, ops);
|
||||
}
|
||||
|
||||
/** Aspect → AEssentiaKey(转换为空 → null)。 */
|
||||
private AEssentiaKey thE$essentiaKey(Aspect aspect) {
|
||||
if (aspect == null) {
|
||||
return null;
|
||||
}
|
||||
ResourceLocation id = AspectIds.getAspectId(aspect);
|
||||
return id == null ? null : AEssentiaKey.of(id);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package thaumicenergistics.common.integration.appeng;
|
||||
|
||||
import appeng.api.networking.IGrid;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.upgrades.IUpgradeableObject;
|
||||
import appeng.helpers.patternprovider.PatternProviderTarget;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import thaumcraft.api.aspects.IAspectContainer;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaEndpoints;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/** 所有供应器共用已持有资源的输出目标;可选兼容层仅提供宿主和访问面。 */
|
||||
public final class ProviderEssentiaTargets {
|
||||
private ProviderEssentiaTargets() { }
|
||||
|
||||
public static boolean hasCard(Object host) {
|
||||
return host instanceof IUpgradeableObject upgradeable
|
||||
&& upgradeable.getUpgrades().isInstalled(ModItems.ESSENTIA_UPGRADE_CARD.get());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PatternProviderTarget wrap(@Nullable PatternProviderTarget original, @Nullable IGrid grid,
|
||||
IActionSource source, @Nullable BlockEntity target, @Nullable Direction face) {
|
||||
if (grid == null || target == null || !(target instanceof IAspectContainer)
|
||||
&& EssentiaEndpoints.transport(target, face) == null) return original;
|
||||
if (original instanceof ThEEssentiaPushTarget || original instanceof ThECompositePushTarget) return original;
|
||||
var essentia = new ThEEssentiaPushTarget(grid, source, target, face);
|
||||
return original == null ? essentia : new ThECompositePushTarget(original, essentia);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PatternProviderTarget fromSource(@Nullable PatternProviderTarget original, IActionSource source,
|
||||
@Nullable BlockEntity target, @Nullable Direction face) {
|
||||
var machine = source.machine().orElse(null);
|
||||
if (!hasCard(machine)) return original;
|
||||
var node = machine.getActionableNode();
|
||||
return wrap(original, node != null ? node.getGrid() : null, source, target, face);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package thaumicenergistics.common.integration.appeng;
|
||||
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
|
||||
public final class ThEAppliedEnergistics {
|
||||
private static final Logger LOG = LoggerFactory.getLogger("ThE-AE2");
|
||||
private ThEAppliedEnergistics() {}
|
||||
public static void init() { LOG.info("ThaumicEnergistics AE2 integration stub loaded."); }
|
||||
}
|
||||
+9
-31
@@ -6,7 +6,6 @@ import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.PowerMultiplier;
|
||||
import appeng.api.networking.IGrid;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.stacks.AEKey;
|
||||
@@ -14,31 +13,14 @@ import appeng.helpers.patternprovider.PatternProviderTarget;
|
||||
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.IAspectContainer;
|
||||
import thaumcraft.api.aspects.IEssentiaTransport;
|
||||
|
||||
import thaumicenergistics.common.essentia.capability.EssentiaTransfer;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaConversionHelper;
|
||||
import thaumicenergistics.common.integration.tc.TCReflection;
|
||||
|
||||
/**
|
||||
* T-M2-002(P-A 裁决):样板供应器<b>订单驱动源质输出</b>的推送落点(纯输出侧)。
|
||||
* <p>
|
||||
* <b>为什么复用导出总线范式</b>:TC {@code IEssentiaTransport.simulateAddEssentia} 的 default
|
||||
* 实现恒返 0(字节码实证:iconst_0,仅管道/储罐/结晶器覆写),若按字面 simulate/add 配对,
|
||||
* 罐子/蒸馏器等大半 TC 容器会被误判「不可接收」。故本类与 {@link EssentiaTransfer#push} 同范式:
|
||||
* MODULATE 直接走导出总线落点(IAspectContainer 优先 + addEssentia 回退),
|
||||
* SIMULATE 采用<b>类型级近似</b>({@code simulateAddEssentia > 0},拉取式机器回退
|
||||
* {@code isConnectable && canInputFrom},容器类回退 {@code doesContainerAccept},
|
||||
* <b>不验余量</b>)——余量缺口由 AE2 原生 sendList 重试兜底,
|
||||
* 验收口径为「下单后源质最终到位」。
|
||||
* <p>
|
||||
* <b>为什么不在 mixin 包</b>:本类是普通运行期类(由注入体直接 new),Mixin 框架禁止
|
||||
* mixin 声明包内类被普通代码直接引用(IllegalClassLoadError),故落 AE2 集成包——
|
||||
* 与 {@code IEssentiaInterfaceLogic}(T-M2-001 桥接接口)同一分层先例。
|
||||
* <p>
|
||||
* <b>为什么不收物品/流体</b>:源质交互分工制约定供应器 = 纯输出侧的源质通道;
|
||||
* 物品/流体产物回收仍走 AE2 原生(机器推回供应器),源质落点只认 {@link AEssentiaKey}。
|
||||
* 样板供应器的源质输出目标。CPU 已交付输入,因此只插入已持有资源,不再次提取网络。
|
||||
* 模拟按可接受类型预检,实际拒收余量由 AE2 sendList 保存并重试。
|
||||
*/
|
||||
public final class ThEEssentiaPushTarget implements PatternProviderTarget {
|
||||
|
||||
@@ -65,15 +47,10 @@ public final class ThEEssentiaPushTarget implements PatternProviderTarget {
|
||||
// 实际注入不足的部分由 pushPattern 的 addToSendList → sendStacksOut 原生重试
|
||||
return thE$typeAccepts(key) ? amount : 0;
|
||||
}
|
||||
// 与导出总线同款落点:IAspectContainer 优先 + addEssentia 回退;未注入部分退回网络,绝不丢料
|
||||
long injected = EssentiaTransfer.push(this.grid, this.source, key, amount, this.container, this.accessSide);
|
||||
if (injected > 0) {
|
||||
// 按实际搬运量 double 记账(禁止 (int) 截断),口径与导出总线 TRANSFER_POWER 一致
|
||||
this.grid.getEnergyService().extractAEPower(
|
||||
injected * EssentiaConversionHelper.AE_PER_ESSENTIA,
|
||||
Actionable.MODULATE, PowerMultiplier.CONFIG);
|
||||
}
|
||||
return injected;
|
||||
// CPU 已经交付输入;这里只交付已持有资源,未接收部分由供应器 sendList 重试。
|
||||
return thaumicenergistics.common.essentia.capability.EssentiaEnergy.transfer(
|
||||
grid, amount, allowed -> EssentiaTransfer.insertOwned(
|
||||
key, allowed, container, accessSide));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -84,7 +61,7 @@ public final class ThEEssentiaPushTarget implements PatternProviderTarget {
|
||||
@Override
|
||||
public boolean containsPatternInput(Set<AEKey> patternInputs) {
|
||||
try {
|
||||
for (var advertised : TCReflection.listEssentia(this.container)) {
|
||||
for (var advertised : thaumicenergistics.common.integration.tc.EssentiaEndpoints.contents(this.container, accessSide)) {
|
||||
for (var key : patternInputs) {
|
||||
if (key instanceof AEssentiaKey essentiaKey
|
||||
&& advertised.aspectId().equals(essentiaKey.getId())) {
|
||||
@@ -110,7 +87,8 @@ public final class ThEEssentiaPushTarget implements PatternProviderTarget {
|
||||
if (aspect == null) {
|
||||
return false;
|
||||
}
|
||||
if (this.container instanceof IEssentiaTransport transport
|
||||
var transport = thaumicenergistics.common.integration.tc.EssentiaEndpoints.transport(container, accessSide);
|
||||
if (transport != null
|
||||
&& (transport.simulateAddEssentia(aspect, 1, this.accessSide) > 0
|
||||
|| (transport.isConnectable(this.accessSide)
|
||||
&& transport.canInputFrom(this.accessSide)))) {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package thaumicenergistics.common.integration.extendedae;
|
||||
|
||||
import appeng.api.upgrades.Upgrades;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.neoforged.fml.ModList;
|
||||
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/**
|
||||
* Extended AE(extendedae)可选兼容:把源质访问卡准入注册到其扩展样板供应器与超大接口。
|
||||
* <p>
|
||||
* 为什么只做注册:EAE 两类宿主(方块/部件)的 Logic 均复用 AE2 的
|
||||
* {@code PatternProviderLogic} 与 {@code InterfaceLogic}(2.2.35 jar javap 实证),
|
||||
* 本项目对这两个 Logic 类的 Mixin(卡槽组 + 源质组)对其自动生效,
|
||||
* 唯一缺口是 {@code Upgrades.add} 宿主准入——此处补齐即可,零 EAE 编译引用。
|
||||
* <p>
|
||||
* 为什么升级库存宿主物品必然匹配:EAE 宿主的 {@code getTerminalIcon()} 覆写返回
|
||||
* EAE 自身物品(部件返回 part item、方块返回 EX_PATTERN_PROVIDER),超大接口走
|
||||
* AE2 {@code createLogic()} 传 {@code getItemFromBlockEntity()} / 构造器 partItem——
|
||||
* 与本类注册的四个 ID 一一对应,AE2 准入查询({@code Upgrades.getMaxInstallable})成立。
|
||||
*/
|
||||
public final class ThEExtendedAE {
|
||||
|
||||
public static final String MOD_ID = "extendedae";
|
||||
|
||||
private ThEExtendedAE() {
|
||||
}
|
||||
|
||||
public static void registerEssentiaUpgrades() {
|
||||
if (!ModList.get().isLoaded(MOD_ID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Item card = ModItems.ESSENTIA_UPGRADE_CARD.get();
|
||||
|
||||
// 同设备方块/部件显示名相同(EAE zh_cn/en_us lang 实证),tooltipGroup 传
|
||||
// EAE 方块翻译键使「支持设备」列表合并显示,对齐本项目 MGMT-TOOLTIP 范式。
|
||||
registerHost(card, "ex_pattern_provider", "block.extendedae.ex_pattern_provider");
|
||||
registerHost(card, "ex_pattern_provider_part", "block.extendedae.ex_pattern_provider");
|
||||
registerHost(card, "oversize_interface", "block.extendedae.oversize_interface");
|
||||
registerHost(card, "oversize_interface_part", "block.extendedae.oversize_interface");
|
||||
}
|
||||
|
||||
private static void registerHost(Item card, String path, String tooltipGroup) {
|
||||
ResourceLocation id = ResourceLocation.fromNamespaceAndPath(MOD_ID, path);
|
||||
|
||||
Item host = BuiltInRegistries.ITEM.getOptional(id).orElse(null);
|
||||
|
||||
if (host == null || host == Items.AIR) {
|
||||
// EAE 版本差异(增删设备/改 ID)时静默跳过该项,不允许启动失败。
|
||||
ThaumicEnergistics.LOG
|
||||
.warn("Skipping Extended AE essentia upgrade registration: missing host item {}", id);
|
||||
return;
|
||||
}
|
||||
|
||||
Upgrades.add(card, host, 1, tooltipGroup);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package thaumicenergistics.common.integration.tc;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
|
||||
/** 不可变要素键转换与注册表查找,不包含方块反射或资源转移。 */
|
||||
public final class AspectIds {
|
||||
private static final Map<String, ResourceLocation> ASPECT_ID_CACHE = new ConcurrentHashMap<>();
|
||||
private AspectIds() { }
|
||||
|
||||
@Nullable
|
||||
public static Aspect findAspectById(ResourceLocation id) {
|
||||
if (id == null) return null;
|
||||
if (Aspect.aspects == null) return null;
|
||||
ensureAspectCache();
|
||||
String lowerTag = id.getPath().toLowerCase(Locale.ROOT);
|
||||
Aspect cached = ASPECT_BY_TAG.get(lowerTag);
|
||||
if (cached != null) return cached;
|
||||
// 缓存 miss:运行期(post-init)可能注册了新 aspect,回退一次实时遍历并补入缓存
|
||||
for (Aspect aspect : Aspect.aspects.values()) {
|
||||
if (aspect != null && aspect.getTag() != null && aspect.getTag().equalsIgnoreCase(id.getPath())) {
|
||||
ASPECT_BY_TAG.putIfAbsent(lowerTag, aspect);
|
||||
return aspect;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** tag(小写) → Aspect 反向缓存,避免每次调用 O(n) 遍历 Aspect.aspects。 */
|
||||
private static final Map<String, Aspect> ASPECT_BY_TAG = new ConcurrentHashMap<>();
|
||||
private static volatile boolean aspectCacheBuilt = false;
|
||||
|
||||
private static void ensureAspectCache() {
|
||||
if (aspectCacheBuilt) return;
|
||||
synchronized (ASPECT_BY_TAG) {
|
||||
if (aspectCacheBuilt) return;
|
||||
for (Aspect aspect : Aspect.aspects.values()) {
|
||||
if (aspect != null && aspect.getTag() != null) {
|
||||
ASPECT_BY_TAG.putIfAbsent(aspect.getTag().toLowerCase(Locale.ROOT), aspect);
|
||||
}
|
||||
}
|
||||
aspectCacheBuilt = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static ResourceLocation getAspectId(@Nullable Aspect aspect) {
|
||||
if (aspect == null) return null;
|
||||
String tag = aspect.getTag();
|
||||
if (tag == null || tag.isEmpty()) return null;
|
||||
return ASPECT_ID_CACHE.computeIfAbsent(tag.toLowerCase(Locale.ROOT), t ->
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", t));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package thaumicenergistics.common.integration.tc;
|
||||
|
||||
import java.util.List;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import thaumcraft.api.aspects.EssentiaCapabilities;
|
||||
import thaumcraft.api.aspects.IEssentiaTransport;
|
||||
import thaumcraft.common.blockentities.JarBlockEntity;
|
||||
import thaumicenergistics.api.storage.AspectStack;
|
||||
|
||||
/** TC 能力优先,固定版本的炼金炉等遗留容器由兼容回退处理。 */
|
||||
public final class EssentiaEndpoints {
|
||||
private EssentiaEndpoints() {
|
||||
}
|
||||
|
||||
/** ME accesses the jar's contents from any face; other machines retain their sided ports. */
|
||||
@Nullable
|
||||
public static Direction accessSide(BlockEntity be, @Nullable Direction side) {
|
||||
return be instanceof JarBlockEntity && side != null ? Direction.UP : side;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static IEssentiaTransport transport(BlockEntity be, @Nullable Direction side) {
|
||||
return be == null || be.getLevel() == null ? null
|
||||
: EssentiaCapabilities.find(be.getLevel(), be.getBlockPos(), side);
|
||||
}
|
||||
|
||||
public static List<AspectStack> contents(BlockEntity be, @Nullable Direction side) {
|
||||
side = accessSide(be, side);
|
||||
var transport = transport(be, side);
|
||||
if (transport == null || side == null) return TCReflection.listEssentia(be);
|
||||
if (!transport.isConnectable(side) || !transport.canOutputTo(side)) return List.of();
|
||||
var id = AspectIds.getAspectId(transport.getEssentiaType(side));
|
||||
int amount = transport.getEssentiaAmount(side);
|
||||
return id == null || amount <= 0 ? List.of() : List.of(new AspectStack(id, amount));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static AspectStack extract(BlockEntity be, ResourceLocation id, int amount, @Nullable Direction side) {
|
||||
side = accessSide(be, side);
|
||||
var transport = transport(be, side);
|
||||
if (transport == null || side == null) return TCReflection.extractEssentia(be, id, amount);
|
||||
var aspect = AspectIds.findAspectById(id);
|
||||
if (aspect == null || !transport.isConnectable(side) || !transport.canOutputTo(side)) return null;
|
||||
int taken = Math.max(0, Math.min(amount, transport.takeEssentia(aspect, amount, side)));
|
||||
if (taken > 0) {
|
||||
be.setChanged();
|
||||
return new AspectStack(id, taken);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int insert(BlockEntity be, ResourceLocation id, int amount, @Nullable Direction side) {
|
||||
if (amount <= 0 || (be instanceof JarBlockEntity jar
|
||||
&& !jar.doesContainerAccept(AspectIds.findAspectById(id)))) return 0;
|
||||
side = accessSide(be, side);
|
||||
var transport = transport(be, side);
|
||||
if (transport == null || side == null) {
|
||||
return TCReflection.insertEssentia(be, new AspectStack(id, amount));
|
||||
}
|
||||
var aspect = AspectIds.findAspectById(id);
|
||||
if (aspect == null || !transport.isConnectable(side) || !transport.canInputFrom(side)) return 0;
|
||||
int inserted = Math.max(0, Math.min(amount, transport.addEssentia(aspect, amount, side)));
|
||||
if (inserted > 0) be.setChanged();
|
||||
return inserted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package thaumicenergistics.common.integration.tc;
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import thaumcraft.api.aspects.IEssentiaContainerItem;
|
||||
|
||||
/** 按 TC 的真实物品组件保存剩余源质,不把部分成功假定为可回滚的事务。 */
|
||||
public final class EssentiaItemContainers {
|
||||
private EssentiaItemContainers() {
|
||||
}
|
||||
|
||||
public static AspectList contents(ItemStack stack) {
|
||||
if (ThEEssentiaContainers.isEssentiaContainer(stack)
|
||||
&& stack.getItem() instanceof IEssentiaContainerItem container) {
|
||||
var aspects = container.getAspects(stack);
|
||||
if (aspects != null) {
|
||||
return aspects.copy();
|
||||
}
|
||||
}
|
||||
return new AspectList();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static ItemStack withContents(ItemStack original, AspectList contents) {
|
||||
ItemStack result;
|
||||
if (ThEEssentiaContainers.isJar(original)) {
|
||||
result = original.copyWithCount(1);
|
||||
} else if (ThEEssentiaContainers.isPhial(original)) {
|
||||
String path = contents.isEmpty() ? "glass_phial" : "phial_of_essentia";
|
||||
var item = BuiltInRegistries.ITEM.getOptional(
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", path)).orElse(null);
|
||||
if (item == null) {
|
||||
return null;
|
||||
}
|
||||
result = new ItemStack(item);
|
||||
result.applyComponents(original.getComponentsPatch());
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (result.getItem() instanceof IEssentiaContainerItem container) {
|
||||
container.setAspects(result, contents);
|
||||
var actual = contents(result);
|
||||
for (Aspect aspect : contents.getAspects()) {
|
||||
if (actual.getAmount(aspect) != contents.getAmount(aspect)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (actual.visSize() != contents.visSize()) {
|
||||
return null;
|
||||
}
|
||||
} else if (!contents.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
// Jars never change identity when filled or drained. Phials intentionally change item type.
|
||||
// Enforce this for both native AE2 container interactions and our terminal packet paths.
|
||||
if (ThEEssentiaContainers.isJar(original) && result.getItem() != original.getItem()) {
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package thaumicenergistics.common.integration.tc;
|
||||
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import thaumicenergistics.api.storage.AspectStack;
|
||||
|
||||
/** port.261 炼金炉的私有方面缓存兼容,公开 capability 无法覆盖时才调用。 */
|
||||
final class LegacyFurnaceEssentia {
|
||||
private static volatile java.lang.reflect.Field furnaceAspectsField;
|
||||
private static final java.util.Set<Class<?>> WARNED = java.util.concurrent.ConcurrentHashMap.newKeySet();
|
||||
private LegacyFurnaceEssentia() { }
|
||||
|
||||
/** 读取荒古炼金炉 private aspects 字段(不实现 IAspectContainer;只读,返回活引用用于原地修改)。 */
|
||||
@Nullable
|
||||
static AspectList getFurnaceAspects(BlockEntity be) {
|
||||
try {
|
||||
if (furnaceAspectsField == null) {
|
||||
furnaceAspectsField = be.getClass().getDeclaredField("aspects");
|
||||
furnaceAspectsField.setAccessible(true);
|
||||
}
|
||||
Object raw = furnaceAspectsField.get(be);
|
||||
return raw instanceof AspectList list ? list : null;
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
if (WARNED.add(be.getClass())) thaumicenergistics.ThaumicEnergistics.LOG.warn(
|
||||
"Legacy furnace essentia adapter cannot read {}: {}", be.getClass().getName(), e.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 荒古炼金炉写回(aspects 为 private 字段,无公开写入 API)。返回实际写入量。 */
|
||||
static int addToFurnace(BlockEntity be, Aspect aspect, int amount) {
|
||||
if (amount <= 0) return 0;
|
||||
try {
|
||||
AspectList list = getFurnaceAspects(be);
|
||||
if (list == null) {
|
||||
if (furnaceAspectsField == null) return 0;
|
||||
list = new AspectList();
|
||||
furnaceAspectsField.set(be, list);
|
||||
}
|
||||
list.add(aspect, amount);
|
||||
be.setChanged();
|
||||
return amount;
|
||||
} catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** 从荒古炼金炉内部源质缓存直接抽取(替代蒸馏釜/罐子中转)。only 非空时只抽指定方面。 */
|
||||
@Nullable
|
||||
static AspectStack extractFromFurnace(BlockEntity be, @Nullable ResourceLocation only, int maxAmount) {
|
||||
AspectList furnaceAspects = getFurnaceAspects(be);
|
||||
if (furnaceAspects == null || furnaceAspects.size() <= 0) return null;
|
||||
for (Aspect aspect : furnaceAspects.getAspects()) {
|
||||
if (aspect == null) continue;
|
||||
int amt = furnaceAspects.getAmount(aspect);
|
||||
if (amt <= 0) continue;
|
||||
ResourceLocation id = AspectIds.getAspectId(aspect);
|
||||
if (id == null) continue;
|
||||
if (only != null && !only.equals(id)) continue;
|
||||
int toExtract = Math.min(amt, maxAmount);
|
||||
furnaceAspects.remove(aspect, toExtract);
|
||||
be.setChanged();
|
||||
return new AspectStack(id, toExtract);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,13 +7,12 @@ import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.CustomData;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import thaumicenergistics.common.tiles.TileArcaneAssembler;
|
||||
|
||||
/**
|
||||
* 从 AE2 {@link IPatternDetails} 中提取 TC 研究键的辅助类。
|
||||
*
|
||||
* 两种样板携带研究键的方式:
|
||||
* - 奥术装配器样板 {@link TileArcaneAssembler.ArcaneAssemblerPattern}:直接持 research 字段
|
||||
* - 奥术装配器样板 {@link thaumicenergistics.common.crafting.ArcaneAssemblerPattern}:直接持 research 字段
|
||||
* - 蒸馏处理样板(AE2 标准 processing pattern):通过样板上 DataComponents.CUSTOM_DATA 的 research 字段标记
|
||||
*/
|
||||
public final class PatternResearchHelper {
|
||||
@@ -27,7 +26,7 @@ public final class PatternResearchHelper {
|
||||
*/
|
||||
@Nullable
|
||||
public static String getResearch(IPatternDetails pattern) {
|
||||
if (pattern instanceof TileArcaneAssembler.ArcaneAssemblerPattern arcanePattern) {
|
||||
if (pattern instanceof thaumicenergistics.common.crafting.ArcaneAssemblerPattern arcanePattern) {
|
||||
return arcanePattern.getResearch();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package thaumicenergistics.common.integration.tc;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@@ -16,69 +15,11 @@ import thaumicenergistics.api.storage.AspectStack;
|
||||
|
||||
public final class TCReflection {
|
||||
|
||||
/** aspect tag → ResourceLocation 缓存(tag 有界:6 个源质 + 已注册方面)。 */
|
||||
private static final Map<String, ResourceLocation> ASPECT_ID_CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
/** 荒古炼金炉类名(TC port;不实现 IAspectContainer,需反射抽内部源质)。 */
|
||||
private static final String FURNACE_CLASS_NAME = "thaumcraft.common.blockentities.AlchemicalFurnaceBlockEntity";
|
||||
/** 炼金炉 private aspects 字段(缓存 Field 避免每 tick getDeclaredField)。 */
|
||||
private static volatile java.lang.reflect.Field furnaceAspectsField;
|
||||
|
||||
private TCReflection() {}
|
||||
|
||||
/** 读取荒古炼金炉 private aspects 字段(不实现 IAspectContainer;只读,返回活引用用于原地修改)。 */
|
||||
@Nullable
|
||||
private static AspectList getFurnaceAspects(BlockEntity be) {
|
||||
try {
|
||||
if (furnaceAspectsField == null) {
|
||||
furnaceAspectsField = be.getClass().getDeclaredField("aspects");
|
||||
furnaceAspectsField.setAccessible(true);
|
||||
}
|
||||
Object raw = furnaceAspectsField.get(be);
|
||||
return raw instanceof AspectList list ? list : null;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 荒古炼金炉写回(aspects 为 private 字段,无公开写入 API)。返回实际写入量。 */
|
||||
private static int addToFurnace(BlockEntity be, Aspect aspect, int amount) {
|
||||
if (amount <= 0) return 0;
|
||||
try {
|
||||
AspectList list = getFurnaceAspects(be);
|
||||
if (list == null) {
|
||||
if (furnaceAspectsField == null) return 0;
|
||||
list = new AspectList();
|
||||
furnaceAspectsField.set(be, list);
|
||||
}
|
||||
list.add(aspect, amount);
|
||||
be.setChanged();
|
||||
return amount;
|
||||
} catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** 从荒古炼金炉内部源质缓存直接抽取(替代蒸馏釜/罐子中转)。only 非空时只抽指定方面。 */
|
||||
@Nullable
|
||||
private static AspectStack extractFromFurnace(BlockEntity be, @Nullable ResourceLocation only, int maxAmount) {
|
||||
AspectList furnaceAspects = getFurnaceAspects(be);
|
||||
if (furnaceAspects == null || furnaceAspects.size() <= 0) return null;
|
||||
for (Aspect aspect : furnaceAspects.getAspects()) {
|
||||
if (aspect == null) continue;
|
||||
int amt = furnaceAspects.getAmount(aspect);
|
||||
if (amt <= 0) continue;
|
||||
ResourceLocation id = getAspectId(aspect);
|
||||
if (id == null) continue;
|
||||
if (only != null && !only.equals(id)) continue;
|
||||
int toExtract = Math.min(amt, maxAmount);
|
||||
furnaceAspects.remove(aspect, toExtract);
|
||||
be.setChanged();
|
||||
return new AspectStack(id, toExtract);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static AspectStack extractEssentia(@Nullable BlockEntity be, int maxAmount) {
|
||||
return extractEssentia(be, null, maxAmount);
|
||||
@@ -95,7 +36,7 @@ public final class TCReflection {
|
||||
// ===== 路径0: 荒古炼金炉直连(AlchemicalFurnaceBlockEntity 不实现 IAspectContainer,
|
||||
// 源质在 private aspects 缓存——直接抽取,替代"必须经蒸馏釜/罐子")=====
|
||||
if (FURNACE_CLASS_NAME.equals(be.getClass().getName())) {
|
||||
AspectStack fromFurnace = extractFromFurnace(be, only, maxAmount);
|
||||
AspectStack fromFurnace = LegacyFurnaceEssentia.extractFromFurnace(be, only, maxAmount);
|
||||
if (fromFurnace != null) return fromFurnace;
|
||||
}
|
||||
// ===== 路径0b: TC 管道接口(EssentiaTransport——高级荒古炼金炉喷嘴/源质管道)=====
|
||||
@@ -174,7 +115,7 @@ public final class TCReflection {
|
||||
// 荒古炼金炉:不实现 IAspectContainer,源质在 private aspects 字段 → 反射写回。
|
||||
// (此前直接 return 导致导入总线"网络已满"时抽出的源质无处归还而消失)
|
||||
if (FURNACE_CLASS_NAME.equals(be.getClass().getName())) {
|
||||
addToFurnace(be, aspect, (int) stack.amount());
|
||||
LegacyFurnaceEssentia.addToFurnace(be, aspect, (int) stack.amount());
|
||||
return;
|
||||
}
|
||||
if (!(be instanceof IAspectContainer container)) return;
|
||||
@@ -188,7 +129,7 @@ public final class TCReflection {
|
||||
if (aspect == null) return 0;
|
||||
int toInsert = (int) Math.min(stack.amount(), Integer.MAX_VALUE);
|
||||
if (FURNACE_CLASS_NAME.equals(be.getClass().getName())) {
|
||||
return addToFurnace(be, aspect, toInsert);
|
||||
return LegacyFurnaceEssentia.addToFurnace(be, aspect, toInsert);
|
||||
}
|
||||
if (!(be instanceof IAspectContainer container)) return 0;
|
||||
int leftover = container.addToContainer(aspect, toInsert);
|
||||
@@ -205,7 +146,7 @@ public final class TCReflection {
|
||||
if (be == null) return result;
|
||||
// 荒古炼金炉(不实现 IAspectContainer)
|
||||
if (FURNACE_CLASS_NAME.equals(be.getClass().getName())) {
|
||||
AspectList furnaceAspects = getFurnaceAspects(be);
|
||||
AspectList furnaceAspects = LegacyFurnaceEssentia.getFurnaceAspects(be);
|
||||
if (furnaceAspects != null) {
|
||||
for (Aspect aspect : furnaceAspects.getAspects()) {
|
||||
if (aspect == null) continue;
|
||||
@@ -256,37 +197,7 @@ public final class TCReflection {
|
||||
|
||||
@Nullable
|
||||
public static Aspect findAspectById(ResourceLocation id) {
|
||||
if (id == null) return null;
|
||||
if (Aspect.aspects == null) return null;
|
||||
ensureAspectCache();
|
||||
String lowerTag = id.getPath().toLowerCase(Locale.ROOT);
|
||||
Aspect cached = ASPECT_BY_TAG.get(lowerTag);
|
||||
if (cached != null) return cached;
|
||||
// 缓存 miss:运行期(post-init)可能注册了新 aspect,回退一次实时遍历并补入缓存
|
||||
for (Aspect aspect : Aspect.aspects.values()) {
|
||||
if (aspect != null && aspect.getTag() != null && aspect.getTag().equalsIgnoreCase(id.getPath())) {
|
||||
ASPECT_BY_TAG.putIfAbsent(lowerTag, aspect);
|
||||
return aspect;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** tag(小写) → Aspect 反向缓存,避免每次调用 O(n) 遍历 Aspect.aspects。 */
|
||||
private static final Map<String, Aspect> ASPECT_BY_TAG = new ConcurrentHashMap<>();
|
||||
private static volatile boolean aspectCacheBuilt = false;
|
||||
|
||||
private static void ensureAspectCache() {
|
||||
if (aspectCacheBuilt) return;
|
||||
synchronized (ASPECT_BY_TAG) {
|
||||
if (aspectCacheBuilt) return;
|
||||
for (Aspect aspect : Aspect.aspects.values()) {
|
||||
if (aspect != null && aspect.getTag() != null) {
|
||||
ASPECT_BY_TAG.putIfAbsent(aspect.getTag().toLowerCase(Locale.ROOT), aspect);
|
||||
}
|
||||
}
|
||||
aspectCacheBuilt = true;
|
||||
}
|
||||
return AspectIds.findAspectById(id);
|
||||
}
|
||||
|
||||
/** 按方块实体类缓存反射方法(getAspect/getAmount),避免每次调用 getMethod。 */
|
||||
@@ -304,10 +215,7 @@ public final class TCReflection {
|
||||
|
||||
@Nullable
|
||||
public static ResourceLocation getAspectId(@Nullable Aspect aspect) {
|
||||
if (aspect == null) return null;
|
||||
String tag = aspect.getTag();
|
||||
if (tag == null || tag.isEmpty()) return null;
|
||||
return ASPECT_ID_CACHE.computeIfAbsent(tag.toLowerCase(Locale.ROOT), t ->
|
||||
ResourceLocation.fromNamespaceAndPath("thaumcraft", t));
|
||||
return AspectIds.getAspectId(aspect);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -198,7 +198,8 @@ public final class ThEThaumcraft {
|
||||
.setPages(
|
||||
new ResearchPage("tc.research_text.ESSENTIASTORAGE"),
|
||||
new ResearchPage(RecipeRegistration.STORAGE_COMPONENT_1K),
|
||||
new ResearchPage(new IArcaneRecipe[]{RecipeRegistration.STORAGE_COMPONENT_4K, RecipeRegistration.STORAGE_COMPONENT_16K, RecipeRegistration.STORAGE_COMPONENT_64K}))
|
||||
new ResearchPage(new IArcaneRecipe[]{RecipeRegistration.STORAGE_COMPONENT_4K, RecipeRegistration.STORAGE_COMPONENT_16K, RecipeRegistration.STORAGE_COMPONENT_64K,
|
||||
RecipeRegistration.STORAGE_COMPONENT_256K, RecipeRegistration.STORAGE_COMPONENT_1M, RecipeRegistration.STORAGE_COMPONENT_4M, RecipeRegistration.STORAGE_COMPONENT_16M, RecipeRegistration.STORAGE_COMPONENT_64M, RecipeRegistration.STORAGE_COMPONENT_256M}))
|
||||
.registerResearchItem();
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,21 @@ public class VisProviderProxy extends TileVisNode {
|
||||
this.owner = new WeakReference<>(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* This node is never installed in a chunk. Its location may be air or any adjacent block,
|
||||
* so the real-block whitelist of BlockEntityType does not apply. The superclass constructor
|
||||
* calls this method before our fields are initialized; it must not depend on owner or level.
|
||||
*/
|
||||
@Override
|
||||
public boolean isValidBlockState(BlockState state) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setChanged() {
|
||||
// Entirely transient: graph changes must not dirty a real chunk or notify its neighbours.
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造后绑定所属部件与世界(BlockEntityType supplier 无法传入 owner,故在此注入)。
|
||||
*/
|
||||
@@ -62,7 +77,8 @@ public class VisProviderProxy extends TileVisNode {
|
||||
@Override
|
||||
public int consumeVis(Aspect aspect, int centivis) {
|
||||
VisInterfacePart part = this.owner.get();
|
||||
if (part == null || !part.isActive()) {
|
||||
if (isRemoved() || part == null || !part.isActive() || centivis <= 0
|
||||
|| getLevel() == null || getLevel().isClientSide()) {
|
||||
return 0;
|
||||
}
|
||||
ResourceLocation aspectId = ResourceLocation.fromNamespaceAndPath("thaumcraft", aspect.tag());
|
||||
@@ -80,6 +96,14 @@ public class VisProviderProxy extends TileVisNode {
|
||||
|
||||
@Override
|
||||
public void invalidate() {
|
||||
VisNetHandler.removeNode(this);
|
||||
setRemoved();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRemoved() {
|
||||
if (isRemoved()) return;
|
||||
this.owner.clear();
|
||||
// TileVisNode removes its graph, clears parent/children, and delegates to BlockEntity.
|
||||
super.setRemoved();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,8 +86,10 @@ public class HandlerKnowledgeCore {
|
||||
if (pattern == null || !pattern.isPatternValid()) return;
|
||||
if (!hasRoomToStorePattern()) return;
|
||||
|
||||
ArcaneCraftingPattern existing = getPatternForItem(pattern.getResult());
|
||||
if (existing == null) {
|
||||
var definition = pattern.writeToNBT(new CompoundTag());
|
||||
boolean exists = this.patterns.stream().anyMatch(existing ->
|
||||
existing.writeToNBT(new CompoundTag()).equals(definition));
|
||||
if (!exists) {
|
||||
this.patterns.add(pattern);
|
||||
saveKCoreData();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package thaumicenergistics.common.inventory;
|
||||
|
||||
import net.minecraft.core.component.DataComponentType;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.ItemContainerContents;
|
||||
import appeng.util.inv.AppEngInternalInventory;
|
||||
import appeng.util.inv.InternalInventoryHost;
|
||||
|
||||
public final class PersistedTerminalInventories {
|
||||
private PersistedTerminalInventories() {
|
||||
}
|
||||
|
||||
public static AppEngInternalInventory createPersistedInv(Player player, ItemStack stack, int size,
|
||||
DataComponentType<ItemContainerContents> component) {
|
||||
var inv = new AppEngInternalInventory(new InternalInventoryHost() {
|
||||
@Override
|
||||
public void saveChangedInventory(AppEngInternalInventory changed) {
|
||||
stack.set(component, changed.toItemContainerContents());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClientSide() {
|
||||
return player.level().isClientSide();
|
||||
}
|
||||
}, size);
|
||||
inv.fromItemContainerContents(stack.getOrDefault(component, ItemContainerContents.EMPTY));
|
||||
return inv;
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public class ItemEssentiaCell extends Item implements IBasicCellItem {
|
||||
public ItemEssentiaCell(Item.Properties props, String tier, int kilobytes, int bytesPerType, int totalTypes, double idleDrain) {
|
||||
super(props.stacksTo(1));
|
||||
this.tier = tier;
|
||||
this.totalBytes = kilobytes * 1024;
|
||||
this.totalBytes = Math.multiplyExact(kilobytes, 1024);
|
||||
this.bytesPerType = bytesPerType;
|
||||
this.totalTypes = totalTypes;
|
||||
this.idleDrain = idleDrain;
|
||||
@@ -213,35 +213,43 @@ public class ItemEssentiaCell extends Item implements IBasicCellItem {
|
||||
}
|
||||
}
|
||||
|
||||
//shift+右键 返回 对应等级存储组件+源质存储外壳
|
||||
// Only empty cells may be disassembled; return upgrades without losing them.
|
||||
@Override
|
||||
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
|
||||
ItemStack held = player.getItemInHand(hand);
|
||||
|
||||
if (!level.isClientSide) {
|
||||
if (player.isShiftKeyDown()) {
|
||||
if (held.getItem() instanceof ItemEssentiaCell cellItem) {
|
||||
String tier = cellItem.getTier();
|
||||
if (!player.isShiftKeyDown()) return InteractionResultHolder.pass(held);
|
||||
Item componentItem = switch (tier) {
|
||||
case "1k" -> ModItems.STORAGE_COMPONENT_1K.get();
|
||||
case "4k" -> ModItems.STORAGE_COMPONENT_4K.get();
|
||||
case "16k" -> ModItems.STORAGE_COMPONENT_16K.get();
|
||||
case "64k" -> ModItems.STORAGE_COMPONENT_64K.get();
|
||||
case "256k" -> ModItems.STORAGE_COMPONENT_256K.get();
|
||||
case "1m" -> ModItems.STORAGE_COMPONENT_1M.get();
|
||||
case "4m" -> ModItems.STORAGE_COMPONENT_4M.get();
|
||||
case "16m" -> ModItems.STORAGE_COMPONENT_16M.get();
|
||||
case "64m" -> ModItems.STORAGE_COMPONENT_64M.get();
|
||||
case "256m" -> ModItems.STORAGE_COMPONENT_256M.get();
|
||||
default -> null;
|
||||
};
|
||||
if(componentItem != null){
|
||||
player.addItem(new ItemStack(componentItem,1));
|
||||
player.addItem(new ItemStack(ModItems.STORAGE_CASING.get(),1));
|
||||
if (componentItem == null) return InteractionResultHolder.pass(held);
|
||||
if (!level.isClientSide) {
|
||||
BasicCellInventory inventory = BasicCellInventory.createInventory(held, null);
|
||||
// Fail closed if the storage handler could not read the cell.
|
||||
if (inventory == null || inventory.getStoredItemCount() != 0) {
|
||||
player.displayClientMessage(appeng.core.localization.PlayerMessages.OnlyEmptyCellsCanBeDisassembled.text(), true);
|
||||
return InteractionResultHolder.fail(held);
|
||||
}
|
||||
List<ItemStack> returned = new ArrayList<>();
|
||||
returned.add(new ItemStack(componentItem));
|
||||
returned.add(new ItemStack(ModItems.STORAGE_CASING.get()));
|
||||
getUpgrades(held).forEach(upgrade -> {
|
||||
if (!upgrade.isEmpty()) returned.add(upgrade.copy());
|
||||
});
|
||||
player.setItemInHand(hand, ItemStack.EMPTY);
|
||||
returned.forEach(player.getInventory()::placeItemBackInInventory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(player.isShiftKeyDown()){
|
||||
return InteractionResultHolder.success(ItemStack.EMPTY);
|
||||
}else{
|
||||
return InteractionResultHolder.pass(held);
|
||||
}
|
||||
return InteractionResultHolder.sidedSuccess(player.getItemInHand(hand), level.isClientSide);
|
||||
}
|
||||
|
||||
|
||||
@@ -258,6 +266,24 @@ public class ItemEssentiaCell extends Item implements IBasicCellItem {
|
||||
public static ItemEssentiaCell create64k(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "64k", 64, 8, ThEConfig.CELL_MAX_TYPES, 2.0);
|
||||
}
|
||||
public static ItemEssentiaCell create256k(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "256k", 256, 8, ThEConfig.CELL_MAX_TYPES, 2.5);
|
||||
}
|
||||
public static ItemEssentiaCell create1m(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "1m", 1024, 8, ThEConfig.CELL_MAX_TYPES, 3.0);
|
||||
}
|
||||
public static ItemEssentiaCell create4m(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "4m", 4096, 8, ThEConfig.CELL_MAX_TYPES, 3.5);
|
||||
}
|
||||
public static ItemEssentiaCell create16m(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "16m", 16384, 8, ThEConfig.CELL_MAX_TYPES, 4.0);
|
||||
}
|
||||
public static ItemEssentiaCell create64m(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "64m", 65536, 8, ThEConfig.CELL_MAX_TYPES, 4.5);
|
||||
}
|
||||
public static ItemEssentiaCell create256m(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "256m", 262144, 8, ThEConfig.CELL_MAX_TYPES, 5.0);
|
||||
}
|
||||
public static ItemEssentiaCell createCreative(Item.Properties props) {
|
||||
return new ItemEssentiaCell(props, "creative", Integer.MAX_VALUE / 1024, 8, 63, 0.0);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import thaumcraft.common.items.TCFunctionalItems;
|
||||
import thaumcraft.common.vis.TCVisHelper;
|
||||
import thaumicenergistics.common.blocks.ThEWrenchHandler;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.sounds.SoundEvents;
|
||||
@@ -121,6 +122,12 @@ public class ItemFocusAEWrench extends TCFunctionalItems.FocusItem {
|
||||
return false;
|
||||
}
|
||||
|
||||
BlockPos pos = hit.getBlockPos();
|
||||
// 拆卸资格预检(AE2 方块实体或 ThE 方块)先于扣 vis——对不可拆目标施法失败不耗能
|
||||
if (!canDisassembleTarget(level, pos)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
AspectList cost = this.visCost(focusStack);
|
||||
if (!wand.consumeVisCost(wandStack, player, cost, false)) {
|
||||
player.displayClientMessage(
|
||||
@@ -131,7 +138,6 @@ public class ItemFocusAEWrench extends TCFunctionalItems.FocusItem {
|
||||
return false;
|
||||
}
|
||||
|
||||
BlockPos pos = hit.getBlockPos();
|
||||
boolean handled = handleWrenchAction(level, player, hit, wandStack);
|
||||
|
||||
if (handled) {
|
||||
@@ -142,6 +148,12 @@ public class ItemFocusAEWrench extends TCFunctionalItems.FocusItem {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 拆卸资格预检:AE2 原生方块实体(disassembleWithWrench 路径)或 ThE 方块(公共拆卸路径)。 */
|
||||
private static boolean canDisassembleTarget(Level level, BlockPos pos) {
|
||||
return level.getBlockEntity(pos) instanceof AEBaseBlockEntity
|
||||
|| ThEWrenchHandler.isDisassemblyTarget(level, pos);
|
||||
}
|
||||
|
||||
private boolean handleWrenchAction(Level level, Player player, BlockHitResult hit, ItemStack wandStack) {
|
||||
BlockPos pos = hit.getBlockPos();
|
||||
var blockEntity = level.getBlockEntity(pos);
|
||||
@@ -151,6 +163,12 @@ public class ItemFocusAEWrench extends TCFunctionalItems.FocusItem {
|
||||
return result.consumesAction();
|
||||
}
|
||||
|
||||
// ThE 方块:AE2 的 WrenchHook 只处理 AEBaseBlockEntity,ThETileBase 等不走该路径,
|
||||
// 经 ThEWrenchHandler 公共拆卸入口(与普通 AE2 扳手事件同一条逻辑)。
|
||||
if (ThEWrenchHandler.disassembleThEBlock(player, level, pos)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ public class WirelessArcaneCraftingTerminalItem extends WirelessTerminalItem {
|
||||
|
||||
@Override
|
||||
public MenuType<?> getMenuType() {
|
||||
return thaumicenergistics.init.ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL.get();
|
||||
return thaumicenergistics.init.ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+118
-33
@@ -10,15 +10,20 @@ import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.component.ItemContainerContents;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.PowerMultiplier;
|
||||
import appeng.api.features.Locatables;
|
||||
import appeng.api.ids.AEComponents;
|
||||
import appeng.api.inventories.ISegmentedInventory;
|
||||
import appeng.api.inventories.InternalInventory;
|
||||
import appeng.api.networking.IGridNode;
|
||||
import appeng.api.networking.security.IActionHost;
|
||||
import appeng.api.storage.ILinkStatus;
|
||||
import appeng.api.storage.MEStorage;
|
||||
import appeng.api.storage.SupplierStorage;
|
||||
import appeng.helpers.WirelessTerminalMenuHost;
|
||||
import appeng.me.storage.NullInventory;
|
||||
import appeng.menu.ISubMenu;
|
||||
import appeng.menu.locator.ItemMenuHostLocator;
|
||||
import appeng.util.inv.AppEngInternalInventory;
|
||||
@@ -27,6 +32,7 @@ import appeng.util.inv.InternalInventoryHost;
|
||||
import net.neoforged.fml.ModList;
|
||||
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.container.IArcaneTerminalInventoryHost;
|
||||
import thaumicenergistics.common.parts.ArcaneCraftingTerminalPart;
|
||||
import thaumicenergistics.init.ModComponents;
|
||||
|
||||
@@ -35,13 +41,12 @@ import thaumicenergistics.init.ModComponents;
|
||||
* 合成格/法杖槽持久化进物品组件(关菜单或存背包不丢料)。
|
||||
* 子库存 id 复用有线部件常量,{@code ContainerArcaneCraftingTerminal} 无需改动即可识别本宿主。
|
||||
* <p>
|
||||
* WTBRIDGE:量子桥卡联动为何复刻而非引用——ae2wtlib 桥卡逻辑在其自有
|
||||
* {@code WTMenuHost}(类层级硬绑定其 {@code ItemWT}),软依赖 + Java 单继承下无法继承复用,
|
||||
* 故在本类覆写 {@code updateLinkStatus}/{@code getLinkStatus} 复刻其公开 API 语义。
|
||||
* 完整 AE2WT 存在时,物品工厂选择 ItemWT 实现并使用 AE2WTArcaneTerminalMenuHost,
|
||||
* 本类只用于独立物品;旧桥卡兼容保留在此,不参与 AE2WT 宿主的扣费或连接更新。
|
||||
*/
|
||||
public class WirelessArcaneCraftingTerminalMenuHost
|
||||
extends WirelessTerminalMenuHost<WirelessArcaneCraftingTerminalItem>
|
||||
implements ISegmentedInventory {
|
||||
implements ISegmentedInventory, IArcaneTerminalInventoryHost {
|
||||
|
||||
// ==================== WTBRIDGE 软依赖常量(id 来源:ae2wtlib 19.5.1,升级对齐点) ====================
|
||||
/** 量子桥卡物品 id(ae2wtlib AE2wtlibItems.QUANTUM_BRIDGE_CARD 注册名)。 */
|
||||
@@ -62,6 +67,14 @@ public class WirelessArcaneCraftingTerminalMenuHost
|
||||
private final AppEngInternalInventory singularityInv;
|
||||
/** 桥卡链路当前是否有效(本类自有状态:AE2 基类 linkStatus 字段 private 不可直改)。 */
|
||||
private boolean quantumBridgeLinked;
|
||||
@Nullable
|
||||
private IActionHost quantumBridge;
|
||||
/** 库存与合成节点必须取自同一链路,不能只把界面的连接状态改成成功。 */
|
||||
private final MEStorage quantumStorage = new SupplierStorage(() -> {
|
||||
var node = getActionableNode();
|
||||
return node != null && node.getGrid() != null
|
||||
? node.getGrid().getStorageService().getInventory() : NullInventory.of();
|
||||
});
|
||||
|
||||
public WirelessArcaneCraftingTerminalMenuHost(
|
||||
WirelessArcaneCraftingTerminalItem item,
|
||||
@@ -69,8 +82,8 @@ public class WirelessArcaneCraftingTerminalMenuHost
|
||||
ItemMenuHostLocator locator,
|
||||
BiConsumer<Player, ISubMenu> returnToMainMenu) {
|
||||
super(item, player, locator, returnToMainMenu);
|
||||
this.craftingGrid = createPersistedInv(player, this.getItemStack(), 9, AEComponents.CRAFTING_INV);
|
||||
this.wandInv = createPersistedInv(player, this.getItemStack(), 1, ModComponents.WAND_INV.get());
|
||||
this.craftingGrid = thaumicenergistics.common.inventory.PersistedTerminalInventories.createPersistedInv(player, this.getItemStack(), 9, AEComponents.CRAFTING_INV);
|
||||
this.wandInv = thaumicenergistics.common.inventory.PersistedTerminalInventories.createPersistedInv(player, this.getItemStack(), 1, ModComponents.WAND_INV.get());
|
||||
this.singularityInv = createSingularityInv(player, this.getItemStack());
|
||||
}
|
||||
|
||||
@@ -125,10 +138,22 @@ public class WirelessArcaneCraftingTerminalMenuHost
|
||||
this.getItemStack().set(ModComponents.WAND_INV.get(), this.wandInv.toItemContainerContents());
|
||||
}
|
||||
|
||||
// ==================== WTBRIDGE:量子桥卡生效逻辑(照抄 ae2wtlib isQuantumLinked 语义) ====================
|
||||
/** 契约实现:本宿主奇点子库存即 WTBRIDGE-SLOT 自有库存(本模组命名空间 id)。 */
|
||||
@Override
|
||||
public void refreshConnection() {
|
||||
updateConnectedAccessPoint();
|
||||
updateLinkStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceLocation getSingularityInvId() {
|
||||
return INV_SINGULARITY;
|
||||
}
|
||||
|
||||
// ==================== WTBRIDGE:量子桥卡连接逻辑 ====================
|
||||
|
||||
/**
|
||||
* 桥卡链路有效时强制 connected(跨维/无限距离);否则逐字节回落 AE2 原生状态。
|
||||
* 桥卡链路有效时 connected(跨维/无限距离);否则回落 AE2 原生状态。
|
||||
*/
|
||||
@Override
|
||||
public ILinkStatus getLinkStatus() {
|
||||
@@ -138,13 +163,34 @@ public class WirelessArcaneCraftingTerminalMenuHost
|
||||
return super.getLinkStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public MEStorage getInventory() {
|
||||
return quantumStorage;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IGridNode getActionableNode() {
|
||||
if (!getPlayer().level().isClientSide() && quantumBridge != null) {
|
||||
return quantumBridge.getActionableNode();
|
||||
}
|
||||
return super.getActionableNode();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateConnectedAccessPoint() {
|
||||
super.updateConnectedAccessPoint();
|
||||
// AE2 的父类构造器也调用此方法;解析只依赖终端物品,不能依赖尚未创建的子库存。
|
||||
quantumBridge = findQuantumBridge();
|
||||
}
|
||||
|
||||
/**
|
||||
* 先判桥卡链路(有效且有余能 → connected),否则完整回落 AE2 原生判定(访问点/范围/电量)。
|
||||
*/
|
||||
@Override
|
||||
protected void updateLinkStatus() {
|
||||
this.quantumBridgeLinked = false;
|
||||
if (isQuantumLinkedViaBridgeCard() && consumeIdlePower(Actionable.SIMULATE)) {
|
||||
if (quantumBridge != null && consumeIdlePower(Actionable.SIMULATE)) {
|
||||
this.quantumBridgeLinked = true;
|
||||
return;
|
||||
}
|
||||
@@ -153,55 +199,94 @@ public class WirelessArcaneCraftingTerminalMenuHost
|
||||
|
||||
/**
|
||||
* 复刻 ae2wtlib {@code WTMenuHost.isQuantumLinked}:卡在槽 → 奇点组件 → 频率查桥。
|
||||
* 全程零 ae2wtlib 编译引用(注册表软查 + AE2 公开 API),ae2wtlib 缺席时恒 false。
|
||||
* 全程零 ae2wtlib 编译引用(注册表软查 + AE2 公开 API),缺席或链路无效时返回 null。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private boolean isQuantumLinkedViaBridgeCard() {
|
||||
if (!ModList.get().isLoaded(AE2WTLIB_MODID)) {
|
||||
return false;
|
||||
@Nullable
|
||||
private IActionHost findQuantumBridge() {
|
||||
if (getPlayer().level().isClientSide() || !ModList.get().isLoaded(AE2WTLIB_MODID)) {
|
||||
return null;
|
||||
}
|
||||
// 1. 桥卡物品软查 + 是否已装入 WACT 升级槽(AE2 标准 IUpgradeInventory,准入映射见 ThaumicEnergistics)
|
||||
var card = BuiltInRegistries.ITEM.getOptional(AE2WTLIB_QUANTUM_BRIDGE_CARD).orElse(null);
|
||||
if (card == null || card == Items.AIR) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
if (!this.getItem().getUpgrades(this.getItemStack()).isInstalled(card)) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
// 2. 奇点组件类型软查(ae2wtlib 注册于 BuiltInRegistries.DATA_COMPONENT_TYPE)
|
||||
var type = BuiltInRegistries.DATA_COMPONENT_TYPE.getOptional(AE2WTLIB_SINGULARITY_COMPONENT).orElse(null);
|
||||
if (type == null) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
ItemStack singularity = this.getItemStack().getOrDefault((DataComponentType<ItemStack>) type, ItemStack.EMPTY);
|
||||
if (singularity.isEmpty()) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
// 3. 缠绕奇点频率(AE2 公开组件)→ Locatables 查桥(对齐 ae2wtlib findQuantumBridge 的 ±freq 语义)
|
||||
Long freq = singularity.get(AEComponents.ENTANGLED_SINGULARITY_ID);
|
||||
if (freq == null) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
var level = this.getPlayer().level();
|
||||
var bridges = Locatables.quantumNetworkBridges();
|
||||
return bridges.get(level, freq) != null || bridges.get(level, -freq) != null;
|
||||
var bridge = bridges.get(level, freq);
|
||||
if (bridge == null) {
|
||||
bridge = bridges.get(level, -freq);
|
||||
}
|
||||
|
||||
/** 官方 createCraftingInv 推广版:子库存读写进指定物品组件。 */
|
||||
private static AppEngInternalInventory createPersistedInv(Player player, ItemStack stack, int size,
|
||||
DataComponentType<ItemContainerContents> component) {
|
||||
var inv = new AppEngInternalInventory(new InternalInventoryHost() {
|
||||
@Override
|
||||
public void saveChangedInventory(AppEngInternalInventory changed) {
|
||||
stack.set(component, changed.toItemContainerContents());
|
||||
if (bridge == null || bridge.getActionableNode() == null) {
|
||||
return null;
|
||||
}
|
||||
var grid = bridge.getActionableNode().getGrid();
|
||||
if (grid == null || !grid.getEnergyService().isNetworkPowered()) {
|
||||
return null;
|
||||
}
|
||||
// 对齐 AE2WT:已经绑定到另一个有效网络时,不能悄悄切到奇点所在网络。
|
||||
var linkedGrid = getItem().getLinkedGrid(getItemStack(), level, null);
|
||||
return linkedGrid == null || linkedGrid == grid ? bridge : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClientSide() {
|
||||
return player.level().isClientSide();
|
||||
protected double getPowerDrainPerTick() {
|
||||
return quantumBridge != null ? 22.5 : super.getPowerDrainPerTick();
|
||||
}
|
||||
}, size);
|
||||
inv.fromItemContainerContents(stack.getOrDefault(component, ItemContainerContents.EMPTY));
|
||||
return inv;
|
||||
|
||||
@Override
|
||||
public boolean consumeIdlePower(Actionable action) {
|
||||
if (action == Actionable.SIMULATE) {
|
||||
rechargeFromQuantumBridge();
|
||||
}
|
||||
boolean success = super.consumeIdlePower(action);
|
||||
if (action == Actionable.SIMULATE) {
|
||||
rechargeFromQuantumBridge();
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
private void rechargeFromQuantumBridge() {
|
||||
if (quantumBridge == null || quantumBridge.getActionableNode() == null) {
|
||||
return;
|
||||
}
|
||||
var grid = quantumBridge.getActionableNode().getGrid();
|
||||
if (grid == null) {
|
||||
return;
|
||||
}
|
||||
var stack = getItemStack();
|
||||
double missing = getItem().getAEMaxPower(stack) - getItem().getAECurrentPower(stack);
|
||||
if (missing <= 0) {
|
||||
return;
|
||||
}
|
||||
var energy = grid.getEnergyService();
|
||||
// 对齐 AE2WT 的半容量储能保护,避免给终端充电把 ME 网络抽停。
|
||||
double safePower = energy.getStoredPower() - energy.getMaxStoredPower() / 2;
|
||||
if (safePower <= 0) {
|
||||
return;
|
||||
}
|
||||
double extracted = energy.extractAEPower(
|
||||
Math.min(missing, safePower), Actionable.MODULATE, PowerMultiplier.ONE);
|
||||
getItem().injectAEPower(stack, extracted, Actionable.MODULATE);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package thaumicenergistics.common.monitor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
|
||||
/** 显示实体的创建、恢复、更新和移除;不负责风险采集或网络状态。 */
|
||||
public final class InfusionMonitorDisplay {
|
||||
private static final String BUBBLE_TAG = "thaumicenergistics:monitor_bubble";
|
||||
private static final int BUBBLE_BG_COLOR = 0xB0333333;
|
||||
private static final int BUBBLE_LINE_WIDTH = 320;
|
||||
private final Supplier<Level> levelSupplier;
|
||||
private final BlockPos position;
|
||||
private net.minecraft.world.entity.Display.TextDisplay bubble;
|
||||
private Component lastText;
|
||||
|
||||
public InfusionMonitorDisplay(Supplier<Level> levelSupplier, BlockPos position) {
|
||||
this.levelSupplier = levelSupplier;
|
||||
this.position = position.immutable();
|
||||
}
|
||||
|
||||
public void update(boolean visible, Component text) {
|
||||
var level = levelSupplier.get();
|
||||
if (level == null || level.isClientSide()) return;
|
||||
if (!visible) { discard(); return; }
|
||||
ensureBubble(level, text);
|
||||
if (bubble != null && !text.equals(lastText)) {
|
||||
applyBubbleNbt(level, text);
|
||||
lastText = text;
|
||||
}
|
||||
}
|
||||
|
||||
/** 确保气泡实体存在(不存在则生成;区块重载后按 Tag 找回旧实体)。 */
|
||||
private void ensureBubble(Level level, Component text) {
|
||||
if (bubble != null && bubble.isAlive()) return;
|
||||
bubble = findBubble(level);
|
||||
if (bubble != null) return;
|
||||
bubble = EntityType.TEXT_DISPLAY.create(level);
|
||||
if (bubble == null) return;
|
||||
bubble.setPos(position.getX() + 0.5, position.getY() + 1.2, position.getZ() + 0.5);
|
||||
// 通过公开实体保存/加载 API 配置 TextDisplay 的文本与显示字段。
|
||||
applyBubbleNbt(level, text);
|
||||
bubble.addTag(BUBBLE_TAG);
|
||||
level.addFreshEntity(bubble);
|
||||
}
|
||||
|
||||
private void applyBubbleNbt(Level level, Component text) {
|
||||
if (bubble == null || level == null) return;
|
||||
try {
|
||||
// 保存完整实体状态,公共 load 路径不会把位置、UUID 等字段重置为默认值。
|
||||
CompoundTag nbt = bubble.saveWithoutId(new CompoundTag());
|
||||
nbt.putString("text", Component.Serializer.toJson(text, level.registryAccess()));
|
||||
nbt.putBoolean("default_background", false);
|
||||
nbt.putInt("background", BUBBLE_BG_COLOR);
|
||||
nbt.putString("billboard", "vertical");
|
||||
nbt.putInt("line_width", BUBBLE_LINE_WIDTH);
|
||||
nbt.putBoolean("shadow", true);
|
||||
nbt.putBoolean("see_through", false);
|
||||
// 必须写 alignment:TextDisplay.readAdditionalSaveData 无条件 decode "alignment",
|
||||
// 缺失时 tag.get 返回 null → Align.CODEC(字符串) decode 失败 → 服务端疯狂刷 "Display entityNot a string"。
|
||||
nbt.putString("alignment", "center");
|
||||
// 文字调小:transformation.scale 整体缩到 0.5(text_display 无字号参数,靠实体缩放)
|
||||
CompoundTag transform = new CompoundTag();
|
||||
transform.put("scale", floatList(0.5F, 0.5F, 0.5F));
|
||||
transform.put("translation", floatList(0F, 0F, 0F));
|
||||
transform.put("left_rotation", floatList(0F, 0F, 0F, 1F));
|
||||
transform.put("right_rotation", floatList(0F, 0F, 0F, 1F));
|
||||
nbt.put("transformation", transform);
|
||||
bubble.load(nbt);
|
||||
} catch (Exception e) {
|
||||
ThaumicEnergistics.LOG.warn("[Monitor] 气泡配置失败: {}", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** 构造 FloatTag 列表(1.21.1 CompoundTag 无 putFloatArray,需 ListTag)。 */
|
||||
private static net.minecraft.nbt.ListTag floatList(float... values) {
|
||||
net.minecraft.nbt.ListTag list = new net.minecraft.nbt.ListTag();
|
||||
for (float v : values) {
|
||||
list.add(net.minecraft.nbt.FloatTag.valueOf(v));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/** 按 Tag + 方块附近 AABB 查找已存在的气泡。 */
|
||||
private net.minecraft.world.entity.Display.TextDisplay findBubble(Level level) {
|
||||
if (level == null) return null;
|
||||
AABB aabb = new AABB(position).inflate(0.15, 2.0, 0.15);
|
||||
List<net.minecraft.world.entity.Display.TextDisplay> list = level.getEntitiesOfClass(
|
||||
net.minecraft.world.entity.Display.TextDisplay.class, aabb,
|
||||
e -> e.getTags().contains(BUBBLE_TAG)
|
||||
&& e.distanceToSqr(position.getX() + 0.5, position.getY() + 1.2, position.getZ() + 0.5) < 0.01);
|
||||
return list.isEmpty() ? null : list.get(0);
|
||||
}
|
||||
|
||||
/** 销毁气泡(方块拆除/条件不满足时)。 */
|
||||
public void discard() {
|
||||
Level level = levelSupplier.get();
|
||||
if (bubble != null && bubble.isAlive()) {
|
||||
bubble.discard();
|
||||
} else {
|
||||
net.minecraft.world.entity.Display.TextDisplay found = findBubble(level);
|
||||
if (found != null) {
|
||||
found.discard();
|
||||
}
|
||||
}
|
||||
bubble = null;
|
||||
lastText = null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package thaumicenergistics.common.monitor;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import thaumicenergistics.common.tiles.TileInfusionMonitor.RiskData;
|
||||
|
||||
/** 注魔风险的显示文字与颜色。 */
|
||||
public final class InfusionMonitorText {
|
||||
private InfusionMonitorText() { }
|
||||
|
||||
/** 风险数据 → 气泡多行文本(2 行:注魔风险/不稳定度;不显示基础+祭坛细分,细分在聊天栏)。 */
|
||||
public static Component bubble(RiskData risk) {
|
||||
// 内边距必须用不间断空格(\u00A0):普通空格在行尾会被字体布局裁剪,
|
||||
// 导致背景只包住左侧、右侧贴边。NBSP 有真实字形,两侧都保留。
|
||||
String pad = "\u00A0\u00A0"; // 左右内边距(NBSP)
|
||||
String tierWord = tierWord(risk.tier());
|
||||
|
||||
Component line1 = Component.literal(pad + "注魔风险: " + tierWord + pad)
|
||||
.withStyle(style -> style.withColor(tierColor(risk.tier())));
|
||||
Component line2 = Component.literal(pad + "不稳定度: " + risk.instability() + pad)
|
||||
.withStyle(style -> style.withColor(0xFFFFFFFF));
|
||||
|
||||
// 上下各留一个空行(垂直内边距)
|
||||
return Component.literal("\n")
|
||||
.append(line1).append("\n")
|
||||
.append(line2).append("\n");
|
||||
}
|
||||
|
||||
/** 5 档文字(无星星)。 */
|
||||
public static String tierWord(int tier) {
|
||||
return switch (tier) {
|
||||
case 1 -> "极低";
|
||||
case 2 -> "低";
|
||||
case 3 -> "中";
|
||||
case 4 -> "高";
|
||||
case 5 -> "极高";
|
||||
default -> "?";
|
||||
};
|
||||
}
|
||||
|
||||
/** 5 档描述(神秘时代风)。 */
|
||||
public static String tierDesc(int tier) {
|
||||
return switch (tier) {
|
||||
case 1 -> "灵光如镜,仪式安然";
|
||||
case 2 -> "灵光微澜,无碍仪式";
|
||||
case 3 -> "符文低鸣,灵光流转不宁";
|
||||
case 4 -> "裂隙于虚空中睁开,注视着祭坛";
|
||||
case 5 -> "咒波翻涌,裂隙将吞没一切";
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
|
||||
/** 档位颜色:1 绿 → 5 红。 */
|
||||
public static int tierColor(int tier) {
|
||||
return switch (tier) {
|
||||
case 1 -> 0xFF55FF55;
|
||||
case 2 -> 0xFFAAFF55;
|
||||
case 3 -> 0xFFFFFF55;
|
||||
case 4 -> 0xFFFFAA55;
|
||||
default -> 0xFFFF5555;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+27
-15
@@ -9,7 +9,7 @@ import thaumicenergistics.ThaumicEnergistics;
|
||||
import appeng.menu.me.common.MEStorageMenu;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import thaumicenergistics.common.container.EssentiaFillHelper;
|
||||
import thaumicenergistics.common.container.ThEEssentiaMenuAccess;
|
||||
import thaumicenergistics.common.container.MenuResources;
|
||||
|
||||
/**
|
||||
* 客户端→服务端:源质容器存入 ME 网络。
|
||||
@@ -52,27 +52,39 @@ public record EssentiaTerminalDepositC2SPacket(int containerId, int slotIndex,
|
||||
// 任意 ME 终端菜单都支持:源质容器右键 → 源质存入网络
|
||||
if (ctx.player().containerMenu.containerId == this.containerId
|
||||
&& ctx.player().containerMenu instanceof MEStorageMenu menu
|
||||
&& menu instanceof ThEEssentiaMenuAccess acc) {
|
||||
&& menu.getLinkStatus().connected()) {
|
||||
var player = menu.getPlayerInventory().player;
|
||||
// 源质物品:优先包携带的 sourceStack(客户端真实来源);否则回退菜单 carried/主手
|
||||
var source = !this.sourceStack.isEmpty() ? this.sourceStack
|
||||
: (!menu.getCarried().isEmpty() ? menu.getCarried()
|
||||
: player.getMainHandItem());
|
||||
if (slotIndex < -1 || slotIndex >= player.getInventory().items.size()) {
|
||||
return;
|
||||
}
|
||||
if (slotIndex >= 0 && menu.slots.stream().noneMatch(slot ->
|
||||
menu.isPlayerSideSlot(slot) && slot.getSlotIndex() == slotIndex)) {
|
||||
return;
|
||||
}
|
||||
boolean carried = slotIndex < 0 && !menu.getCarried().isEmpty();
|
||||
var source = slotIndex >= 0 ? player.getInventory().getItem(slotIndex)
|
||||
: carried ? menu.getCarried() : player.getMainHandItem();
|
||||
// 客户端副本仅用于拒绝过时操作,不能作为源质来源。
|
||||
if (!ItemStack.isSameItemSameComponents(source, sourceStack)
|
||||
|| source.getCount() != sourceStack.getCount()) {
|
||||
menu.broadcastChanges();
|
||||
return;
|
||||
}
|
||||
if (!source.isEmpty()) {
|
||||
var result = EssentiaFillHelper.extractContainerContent(
|
||||
acc.thE_getStorage(), acc.thE_getEnergySource(),
|
||||
menu.getActionSource(), source);
|
||||
var result = EssentiaFillHelper.depositContainerContent(
|
||||
MenuResources.getStorage(menu),
|
||||
MenuResources.getEnergySource(menu),
|
||||
menu.getActionSource(), player, source);
|
||||
if (result != null) {
|
||||
if (this.slotIndex >= 0) {
|
||||
// Shift+右键背包格:空容器留在原背包格
|
||||
player.getInventory().setItem(this.slotIndex, result);
|
||||
} else {
|
||||
// 手持:清空 carried,空容器放回玩家背包(不留 carried,防被 AE2 自动放入网络)
|
||||
menu.setCarried(ItemStack.EMPTY);
|
||||
if (!result.isEmpty()) {
|
||||
if (!player.getInventory().add(result)) {
|
||||
player.drop(result, false);
|
||||
}
|
||||
// 更新实际来源;部分成功时留下包含余量的容器。
|
||||
if (carried) {
|
||||
menu.setCarried(result);
|
||||
} else {
|
||||
player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import net.neoforged.neoforge.network.handling.IPayloadContext;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import appeng.menu.me.common.MEStorageMenu;
|
||||
import thaumicenergistics.common.container.EssentiaFillHelper;
|
||||
import thaumicenergistics.common.container.ThEEssentiaMenuAccess;
|
||||
import thaumicenergistics.common.container.MenuResources;
|
||||
|
||||
/**
|
||||
* 客户端→服务端:源质终端右键源质条目装罐。
|
||||
@@ -47,17 +47,20 @@ public record EssentiaTerminalFillC2SPacket(int containerId, ResourceLocation as
|
||||
// 通用化:任意 ME 终端菜单都支持右键源质条目装罐(源质终端/奥术合成终端/AE2 ME 终端等)
|
||||
if (ctx.player().containerMenu.containerId == this.containerId
|
||||
&& ctx.player().containerMenu instanceof MEStorageMenu menu
|
||||
&& menu instanceof ThEEssentiaMenuAccess acc) {
|
||||
&& menu.getLinkStatus().connected()) {
|
||||
var player = menu.getPlayerInventory().player;
|
||||
// ⚠ 必须用玩家真实栈(carried/主手)而非包里的拷贝:装罐会原地消耗空安瓿(shrink)
|
||||
// 或修改罐子内容(setAspects)。若用 sourceStack(拷贝),消耗/修改不落真实物品——
|
||||
// 空安瓿不消耗却能凭空得到满安瓿。
|
||||
// 顺序与客户端一致:优先 carried(拾取),其次主手;sourceStack 仅兜底。
|
||||
var source = !menu.getCarried().isEmpty() ? menu.getCarried()
|
||||
: (!player.getMainHandItem().isEmpty() ? player.getMainHandItem()
|
||||
: this.sourceStack);
|
||||
var source = !menu.getCarried().isEmpty() ? menu.getCarried() : player.getMainHandItem();
|
||||
if (!ItemStack.isSameItemSameComponents(source, sourceStack)
|
||||
|| source.getCount() != sourceStack.getCount()) {
|
||||
return;
|
||||
}
|
||||
EssentiaFillHelper.fillContainerFromGrid(
|
||||
acc.thE_getStorage(), acc.thE_getEnergySource(),
|
||||
MenuResources.getStorage(menu),
|
||||
MenuResources.getEnergySource(menu),
|
||||
menu.getActionSource(), player, source, this.aspectId);
|
||||
menu.broadcastChanges();
|
||||
}
|
||||
|
||||
@@ -23,6 +23,16 @@ public final class ArcaneVisReplenish {
|
||||
|
||||
private ArcaneVisReplenish() {}
|
||||
|
||||
/** Avoid ticking a passive connection when the wand is absent, unsupported, or already full. */
|
||||
public static boolean needsCharge(ItemStack stack) {
|
||||
if (stack.isEmpty() || !(stack.getItem() instanceof TCFunctionalItems.WandCastingItem wand)) return false;
|
||||
int capacity = wand.getMaxVis(stack);
|
||||
for (Aspect primal : Aspect.getPrimalAspects()) {
|
||||
if (wand.getVis(stack, primal) < capacity) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 有线路径:按 P2P 频率定位要素中继接口后充能。
|
||||
*
|
||||
|
||||
@@ -75,9 +75,20 @@ public class VisInterfacePart extends P2PTunnelPart<VisInterfacePart> implements
|
||||
|
||||
public VisInterfacePart(IPartItem<?> partItem) {
|
||||
super(partItem);
|
||||
getMainNode().addService(IGridTickable.class, this);
|
||||
this.uid = System.currentTimeMillis() ^ this.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeFromWorld() {
|
||||
// A removed grid node will no longer tick, so its TC registration must be retired here.
|
||||
try {
|
||||
removeProvider();
|
||||
} finally {
|
||||
super.removeFromWorld();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPartModel getStaticModels() {
|
||||
return MODELS.getModel(this.isPowered(), this.isActive());
|
||||
@@ -158,6 +169,9 @@ public class VisInterfacePart extends P2PTunnelPart<VisInterfacePart> implements
|
||||
return null;
|
||||
}
|
||||
BlockPos front = getBlockEntity().getBlockPos().relative(getSide());
|
||||
if (!level.hasChunkAt(front)) {
|
||||
return null;
|
||||
}
|
||||
BlockEntity be = level.getBlockEntity(front);
|
||||
if (be instanceof VisRelayBlockEntity relay) {
|
||||
return relay;
|
||||
@@ -246,7 +260,7 @@ public class VisInterfacePart extends P2PTunnelPart<VisInterfacePart> implements
|
||||
|
||||
private void registerProvider() {
|
||||
Level level = getLevel();
|
||||
if (level == null || getBlockEntity() == null) {
|
||||
if (level == null || level.isClientSide() || getBlockEntity() == null) {
|
||||
return;
|
||||
}
|
||||
if (visProviderProxy != null) {
|
||||
@@ -254,6 +268,9 @@ public class VisInterfacePart extends P2PTunnelPart<VisInterfacePart> implements
|
||||
return;
|
||||
}
|
||||
BlockPos front = getBlockEntity().getBlockPos().relative(getSide());
|
||||
if (!level.hasChunkAt(front)) {
|
||||
return;
|
||||
}
|
||||
BlockState state = level.getBlockState(front);
|
||||
VisProviderProxy proxy = new VisProviderProxy(front, state);
|
||||
proxy.bind(this, level);
|
||||
@@ -264,12 +281,14 @@ public class VisInterfacePart extends P2PTunnelPart<VisInterfacePart> implements
|
||||
}
|
||||
|
||||
private void removeProvider() {
|
||||
if (visProviderProxy != null) {
|
||||
VisNetHandler.removeNode(visProviderProxy);
|
||||
VisProviderProxy oldProxy = this.visProviderProxy;
|
||||
this.visProviderProxy = null;
|
||||
}
|
||||
this.providerActive = false;
|
||||
this.isProvider = false;
|
||||
if (oldProxy != null) {
|
||||
// TC's node lifecycle also detaches descendants and marks the old node removed.
|
||||
oldProxy.setRemoved();
|
||||
}
|
||||
}
|
||||
|
||||
private void setDrainColor(int color) {
|
||||
@@ -298,13 +317,10 @@ public class VisInterfacePart extends P2PTunnelPart<VisInterfacePart> implements
|
||||
|
||||
@Override
|
||||
public TickRateModulation tickingRequest(IGridNode node, int ticksSinceLastCall) {
|
||||
if (!isActive()) {
|
||||
removeProvider();
|
||||
return TickRateModulation.SAME;
|
||||
}
|
||||
if (shouldProvide() && !providerActive) {
|
||||
boolean provide = !isClientSide() && isActive() && shouldProvide();
|
||||
if (provide && !providerActive) {
|
||||
registerProvider();
|
||||
} else if (!shouldProvide() && providerActive) {
|
||||
} else if (!provide) {
|
||||
removeProvider();
|
||||
}
|
||||
if (visDrainingColor != 0 && (System.currentTimeMillis() - lastColorUpdate) > TIME_TO_CLEAR) {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package thaumicenergistics.common.parts;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import appeng.helpers.WirelessTerminalMenuHost;
|
||||
import appeng.integration.modules.curios.CuriosIntegration;
|
||||
import appeng.items.tools.powered.WirelessTerminalItem;
|
||||
import appeng.menu.AEBaseMenu;
|
||||
import appeng.menu.locator.MenuLocators;
|
||||
import appeng.menu.locator.ItemMenuHostLocator;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.ItemContainerContents;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.fml.ModList;
|
||||
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.event.tick.PlayerTickEvent;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.container.IArcaneTerminalInventoryHost;
|
||||
import thaumicenergistics.common.integration.ae2wt.AE2WTCompat;
|
||||
import thaumicenergistics.common.items.WirelessArcaneCraftingTerminalItem;
|
||||
import thaumicenergistics.init.ModComponents;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/** One server-side charging path for closed terminals and every universal-terminal mode. */
|
||||
@EventBusSubscriber(modid = ThaumicEnergistics.MODID)
|
||||
public final class WirelessArcaneChargingHandler {
|
||||
// Hosts retain native AE2's ten-tick idle-energy buffer. Recreating one every tick would overcharge power.
|
||||
private static final Map<UUID, Map<Integer, PassiveHost>> HOSTS = new HashMap<>();
|
||||
private record PassiveHost(ServerPlayer player, ItemStack stack, ItemContainerContents wands,
|
||||
WirelessTerminalMenuHost<?> host) { }
|
||||
private WirelessArcaneChargingHandler() { }
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onPlayerTick(PlayerTickEvent.Post event) {
|
||||
if (!(event.getEntity() instanceof ServerPlayer player)) return;
|
||||
for (int slot = 0; slot < player.getInventory().getContainerSize(); slot++) {
|
||||
replenishCarriedTerminal(player, slot);
|
||||
}
|
||||
// AE2 exposes this capability without a Curios runtime dependency; absent mods return null.
|
||||
var curios = player.getCapability(CuriosIntegration.ITEM_HANDLER);
|
||||
int curioSlots = curios == null ? 0 : curios.getSlots();
|
||||
for (int slot = 0; slot < curioSlots; slot++) {
|
||||
replenishCarriedTerminal(player, -slot - 1, MenuLocators.forCurioSlot(slot));
|
||||
}
|
||||
var hosts = HOSTS.get(player.getUUID());
|
||||
if (hosts != null) {
|
||||
hosts.keySet().removeIf(key -> key < 0 && -key - 1 >= curioSlots);
|
||||
if (hosts.isEmpty()) HOSTS.remove(player.getUUID());
|
||||
}
|
||||
}
|
||||
|
||||
public static void replenishCarriedTerminal(ServerPlayer player, int slot) {
|
||||
replenishCarriedTerminal(player, slot, MenuLocators.forInventorySlot(slot));
|
||||
}
|
||||
|
||||
private static void replenishCarriedTerminal(ServerPlayer player, int slot, ItemMenuHostLocator locator) {
|
||||
ItemStack stack = locator.locateItem(player);
|
||||
var hosts = HOSTS.computeIfAbsent(player.getUUID(), ignored -> new HashMap<>());
|
||||
var openHost = player.containerMenu instanceof AEBaseMenu menu
|
||||
&& menu.getTarget() instanceof WirelessTerminalMenuHost<?> terminal
|
||||
&& terminal.getItemStack() == stack ? terminal : null;
|
||||
|
||||
if (!(stack.getItem() instanceof WirelessTerminalItem item)
|
||||
|| !item.getUpgrades(stack).isInstalled(ModItems.VIS_CONNECTOR_CARD.get())) {
|
||||
hosts.remove(slot);
|
||||
return;
|
||||
}
|
||||
// Use the live wand inventory while the arcane menu is open; never overwrite it with a saved copy.
|
||||
if (openHost instanceof IArcaneTerminalInventoryHost arcane) {
|
||||
hosts.remove(slot);
|
||||
if (openHost.getLinkStatus().connected() && WirelessArcaneVis.replenish(arcane)) {
|
||||
player.getInventory().setChanged();
|
||||
}
|
||||
return;
|
||||
}
|
||||
var wands = stack.getOrDefault(ModComponents.WAND_INV.get(), ItemContainerContents.EMPTY);
|
||||
if (wands.getSlots() == 0 || !ArcaneVisReplenish.needsCharge(wands.getStackInSlot(0))) {
|
||||
hosts.remove(slot);
|
||||
return;
|
||||
}
|
||||
var cached = hosts.get(slot);
|
||||
WirelessTerminalMenuHost<?> host;
|
||||
if (cached != null && cached.player() == player && cached.stack() == stack
|
||||
&& cached.wands().equals(wands)) {
|
||||
host = cached.host();
|
||||
} else {
|
||||
if (item instanceof WirelessArcaneCraftingTerminalItem arcane) {
|
||||
host = arcane.getMenuHost(player, locator, null);
|
||||
} else if (ModList.get().isLoaded(IArcaneTerminalInventoryHost.AE2WTLIB_MODID)) {
|
||||
host = AE2WTCompat.createPassiveArcaneHost(player, locator);
|
||||
} else {
|
||||
host = null;
|
||||
}
|
||||
if (host == null) {
|
||||
hosts.remove(slot);
|
||||
return;
|
||||
}
|
||||
hosts.put(slot, new PassiveHost(player, stack, wands, host));
|
||||
}
|
||||
if (!(host instanceof IArcaneTerminalInventoryHost arcane)) return;
|
||||
if (openHost == null) {
|
||||
// Refresh range/quantum connection and let the native host own terminal power accounting.
|
||||
host.tick();
|
||||
} else {
|
||||
// A different universal-terminal mode already ticks its host. Do not debit its idle power twice.
|
||||
arcane.refreshConnection();
|
||||
}
|
||||
if (host.getLinkStatus().connected() && WirelessArcaneVis.replenish(arcane)) {
|
||||
player.getInventory().setChanged();
|
||||
}
|
||||
// Detect external wand replacement while retaining the host for our own persisted charge updates.
|
||||
hosts.put(slot, new PassiveHost(player, stack,
|
||||
stack.getOrDefault(ModComponents.WAND_INV.get(), ItemContainerContents.EMPTY), host));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onLogout(PlayerEvent.PlayerLoggedOutEvent event) {
|
||||
HOSTS.remove(event.getEntity().getUUID());
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onServerStopped(ServerStoppedEvent event) {
|
||||
HOSTS.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package thaumicenergistics.common.parts;
|
||||
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import thaumicenergistics.common.container.IArcaneTerminalInventoryHost;
|
||||
import thaumicenergistics.common.items.VisConnectorCardItem;
|
||||
|
||||
/** 无线终端法杖补充,打开菜单与玩家携带时共用。 */
|
||||
public final class WirelessArcaneVis {
|
||||
private WirelessArcaneVis() { }
|
||||
|
||||
public static boolean replenish(IArcaneTerminalInventoryHost host) {
|
||||
var upgrades = host.getUpgrades();
|
||||
for (int i = 0; i < upgrades.size(); i++) {
|
||||
if (!(upgrades.getStackInSlot(i).getItem() instanceof VisConnectorCardItem)) continue;
|
||||
var node = host.getActionableNode();
|
||||
if (node == null || !node.isActive()) return false;
|
||||
var inventory = host.getSubInventory(ArcaneCraftingTerminalPart.INV_WAND);
|
||||
var wand = inventory != null ? inventory.getStackInSlot(0) : ItemStack.EMPTY;
|
||||
boolean changed = ArcaneVisReplenish.replenishAuto(node.getGrid(), wand);
|
||||
if (changed) host.saveWandInv();
|
||||
return changed;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package thaumicenergistics.common.storage;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
import java.util.Objects;
|
||||
import appeng.api.config.FuzzyMode;
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.IncludeExclude;
|
||||
import appeng.api.config.Settings;
|
||||
import appeng.api.config.StorageFilter;
|
||||
import appeng.api.config.YesNo;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.stacks.AEKey;
|
||||
import appeng.api.stacks.KeyCounter;
|
||||
import appeng.api.storage.MEStorage;
|
||||
import appeng.core.definitions.AEItems;
|
||||
import appeng.me.storage.MEInventoryHandler;
|
||||
import appeng.parts.storagebus.StorageBusPart;
|
||||
import appeng.util.prioritylist.IPartitionList;
|
||||
|
||||
/** 新增视图也经过总线的访问和过滤规则;设置即时读取,避免与原句柄分叉。 */
|
||||
public final class EssentiaStorageBusInventory extends MEInventoryHandler {
|
||||
private final Supplier<StorageBusPart> host;
|
||||
private AEKey[] cachedFilter;
|
||||
private FuzzyMode cachedFuzzyMode;
|
||||
|
||||
public EssentiaStorageBusInventory(MEStorage storage, Supplier<StorageBusPart> host) {
|
||||
super(storage);
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
private void configure() {
|
||||
var bus = host.get();
|
||||
var settings = bus.getConfigManager();
|
||||
var access = settings.getSetting(Settings.ACCESS);
|
||||
setAllowInsertion(access.isAllowInsertion());
|
||||
setAllowExtraction(access.isAllowExtraction());
|
||||
setWhitelist(bus.getUpgrades().isInstalled(AEItems.INVERTER_CARD)
|
||||
? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST);
|
||||
int usable = 18 + bus.getInstalledUpgrades(AEItems.CAPACITY_CARD) * 9;
|
||||
var config = bus.getConfig();
|
||||
int size = Math.min(usable, config.size());
|
||||
FuzzyMode fuzzy = bus.getUpgrades().isInstalled(AEItems.FUZZY_CARD)
|
||||
? settings.getSetting(Settings.FUZZY_MODE) : null;
|
||||
boolean changed = cachedFilter == null || cachedFilter.length != size || cachedFuzzyMode != fuzzy;
|
||||
if (!changed) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (!Objects.equals(cachedFilter[i], config.getKey(i))) {
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
var builder = IPartitionList.builder();
|
||||
if (fuzzy != null) builder.fuzzyMode(fuzzy);
|
||||
cachedFilter = new AEKey[size];
|
||||
cachedFuzzyMode = fuzzy;
|
||||
for (int i = 0; i < size; i++) {
|
||||
cachedFilter[i] = config.getKey(i);
|
||||
builder.add(cachedFilter[i]);
|
||||
}
|
||||
setPartitionList(builder.build());
|
||||
}
|
||||
boolean filter = settings.getSetting(Settings.FILTER_ON_EXTRACT) == YesNo.YES;
|
||||
setExtractFiltering(filter, filter
|
||||
&& settings.getSetting(Settings.STORAGE_FILTER) == StorageFilter.EXTRACTABLE_ONLY);
|
||||
setVoidOverflow(bus.getUpgrades().isInstalled(AEItems.VOID_CARD));
|
||||
}
|
||||
|
||||
@Override
|
||||
public long insert(AEKey key, long amount, Actionable mode, IActionSource source) {
|
||||
configure();
|
||||
return super.insert(key, amount, mode, source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long extract(AEKey key, long amount, Actionable mode, IActionSource source) {
|
||||
configure();
|
||||
if (!host.get().getConfigManager().getSetting(Settings.ACCESS).isAllowExtraction()) {
|
||||
return 0;
|
||||
}
|
||||
return super.extract(key, amount, mode, source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getAvailableStacks(KeyCounter stacks) {
|
||||
configure();
|
||||
super.getAvailableStacks(stacks);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package thaumicenergistics.common.tiles;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import thaumicenergistics.common.crafting.ProbabilityBrainRules;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
@@ -27,7 +28,6 @@ import net.minecraft.world.level.block.state.BlockState;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.PowerMultiplier;
|
||||
import appeng.api.networking.GridFlags;
|
||||
import appeng.api.networking.GridHelper;
|
||||
import appeng.api.networking.IGrid;
|
||||
@@ -35,7 +35,6 @@ import appeng.api.networking.IGridNode;
|
||||
import appeng.api.networking.IGridNodeListener;
|
||||
import appeng.api.networking.IManagedGridNode;
|
||||
import appeng.api.networking.IInWorldGridNodeHost;
|
||||
import appeng.api.networking.energy.IEnergyService;
|
||||
import appeng.api.networking.security.IActionHost;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.networking.storage.IStorageService;
|
||||
@@ -58,7 +57,7 @@ import thaumicenergistics.init.ModItems;
|
||||
/**
|
||||
* 概率之脑 BE(M6):网格节点 + 每秒一次的周期 tick。
|
||||
* 脑槽、4 张加速卡、绑定宿主、进行中的转动与屏幕闪烁都在此记账;
|
||||
* 数值语义照 CE(GachaOdds/GachaTurn),能源直扣 ME 网络(500 AE/周期),
|
||||
* 概率规则参考 CE(GachaOdds/GachaTurn),网络持续耗能 50 AE/t,
|
||||
* 燃料 cognitio 从 ME 源质存储扣取(2/周期),产出经 TCResearchManager.addAspectPool 落入宿主认知要素池。
|
||||
*/
|
||||
public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
@@ -66,8 +65,8 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
|
||||
/** 转动按秒走,每秒醒一次。 */
|
||||
private static final int TICKS_PER_SECOND = 20;
|
||||
/** 每周期 ME 能量消耗(CE GachaPower AE_PER_TURN=500 定稿)。 */
|
||||
public static final double AE_PER_TURN = 500.0;
|
||||
/** 网络持续耗能,由 AE2 能量服务统一扣除,不另收每轮启动费用。 */
|
||||
public static final double AE_PER_TICK = 50.0;
|
||||
/** 每周期 cognitio 燃料(CE 同值)。 */
|
||||
public static final int COGNITIO_PER_TURN = 2;
|
||||
/** 加速卡上限(CE 同值)。 */
|
||||
@@ -75,25 +74,16 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
/** 结果在屏幕上停留秒数(CE FLASH_SECONDS=2)。 */
|
||||
private static final int FLASH_SECONDS = 2;
|
||||
|
||||
// ===== 骰子数值(CE GachaOdds 定稿,用户可调) =====
|
||||
/** 最快的一次转动,也是赔率最好的一次。 */
|
||||
public static final int MIN_SECONDS = 30;
|
||||
/** 无加速卡时最慢的转动。 */
|
||||
public static final int LONGEST_SECONDS = 180;
|
||||
/** 每张加速卡把最长转动缩短的秒数。 */
|
||||
public static final int SECONDS_PER_CARD = 25;
|
||||
/** 加速卡最多把最长转动压到的秒数(第五张起不再变化)。 */
|
||||
public static final int LONGEST_WITH_CARDS = 80;
|
||||
/** 最快转动的给奖赔率。 */
|
||||
public static final double CHANCE_AT_MIN_SECONDS = 0.75;
|
||||
/** 最慢转动的给奖赔率。 */
|
||||
public static final double CHANCE_AT_LONGEST_SECONDS = 0.45;
|
||||
/** 给奖转动抽取次数下限。 */
|
||||
public static final int MIN_DRAWS = 5;
|
||||
/** 给奖转动抽取次数上限。 */
|
||||
public static final int MAX_DRAWS = 7;
|
||||
/** 单次抽取点数上限(1~3)。 */
|
||||
public static final int MAX_POINTS_PER_DRAW = 3;
|
||||
// 公开常量保持兼容,规则集中在 ProbabilityBrainRules。
|
||||
public static final int MIN_SECONDS = ProbabilityBrainRules.MIN_SECONDS;
|
||||
public static final int LONGEST_SECONDS = ProbabilityBrainRules.LONGEST_SECONDS;
|
||||
public static final int SECONDS_PER_CARD = ProbabilityBrainRules.SECONDS_PER_CARD;
|
||||
public static final int LONGEST_WITH_CARDS = ProbabilityBrainRules.LONGEST_WITH_CARDS;
|
||||
public static final double CHANCE_AT_MIN_SECONDS = ProbabilityBrainRules.CHANCE_AT_MIN_SECONDS;
|
||||
public static final double CHANCE_AT_LONGEST_SECONDS = ProbabilityBrainRules.CHANCE_AT_LONGEST_SECONDS;
|
||||
public static final int MIN_DRAWS = ProbabilityBrainRules.MIN_DRAWS;
|
||||
public static final int MAX_DRAWS = ProbabilityBrainRules.MAX_DRAWS;
|
||||
public static final int MAX_POINTS_PER_DRAW = ProbabilityBrainRules.MAX_POINTS_PER_DRAW;
|
||||
|
||||
private final IManagedGridNode mainNode;
|
||||
private final IActionSource actionSource;
|
||||
@@ -139,7 +129,7 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
.setFlags(GridFlags.REQUIRE_CHANNEL)
|
||||
.setExposedOnSides(EnumSet.allOf(Direction.class))
|
||||
.addService(IGridTickable.class, this);
|
||||
mainNode.setIdlePowerUsage(0.0);
|
||||
mainNode.setIdlePowerUsage(AE_PER_TICK);
|
||||
actionSource = IActionSource.ofMachine(this);
|
||||
}
|
||||
|
||||
@@ -225,9 +215,6 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
if (turnSeconds > 0) {
|
||||
return null;
|
||||
}
|
||||
if (!canPayEnergy()) {
|
||||
return WaitReason.NO_POWER;
|
||||
}
|
||||
if (!hasCognitioFuel()) {
|
||||
return WaitReason.NO_ESSENTIA;
|
||||
}
|
||||
@@ -255,16 +242,6 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 能量直扣 ME 网络:500 AE/周期,SIMULATE 预检。 */
|
||||
private boolean canPayEnergy() {
|
||||
IGrid grid = mainNode.getGrid();
|
||||
if (grid == null) {
|
||||
return false;
|
||||
}
|
||||
IEnergyService energy = grid.getEnergyService();
|
||||
return energy.extractAEPower(AE_PER_TURN, Actionable.SIMULATE, PowerMultiplier.ONE) >= AE_PER_TURN;
|
||||
}
|
||||
|
||||
/** cognitio 燃料预检:ME 源质存储须有 2 点可扣。 */
|
||||
private boolean hasCognitioFuel() {
|
||||
IGrid grid = mainNode.getGrid();
|
||||
@@ -281,7 +258,7 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
|
||||
/** 一次抽取同时定下时长和赔率,付过费才开转。 */
|
||||
private void beginTurn(ServerLevel server) {
|
||||
Turn drawn = roll(server.getRandom(), cardCount());
|
||||
var drawn = ProbabilityBrainRules.roll(server.getRandom(), cardCount());
|
||||
if (!payForTurn()) {
|
||||
return;
|
||||
}
|
||||
@@ -290,7 +267,7 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
setChanged();
|
||||
}
|
||||
|
||||
/** 扣 2 点 cognitio 加 500 AE 电力;付不出就不开转。 */
|
||||
/** 每轮只扣 2 点 cognitio,电力通过节点的持续耗能结算。 */
|
||||
private boolean payForTurn() {
|
||||
IGrid grid = mainNode.getGrid();
|
||||
AEKey cog = cognitioKey();
|
||||
@@ -302,11 +279,6 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
return false;
|
||||
}
|
||||
MEStorage inventory = storage.getInventory();
|
||||
IEnergyService energy = grid.getEnergyService();
|
||||
// 能量 SIMULATE(double 记账,禁截断)
|
||||
if (energy.extractAEPower(AE_PER_TURN, Actionable.SIMULATE, PowerMultiplier.ONE) < AE_PER_TURN) {
|
||||
return false;
|
||||
}
|
||||
// 燃料 SIMULATE → MODULATE(竞态兜底:不足则退回已扣部分)
|
||||
if (inventory.extract(cog, COGNITIO_PER_TURN, Actionable.SIMULATE, actionSource) < COGNITIO_PER_TURN) {
|
||||
return false;
|
||||
@@ -318,7 +290,6 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
}
|
||||
return false;
|
||||
}
|
||||
energy.extractAEPower(AE_PER_TURN, Actionable.MODULATE, PowerMultiplier.ONE);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -411,29 +382,9 @@ public class BrainOfProbabilityBlockEntity extends ThETileBase
|
||||
|
||||
// ===== 骰子(CE GachaOdds 同构) =====
|
||||
|
||||
/** 装这么多张卡时可能掷出的最长转动。 */
|
||||
private static int longestSeconds(int cards) {
|
||||
return Math.max(LONGEST_WITH_CARDS, LONGEST_SECONDS - SECONDS_PER_CARD * cards);
|
||||
}
|
||||
|
||||
/** 这个时长的转动给奖的赔率,只看时长。 */
|
||||
private static double payoutChance(int seconds) {
|
||||
double along = (double) (seconds - MIN_SECONDS) / (LONGEST_SECONDS - MIN_SECONDS);
|
||||
return CHANCE_AT_MIN_SECONDS + (CHANCE_AT_LONGEST_SECONDS - CHANCE_AT_MIN_SECONDS) * along;
|
||||
}
|
||||
|
||||
/** 掷出的一次转动:跑多少秒,给不给奖。 */
|
||||
private record Turn(int seconds, boolean pays) {}
|
||||
|
||||
/** 一次抽取定下两半:落到的时长决定这次转动的赔率。 */
|
||||
private Turn roll(RandomSource random, int cards) {
|
||||
int seconds = MIN_SECONDS + random.nextInt(longestSeconds(cards) - MIN_SECONDS + 1);
|
||||
return new Turn(seconds, random.nextDouble() < payoutChance(seconds));
|
||||
}
|
||||
|
||||
/** 箱子为什么停着不动:blankScreen = 该修装置(死屏),其余为待机屏。 */
|
||||
private enum WaitReason {
|
||||
NO_STRUCTURE, NO_BRAIN, UNBOUND_BRAIN, NO_CHANNEL, OWNER_OFFLINE, NO_POWER, NO_ESSENTIA;
|
||||
NO_STRUCTURE, NO_BRAIN, UNBOUND_BRAIN, NO_CHANNEL, OWNER_OFFLINE, NO_ESSENTIA;
|
||||
|
||||
boolean blankScreen() {
|
||||
return this == NO_STRUCTURE || this == NO_CHANNEL;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package thaumicenergistics.common.tiles;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import thaumicenergistics.common.crafting.ArcaneAssemblerPattern;
|
||||
import thaumicenergistics.common.crafting.ArcaneCraftJob;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Hashtable;
|
||||
import java.util.List;
|
||||
@@ -9,7 +11,6 @@ import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.Containers;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
@@ -37,12 +38,10 @@ import appeng.api.networking.crafting.ICraftingProvider;
|
||||
import appeng.api.networking.energy.IEnergyService;
|
||||
import appeng.api.networking.security.IActionHost;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
import appeng.api.networking.storage.IStorageService;
|
||||
import appeng.api.networking.ticking.IGridTickable;
|
||||
import appeng.api.networking.ticking.TickRateModulation;
|
||||
import appeng.api.networking.ticking.TickingRequest;
|
||||
import appeng.api.stacks.AEItemKey;
|
||||
import appeng.api.stacks.AEKey;
|
||||
import appeng.api.stacks.GenericStack;
|
||||
import appeng.api.stacks.KeyCounter;
|
||||
import appeng.api.util.AECableType;
|
||||
@@ -51,7 +50,6 @@ import thaumcraft.api.IVisDiscountGear;
|
||||
import thaumcraft.api.IWarpingGear;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.api.aspects.AspectList;
|
||||
import thaumcraft.api.crafting.IArcaneRecipe;
|
||||
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.integration.tc.ArcaneCraftingPattern;
|
||||
@@ -91,7 +89,7 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
private static final int VIS_REPLENISH_INTERVAL = 5;
|
||||
/** 每次充能上限(cvis/次,每 VIS_REPLENISH_INTERVAL tick 一次 ≈ 20 cVis/tick)。 */
|
||||
private static final int MAX_CVIS_PER_REPLENISH = 100;
|
||||
/** 每次实际 vis 变化累计达到该值才调用一次 setChanged(约 4×5=20 tick),避免合成期间 chunk 持续处于 unsaved 状态。 */
|
||||
/** vis 变化累计达到该值才同步客户端(约 4×5=20 tick);存档变化即时标记。 */
|
||||
private static final int SET_CHANGED_INTERVAL = 4;
|
||||
/** 元始珍珠:TC 奥术配方中唯一 retainIngredient 原料(ShapedArcaneRecipe.retainIngredient),合成不消耗。 */
|
||||
private static final ResourceLocation PRIMORDIAL_PEARL_ID =
|
||||
@@ -129,15 +127,10 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
private boolean isCrafting = false;
|
||||
private int craftTickCounter = 0;
|
||||
private int speedUpgrades = 0;
|
||||
/** 当前合成配方的 3×3 材料网格(GUI 右下配方预览用,随合成开始填充、结束清空)。 */
|
||||
private ItemStack[] previewGrid = emptyPreviewGrid();
|
||||
private final ArcaneCraftJob job = new ArcaneCraftJob();
|
||||
/** 旧存档缺少订单定义时保留忙碌状态,等待核心提供唯一配方。 */
|
||||
private boolean legacyCraftBlocked;
|
||||
|
||||
/** 全 EMPTY 的 9 格预览数组(避免 null 元素导致网络包编码崩溃)。 */
|
||||
private static ItemStack[] emptyPreviewGrid() {
|
||||
ItemStack[] grid = new ItemStack[9];
|
||||
java.util.Arrays.fill(grid, ItemStack.EMPTY);
|
||||
return grid;
|
||||
}
|
||||
/**
|
||||
* 从内存卡粘贴的 vis_interface P2P 频率;装配器优先从该频率的 vis_interface P2P 端抽 vis。
|
||||
* 0 = 未设置,走 essentia 网络。对应 1.7.10 的 visSourceInfo,但用 P2P 频率替代位置(适配 neo P2P 设计)。
|
||||
@@ -146,9 +139,6 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
private AspectList storedVis = new AspectList();
|
||||
private Hashtable<Aspect, Float> visDiscount = new Hashtable<>();
|
||||
private float warpPowerMultiplier = 1.0F;
|
||||
private IArcaneRecipe currentRecipe = null;
|
||||
private AspectList currentRecipeAspects = new AspectList();
|
||||
private ItemStack currentResult = ItemStack.EMPTY;
|
||||
private int visTickCounter = 0;
|
||||
/** replenishVis 的 setChanged 节流计数。 */
|
||||
private int visSetChangedCounter = 0;
|
||||
@@ -204,6 +194,15 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
public void onBreakBlock() {
|
||||
super.onBreakBlock();
|
||||
if (level != null && !level.isClientSide) {
|
||||
// 制作前退真实材料,制作后只掉落尚未输出的产物和催化剂。
|
||||
var remaining = job.produced() ? job.outputs() : java.util.Arrays.asList(job.inputs());
|
||||
if (isCrafting) {
|
||||
for (ItemStack stack : remaining) {
|
||||
if (!stack.isEmpty()) Containers.dropItemStack(level,
|
||||
worldPosition.getX(), worldPosition.getY(), worldPosition.getZ(), stack.copy());
|
||||
}
|
||||
finishCrafting();
|
||||
}
|
||||
for (int i = 0; i < SLOT_COUNT; i++) {
|
||||
if (i >= PATTERN_SLOT_START && i <= PATTERN_SLOT_END) continue;
|
||||
if (i == TARGET_SLOT) continue;
|
||||
@@ -313,10 +312,11 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
}
|
||||
|
||||
/**
|
||||
* replenishVis 抽到 vis 时调用:累计变化次数,每 SET_CHANGED_INTERVAL 次才 markForUpdate 一次。
|
||||
* replenishVis 抽到 vis 时调用:累计变化次数,每次保存变化,SET_CHANGED_INTERVAL 次才同步客户端一次。
|
||||
* markForUpdate = setChanged + sendBlockUpdated(同步 storedVis 到客户端 BE,GUI 进度条依赖客户端 storedVis)。
|
||||
*/
|
||||
private void maybeMarkVisDirty() {
|
||||
setChanged();
|
||||
if (++visSetChangedCounter >= SET_CHANGED_INTERVAL) {
|
||||
visSetChangedCounter = 0;
|
||||
markForUpdate();
|
||||
@@ -324,11 +324,10 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
}
|
||||
|
||||
private TickRateModulation craftingTick(IGrid grid, int ticksSinceLast) {
|
||||
if (currentResult.isEmpty()) {
|
||||
isCrafting = false;
|
||||
previewGrid = emptyPreviewGrid();
|
||||
AssemblerPreviewSyncPacket.send(this, false);
|
||||
return TickRateModulation.IDLE;
|
||||
if (job.produced()) return flushCraftOutputs(grid);
|
||||
if (job.result().isEmpty()) {
|
||||
if (!legacyCraftBlocked) restoreLegacyCraft();
|
||||
if (job.result().isEmpty()) return TickRateModulation.IDLE;
|
||||
}
|
||||
|
||||
boolean enoughVis = hasEnoughVisForCraft();
|
||||
@@ -339,55 +338,10 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
int ticksPerCraft = ticksPerCraft();
|
||||
|
||||
if (craftTickCounter >= ticksPerCraft) {
|
||||
IStorageService storage = grid.getService(IStorageService.class);
|
||||
if (storage == null) return TickRateModulation.IDLE;
|
||||
|
||||
ItemStack output = currentResult.copy();
|
||||
AEItemKey outputKey = AEItemKey.of(output);
|
||||
if (outputKey == null) return TickRateModulation.IDLE;
|
||||
|
||||
// 元始珍珠保留:TC 唯一 retainIngredient 原料,合成后珍珠退回网络(与奥术合成终端一致)。
|
||||
// CPU 已按配方从网络扣除珍珠,这里补回 → 净零不消耗。
|
||||
var retainedPearls = retainedPearlStacks();
|
||||
|
||||
long inserted = storage.getInventory().insert(
|
||||
outputKey, output.getCount(), Actionable.SIMULATE, actionSource);
|
||||
if (inserted < output.getCount()) {
|
||||
return TickRateModulation.SAME;
|
||||
}
|
||||
// 预检:珍珠类型塞满放不回网络则等待,避免合成完成却丢珍珠
|
||||
for (ItemStack pearl : retainedPearls) {
|
||||
AEItemKey pearlKey = AEItemKey.of(pearl);
|
||||
if (pearlKey == null) continue;
|
||||
if (storage.getInventory().insert(
|
||||
pearlKey, pearl.getCount(), Actionable.SIMULATE, actionSource) < pearl.getCount()) {
|
||||
return TickRateModulation.SAME;
|
||||
}
|
||||
}
|
||||
|
||||
consumeVisForCraft();
|
||||
|
||||
storage.getInventory().insert(
|
||||
outputKey, output.getCount(), Actionable.MODULATE, actionSource);
|
||||
// 退回珍珠(数量 = 3×3 配方网格中珍珠总数,通常 1 颗)
|
||||
for (ItemStack pearl : retainedPearls) {
|
||||
AEItemKey pearlKey = AEItemKey.of(pearl);
|
||||
if (pearlKey != null) {
|
||||
storage.getInventory().insert(pearlKey, pearl.getCount(), Actionable.MODULATE, actionSource);
|
||||
}
|
||||
}
|
||||
|
||||
isCrafting = false;
|
||||
currentRecipe = null;
|
||||
currentResult = ItemStack.EMPTY;
|
||||
currentRecipeAspects = new AspectList();
|
||||
previewGrid = emptyPreviewGrid();
|
||||
internalInventory.setItem(TARGET_SLOT, ItemStack.EMPTY);
|
||||
job.produce(retainedPearlStacks());
|
||||
setChanged();
|
||||
markForUpdate();
|
||||
AssemblerPreviewSyncPacket.send(this, false);
|
||||
|
||||
return TickRateModulation.URGENT;
|
||||
return flushCraftOutputs(grid);
|
||||
}
|
||||
|
||||
double powerRequired = (ACTIVE_POWER + (ACTIVE_POWER * speedUpgrades) / 2.0) * warpPowerMultiplier;
|
||||
@@ -405,9 +359,35 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
return TickRateModulation.SAME;
|
||||
}
|
||||
|
||||
private TickRateModulation flushCraftOutputs(IGrid grid) {
|
||||
var storage = grid.getStorageService().getInventory();
|
||||
for (var output : job.outputs()) {
|
||||
if (output.isEmpty()) continue;
|
||||
long accepted = storage.insert(AEItemKey.of(output), output.getCount(), Actionable.MODULATE, actionSource);
|
||||
if (accepted > 0) {
|
||||
output.shrink((int) Math.min(accepted, output.getCount()));
|
||||
setChanged();
|
||||
}
|
||||
}
|
||||
job.outputs().removeIf(ItemStack::isEmpty);
|
||||
if (!job.outputs().isEmpty()) return TickRateModulation.SAME;
|
||||
finishCrafting();
|
||||
return TickRateModulation.URGENT;
|
||||
}
|
||||
|
||||
private void finishCrafting() {
|
||||
isCrafting = false;
|
||||
legacyCraftBlocked = false;
|
||||
job.clear();
|
||||
internalInventory.setItem(TARGET_SLOT, ItemStack.EMPTY);
|
||||
mainNode.setIdlePowerUsage(IDLE_POWER);
|
||||
markForUpdate();
|
||||
AssemblerPreviewSyncPacket.send(this, false);
|
||||
}
|
||||
|
||||
private void consumeVisForCraft() {
|
||||
if (currentRecipeAspects == null || currentRecipeAspects.isEmpty()) return;
|
||||
for (Aspect aspect : currentRecipeAspects.getAspects()) {
|
||||
if (job.aspects() == null || job.aspects().isEmpty()) return;
|
||||
for (Aspect aspect : job.aspects().getAspects()) {
|
||||
int requiredCvis = getRequiredCvisForAspect(aspect);
|
||||
int current = storedVis.getAmount(aspect);
|
||||
storedVis.reduce(aspect, Math.min(requiredCvis, current));
|
||||
@@ -416,8 +396,8 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
}
|
||||
|
||||
private boolean hasEnoughVisForCraft() {
|
||||
if (currentRecipeAspects == null || currentRecipeAspects.isEmpty()) return true;
|
||||
for (Aspect aspect : currentRecipeAspects.getAspects()) {
|
||||
if (job.aspects() == null || job.aspects().isEmpty()) return true;
|
||||
for (Aspect aspect : job.aspects().getAspects()) {
|
||||
int requiredCvis = getRequiredCvisForAspect(aspect);
|
||||
if (storedVis.getAmount(aspect) < requiredCvis) return false;
|
||||
}
|
||||
@@ -425,8 +405,8 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
}
|
||||
|
||||
private int getRequiredCvisForAspect(Aspect aspect) {
|
||||
if (currentRecipeAspects == null) return 0;
|
||||
int baseCost = currentRecipeAspects.getAmount(aspect) * CVIS_MULTIPLIER;
|
||||
if (job.aspects() == null) return 0;
|
||||
int baseCost = job.aspects().getAmount(aspect) * CVIS_MULTIPLIER;
|
||||
float discount = visDiscount.getOrDefault(aspect, BASE_VIS_DISCOUNT);
|
||||
return Math.max(0, Math.round(baseCost * discount));
|
||||
}
|
||||
@@ -437,8 +417,8 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
*/
|
||||
private List<ItemStack> retainedPearlStacks() {
|
||||
List<ItemStack> pearls = new ArrayList<>();
|
||||
if (previewGrid == null) return pearls;
|
||||
for (ItemStack stack : previewGrid) {
|
||||
if (job.inputs() == null) return pearls;
|
||||
for (ItemStack stack : job.inputs()) {
|
||||
if (!stack.isEmpty() && stack.getItem() == BuiltInRegistries.ITEM.get(PRIMORDIAL_PEARL_ID)) {
|
||||
pearls.add(stack.copy());
|
||||
}
|
||||
@@ -504,12 +484,12 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
@Override
|
||||
public boolean pushPattern(IPatternDetails patternDetails, KeyCounter[] inputHolder) {
|
||||
if (patternDetails instanceof ArcaneAssemblerPattern arcanePattern) {
|
||||
return beginCrafting(arcanePattern);
|
||||
return beginCrafting(arcanePattern, inputHolder);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private ArcaneAssemblerPattern buildArcanePattern(ArcaneCraftingPattern acp) {
|
||||
public static ArcaneAssemblerPattern buildArcanePattern(ArcaneCraftingPattern acp) {
|
||||
ItemStack result = acp.getResult();
|
||||
if (result == null || result.isEmpty()) return null;
|
||||
|
||||
@@ -529,50 +509,63 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
}
|
||||
}
|
||||
|
||||
return new ArcaneAssemblerPattern(AEItemKey.of(result), null, aspects, result, inputs,
|
||||
return new ArcaneAssemblerPattern(thaumicenergistics.common.crafting.ArcanePatternDecoder.definition(acp), null, aspects, result, inputs,
|
||||
acp.getResearch(), acp.getIngredients(), alternatives);
|
||||
}
|
||||
|
||||
/**
|
||||
* 样板编码把通配具象化成了编码时的单一变体(如 wisp_essence_ordo),AE2 自动合成时网络里
|
||||
* 若是另一变体(wisp_essence_aer)即报材料不足——手工奥术合成走 tag 匹配没这问题。
|
||||
* 此处把属于本模组自定义通配 tag(wisp_essences/monitors 等)的格子展开为 tag 全部物品,
|
||||
* 作为样板输入的备选变体;只认本模组命名空间,避免把 forge 等通用 tag 成员全卷进来。
|
||||
* Keep the encoded stack as the primary input shown by the crafting planner.
|
||||
* Explicit component patches are part of its identity and must never be
|
||||
* replaced with bare items from a tag. Component-free tag recipes can still
|
||||
* substitute other valid variants, after the originally selected item.
|
||||
*/
|
||||
private static GenericStack[] expandTagAlternates(ItemStack ing) {
|
||||
GenericStack encoded = new GenericStack(AEItemKey.of(ing), ing.getCount());
|
||||
if (!ing.getComponentsPatch().isEmpty()) {
|
||||
return new GenericStack[]{encoded};
|
||||
}
|
||||
for (TagKey<Item> tag : ing.getItemHolder().tags().toList()) {
|
||||
if (!tag.location().getNamespace().equals(ThaumicEnergistics.MODID)) continue;
|
||||
var named = BuiltInRegistries.ITEM.getTag(tag);
|
||||
if (named.isEmpty()) continue;
|
||||
List<GenericStack> alts = new ArrayList<>();
|
||||
alts.add(encoded);
|
||||
for (Holder<Item> holder : named.get()) {
|
||||
AEItemKey key = AEItemKey.of(holder.value());
|
||||
if (key != null) alts.add(new GenericStack(key, ing.getCount()));
|
||||
ItemStack candidate = holder.value().getDefaultInstance();
|
||||
// The generic wisp essence has no aspect without its component.
|
||||
// Tag membership alone does not make it a usable alternative.
|
||||
if (tag.location().getPath().equals("wisp_essences")
|
||||
&& !hasWispAspect(candidate)) continue;
|
||||
AEItemKey key = AEItemKey.of(candidate);
|
||||
if (key != null && alts.stream().noneMatch(alt -> alt.what().equals(key))) {
|
||||
alts.add(new GenericStack(key, ing.getCount()));
|
||||
}
|
||||
}
|
||||
if (alts.size() > 1) return alts.toArray(new GenericStack[0]);
|
||||
}
|
||||
return new GenericStack[]{new GenericStack(AEItemKey.of(ing), ing.getCount())};
|
||||
return new GenericStack[]{encoded};
|
||||
}
|
||||
|
||||
private boolean beginCrafting(ArcaneAssemblerPattern arcanePattern) {
|
||||
private static boolean hasWispAspect(ItemStack stack) {
|
||||
if (!(stack.getItem() instanceof thaumcraft.api.aspects.IEssentiaContainerItem container)) {
|
||||
return false;
|
||||
}
|
||||
AspectList contents = container.getAspects(stack);
|
||||
return contents != null && !contents.isEmpty();
|
||||
}
|
||||
|
||||
private boolean beginCrafting(ArcaneAssemblerPattern arcanePattern, KeyCounter[] inputHolder) {
|
||||
AspectList aspects = arcanePattern.getAspects();
|
||||
ItemStack result = arcanePattern.getResultStack();
|
||||
if (isCrafting || !mainNode.isActive()) return false;
|
||||
if (aspects == null || aspects.isEmpty() || result.isEmpty()) return false;
|
||||
var actualGrid = arcanePattern.materializeInputs(inputHolder, level);
|
||||
if (actualGrid == null) return false;
|
||||
|
||||
this.isCrafting = true;
|
||||
this.craftTickCounter = 0;
|
||||
this.currentRecipe = arcanePattern.getRecipe();
|
||||
this.currentRecipeAspects = aspects.copy();
|
||||
this.currentResult = result.copy();
|
||||
// 配方预览:复制 3×3 材料网格(不足 9 格补空)
|
||||
this.previewGrid = emptyPreviewGrid();
|
||||
ItemStack[] grid = arcanePattern.getGrid();
|
||||
if (grid != null) {
|
||||
for (int i = 0; i < 9 && i < grid.length; i++) {
|
||||
this.previewGrid[i] = grid[i] != null ? grid[i].copy() : ItemStack.EMPTY;
|
||||
}
|
||||
}
|
||||
job.start(aspects, result, actualGrid);
|
||||
for (var holder : inputHolder) holder.reset();
|
||||
this.internalInventory.setItem(TARGET_SLOT, result.copy());
|
||||
setChanged();
|
||||
markForUpdate();
|
||||
@@ -598,7 +591,7 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
@Override
|
||||
public boolean pushPattern(IPatternDetails patternDetails, KeyCounter[] inputs, Direction ejectionDirection) {
|
||||
if (patternDetails instanceof ArcaneAssemblerPattern arcanePattern) {
|
||||
return beginCrafting(arcanePattern);
|
||||
return beginCrafting(arcanePattern, inputs);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -613,9 +606,9 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
public int getCraftTickCounter() { return craftTickCounter; }
|
||||
public int getTicksPerCraft() { return ticksPerCraft(); }
|
||||
/** 当前合成配方的 3×3 材料网格(GUI 右下配方预览;未合成时为空数组)。 */
|
||||
public ItemStack[] getPreviewGrid() { return previewGrid; }
|
||||
public ItemStack[] getPreviewGrid() { return job.inputs(); }
|
||||
/** 当前合成产物(GUI 预产物显示;未合成为空)。 */
|
||||
public ItemStack getCurrentResult() { return currentResult; }
|
||||
public ItemStack getCurrentResult() { return job.result(); }
|
||||
public float getCraftProgress() {
|
||||
if (!isCrafting || ticksPerCraft() <= 0) return 0f;
|
||||
return Math.min(1f, (float) craftTickCounter / ticksPerCraft());
|
||||
@@ -663,6 +656,7 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
|
||||
public void onInventoryChanged(int slot) {
|
||||
if (slot == KCORE_SLOT) {
|
||||
legacyCraftBlocked = false;
|
||||
stalePatterns = true;
|
||||
updatePatternSlots();
|
||||
// 直接通知 AE2 合成服务重新拉取 getAvailablePatterns()。
|
||||
@@ -738,7 +732,7 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
// 配方预览 3×3 材料(GUI 右下角显示)
|
||||
CompoundTag gridTag = new CompoundTag();
|
||||
for (int i = 0; i < 9; i++) {
|
||||
ItemStack stack = previewGrid[i];
|
||||
ItemStack stack = job.inputs()[i];
|
||||
if (stack != null && !stack.isEmpty()) {
|
||||
gridTag.put("g" + i, stack.save(reg));
|
||||
}
|
||||
@@ -749,9 +743,9 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
|
||||
@Override
|
||||
public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider reg) {
|
||||
super.handleUpdateTag(tag, reg);
|
||||
loadingFromClientTag = true;
|
||||
try {
|
||||
super.handleUpdateTag(tag, reg);
|
||||
for (int i = 0; i < SLOT_COUNT; i++) {
|
||||
if (tag.contains("Slot" + i)) {
|
||||
ItemStack stack = ItemStack.parseOptional(reg, tag.getCompound("Slot" + i));
|
||||
@@ -760,12 +754,12 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
internalInventory.setItem(i, ItemStack.EMPTY);
|
||||
}
|
||||
}
|
||||
previewGrid = emptyPreviewGrid();
|
||||
job.clearPreview();
|
||||
if (tag.contains("PreviewGrid")) {
|
||||
CompoundTag gridTag = tag.getCompound("PreviewGrid");
|
||||
for (int i = 0; i < 9; i++) {
|
||||
if (gridTag.contains("g" + i)) {
|
||||
previewGrid[i] = ItemStack.parseOptional(reg, gridTag.getCompound("g" + i));
|
||||
job.inputs()[i] = ItemStack.parseOptional(reg, gridTag.getCompound("g" + i));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -778,7 +772,6 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
protected void loadAdditional(CompoundTag tag, HolderLookup.Provider reg) {
|
||||
super.loadAdditional(tag, reg);
|
||||
mainNode.loadFromNBT(tag);
|
||||
mainNode.setIdlePowerUsage(isCrafting ? ACTIVE_POWER : IDLE_POWER);
|
||||
|
||||
if (tag.contains("AttachSide")) attachmentSide = Direction.from3DDataValue(tag.getInt("AttachSide"));
|
||||
isCrafting = tag.getBoolean("IsCrafting");
|
||||
@@ -806,12 +799,37 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
}
|
||||
}
|
||||
|
||||
job.load(tag, reg);
|
||||
legacyCraftBlocked = false;
|
||||
if (isCrafting && job.result().isEmpty()) restoreLegacyCraft();
|
||||
// 制作电力由 craftingTick 实扣,重载不能额外叠加节点闲置耗电。
|
||||
mainNode.setIdlePowerUsage(IDLE_POWER);
|
||||
|
||||
updatePatternSlots();
|
||||
stalePatterns = true;
|
||||
calculateVisDiscounts();
|
||||
recountSpeedUpgrades();
|
||||
}
|
||||
|
||||
/** 老存档只保存目标槽:仅在知识核心能唯一确定配方时恢复,避免猜错配方。 */
|
||||
private void restoreLegacyCraft() {
|
||||
var target = internalInventory.getItem(TARGET_SLOT);
|
||||
var core = internalInventory.getItem(KCORE_SLOT);
|
||||
if (!target.isEmpty() && core.is(ModItems.KNOWLEDGE_CORE.get())) {
|
||||
var matches = new HandlerKnowledgeCore(core).getPatterns().stream()
|
||||
.filter(pattern -> pattern != null && pattern.isPatternValid()
|
||||
&& ItemStack.matches(pattern.getResult(), target)).toList();
|
||||
if (matches.size() == 1) {
|
||||
var pattern = matches.getFirst();
|
||||
job.start(pattern.getAspects(), target, pattern.getIngredients());
|
||||
legacyCraftBlocked = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
ThaumicEnergistics.LOG.warn("Pausing legacy arcane craft at {}: missing or ambiguous pattern; restore a unique knowledge-core recipe to resume", worldPosition);
|
||||
legacyCraftBlocked = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void saveAdditional(CompoundTag tag, HolderLookup.Provider reg) {
|
||||
super.saveAdditional(tag, reg);
|
||||
@@ -820,6 +838,7 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
tag.putBoolean("IsCrafting", isCrafting);
|
||||
tag.putInt("CraftTick", craftTickCounter);
|
||||
tag.putInt("SpeedUpgrades", speedUpgrades);
|
||||
job.save(tag, reg);
|
||||
if (visSourceFreq != 0) tag.putShort("VisSourceFreq", visSourceFreq);
|
||||
|
||||
CompoundTag visTag = new CompoundTag();
|
||||
@@ -839,126 +858,4 @@ public class TileArcaneAssembler extends ThETileBase
|
||||
}
|
||||
}
|
||||
|
||||
public static class ArcaneAssemblerPattern implements IPatternDetails {
|
||||
private final AEItemKey definition;
|
||||
private final IArcaneRecipe recipe;
|
||||
private final AspectList aspects;
|
||||
private final ItemStack resultStack;
|
||||
private final IInput[] inputs;
|
||||
private final String research;
|
||||
/** 3×3 配方网格(知识核心存储的 9 格材料,GUI 配方预览用)。 */
|
||||
private final ItemStack[] grid;
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks) {
|
||||
this(definition, recipe, aspects, resultStack, inputStacks, null, null, null);
|
||||
}
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks, String research) {
|
||||
this(definition, recipe, aspects, resultStack, inputStacks, research, null, null);
|
||||
}
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks, String research, ItemStack[] grid) {
|
||||
this(definition, recipe, aspects, resultStack, inputStacks, research, grid, null);
|
||||
}
|
||||
|
||||
public ArcaneAssemblerPattern(AEItemKey definition, IArcaneRecipe recipe,
|
||||
AspectList aspects, ItemStack resultStack,
|
||||
List<GenericStack> inputStacks, String research, ItemStack[] grid,
|
||||
List<GenericStack[]> inputAlternatives) {
|
||||
this.definition = definition;
|
||||
this.recipe = recipe;
|
||||
this.aspects = aspects;
|
||||
this.resultStack = resultStack;
|
||||
this.research = research;
|
||||
this.grid = grid;
|
||||
this.inputs = new IInput[inputStacks.size()];
|
||||
for (int i = 0; i < inputStacks.size(); i++) {
|
||||
GenericStack stack = inputStacks.get(i);
|
||||
// 通配变体组(tag 展开结果);null/单元素退化为精确匹配(与旧行为一致)
|
||||
GenericStack[] alts = (inputAlternatives != null && i < inputAlternatives.size()
|
||||
&& inputAlternatives.get(i) != null)
|
||||
? inputAlternatives.get(i)
|
||||
: new GenericStack[]{stack};
|
||||
this.inputs[i] = new IInput() {
|
||||
@Override
|
||||
public GenericStack[] getPossibleInputs() {
|
||||
return alts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getMultiplier() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(AEKey input, Level level) {
|
||||
if (!(input instanceof AEItemKey itemKey)) return false;
|
||||
for (GenericStack alt : alts) {
|
||||
if (alt.what() instanceof AEItemKey altKey && altKey.equals(itemKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public AEKey getRemainingKey(AEKey what) {
|
||||
// 元始珍珠作为"催化"原料:声明合成后它会返回网络(AE2 原生容器机制)。
|
||||
// 规划端据此按"每次 1 单"顺序模拟、执行端把珍珠计入 CPU waitingFor,
|
||||
// 机器合成完成把珍珠退回网络后 CPU 自动捕获续下一单——1 颗珍珠可连续多单。
|
||||
if (what instanceof AEItemKey itemKey
|
||||
&& itemKey.getItem() == BuiltInRegistries.ITEM.get(PRIMORDIAL_PEARL_ID)) {
|
||||
return what;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AEItemKey getDefinition() { return definition; }
|
||||
|
||||
@Override
|
||||
public IInput[] getInputs() { return inputs; }
|
||||
|
||||
@Override
|
||||
public List<GenericStack> getOutputs() {
|
||||
return List.of(new GenericStack(AEItemKey.of(resultStack), resultStack.getCount()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPushInputsToExternalInventory() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof ArcaneAssemblerPattern other)) return false;
|
||||
return definition != null && definition.equals(other.definition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return definition != null ? definition.hashCode() : 0;
|
||||
}
|
||||
|
||||
public IArcaneRecipe getRecipe() { return recipe; }
|
||||
public AspectList getAspects() { return aspects; }
|
||||
public ItemStack getResultStack() { return resultStack; }
|
||||
/** 3×3 配方网格(可能为 null/短数组,GUI 预览用)。 */
|
||||
@Nullable
|
||||
public ItemStack[] getGrid() { return grid; }
|
||||
/** 对应 TC 奥术配方的研究键;无研究要求/老数据时可能为 null。 */
|
||||
@Nullable
|
||||
public String getResearch() { return research; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package thaumicenergistics.common.tiles;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import thaumicenergistics.common.monitor.InfusionMonitorDisplay;
|
||||
import thaumicenergistics.common.monitor.InfusionMonitorText;
|
||||
import static thaumicenergistics.common.monitor.InfusionMonitorText.*;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
@@ -8,17 +11,13 @@ import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.Containers;
|
||||
import net.minecraft.world.SimpleContainer;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.Display;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
import appeng.api.networking.GridFlags;
|
||||
import appeng.api.networking.GridHelper;
|
||||
@@ -27,12 +26,10 @@ import appeng.api.networking.IGridNodeListener;
|
||||
import appeng.api.networking.IManagedGridNode;
|
||||
import appeng.api.networking.IInWorldGridNodeHost;
|
||||
import appeng.api.util.AECableType;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.init.ModBlockEntities;
|
||||
import thaumicenergistics.init.ModBlocks;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import thaumcraft.common.blockentities.InfusionMatrixBlockEntity;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
@@ -85,22 +82,8 @@ public class TileInfusionMonitor extends ThETileBase implements IInWorldGridNode
|
||||
/** 区块卸载/方块移除中:禁止 setBlock / markForUpdate(卸载时改方块状态会触发区块重载,停服保存死循环)。 */
|
||||
private boolean unloading = false;
|
||||
|
||||
/** 上一次写入气泡的文本(内容未变则跳过反射/NBT 重建,避免每 tick 开销)。 */
|
||||
private net.minecraft.network.chat.Component lastBubbleText = null;
|
||||
|
||||
/** 缓存的注魔风险数据(弹窗显示)。 */
|
||||
private RiskData cachedRisk = RiskData.NONE;
|
||||
|
||||
/** 悬浮气泡实体(text_display,服务端引用)。 */
|
||||
private net.minecraft.world.entity.Display.TextDisplay bubble;
|
||||
|
||||
/** 气泡实体 Tag(用于坐标匹配查找)。 */
|
||||
private static final String BUBBLE_TAG = "thaumicenergistics:monitor_bubble";
|
||||
/** 气泡背景:半透明深灰(ARGB,Alpha=176)。 */
|
||||
private static final int BUBBLE_BG_COLOR = 0xB0333333;
|
||||
/** 气泡行宽(换行宽度)。中文全角字符约 12px,最长行"不稳定度: 9 (基础 5 + 祭坛 4)"约 240px——
|
||||
* 必须大于最长行,否则行尾空格被换行逻辑丢弃、背景只包住分段 → 右侧看似截断。 */
|
||||
private static final int BUBBLE_LINE_WIDTH = 320;
|
||||
private final InfusionMonitorDisplay display = new InfusionMonitorDisplay(this::getLevel, worldPosition);
|
||||
|
||||
private final IGridNodeListener<TileInfusionMonitor> nodeListener = new IGridNodeListener<>() {
|
||||
@Override
|
||||
@@ -144,7 +127,7 @@ public class TileInfusionMonitor extends ThETileBase implements IInWorldGridNode
|
||||
unloading = true; // 先置标志再销毁网格节点:节点销毁回调会触发 updateNetworkState
|
||||
super.setRemoved();
|
||||
if (level != null && !level.isClientSide()) {
|
||||
discardBubble();
|
||||
display.discard();
|
||||
}
|
||||
if (mainNode != null) {
|
||||
mainNode.destroy();
|
||||
@@ -164,7 +147,7 @@ public class TileInfusionMonitor extends ThETileBase implements IInWorldGridNode
|
||||
public void onBreakBlock() {
|
||||
super.onBreakBlock();
|
||||
if (level != null && !level.isClientSide) {
|
||||
discardBubble();
|
||||
display.discard();
|
||||
Containers.dropContents(level, worldPosition, inventory);
|
||||
}
|
||||
}
|
||||
@@ -311,155 +294,7 @@ public class TileInfusionMonitor extends ThETileBase implements IInWorldGridNode
|
||||
boolean shouldShow = getBlockState().getValue(ModBlocks.BOOK)
|
||||
&& getBlockState().getValue(ModBlocks.NETWORK)
|
||||
&& cachedRisk.found();
|
||||
if (shouldShow) {
|
||||
ensureBubble();
|
||||
if (bubble != null) {
|
||||
// 文本未变则跳过反射/NBT 重建(原实现每 tick 都重建,是 mspt 开销之一)
|
||||
net.minecraft.network.chat.Component text = buildBubbleText(cachedRisk);
|
||||
if (!text.equals(lastBubbleText)) {
|
||||
lastBubbleText = text;
|
||||
applyBubbleNbt(text);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
discardBubble();
|
||||
lastBubbleText = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 确保气泡实体存在(不存在则生成;区块重载后按 Tag 找回旧实体)。 */
|
||||
private void ensureBubble() {
|
||||
if (bubble != null && bubble.isAlive()) return;
|
||||
bubble = findBubble();
|
||||
if (bubble != null) return;
|
||||
bubble = EntityType.TEXT_DISPLAY.create(level);
|
||||
if (bubble == null) return;
|
||||
bubble.setPos(worldPosition.getX() + 0.5, worldPosition.getY() + 1.2, worldPosition.getZ() + 0.5);
|
||||
// 1.21.1 TextDisplay 配置 API 均为 private/protected:反射调用 readAdditionalSaveData
|
||||
// 用 summon 命令同款 NBT 一次配置全部字段(text/background/billboard/shadow/see_through 等)。
|
||||
applyBubbleNbt(buildBubbleText(cachedRisk));
|
||||
bubble.addTag(BUBBLE_TAG);
|
||||
level.addFreshEntity(bubble);
|
||||
}
|
||||
|
||||
/** 反射调用 readAdditionalSaveData(CompoundTag) 配置气泡(缓存 Method)。 */
|
||||
private static java.lang.reflect.Method READ_NBT_METHOD;
|
||||
|
||||
private void applyBubbleNbt(Component text) {
|
||||
if (bubble == null || level == null) return;
|
||||
try {
|
||||
if (READ_NBT_METHOD == null) {
|
||||
READ_NBT_METHOD = Entity.class
|
||||
.getDeclaredMethod("readAdditionalSaveData", CompoundTag.class);
|
||||
READ_NBT_METHOD.setAccessible(true);
|
||||
}
|
||||
CompoundTag nbt = new CompoundTag();
|
||||
nbt.putString("text", Component.Serializer.toJson(text, level.registryAccess()));
|
||||
nbt.putBoolean("default_background", false);
|
||||
nbt.putInt("background", BUBBLE_BG_COLOR);
|
||||
nbt.putString("billboard", "vertical");
|
||||
nbt.putInt("line_width", BUBBLE_LINE_WIDTH);
|
||||
nbt.putBoolean("shadow", true);
|
||||
nbt.putBoolean("see_through", false);
|
||||
// 必须写 alignment:TextDisplay.readAdditionalSaveData 无条件 decode "alignment",
|
||||
// 缺失时 tag.get 返回 null → Align.CODEC(字符串) decode 失败 → 服务端疯狂刷 "Display entityNot a string"。
|
||||
nbt.putString("alignment", "center");
|
||||
// 文字调小:transformation.scale 整体缩到 0.5(text_display 无字号参数,靠实体缩放)
|
||||
CompoundTag transform = new CompoundTag();
|
||||
transform.put("scale", floatList(0.5F, 0.5F, 0.5F));
|
||||
transform.put("translation", floatList(0F, 0F, 0F));
|
||||
transform.put("left_rotation", floatList(0F, 0F, 0F, 1F));
|
||||
transform.put("right_rotation", floatList(0F, 0F, 0F, 1F));
|
||||
nbt.put("transformation", transform);
|
||||
READ_NBT_METHOD.invoke(bubble, nbt);
|
||||
} catch (Exception e) {
|
||||
ThaumicEnergistics.LOG.warn("[Monitor] 气泡配置失败: {}", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** 构造 FloatTag 列表(1.21.1 CompoundTag 无 putFloatArray,需 ListTag)。 */
|
||||
private static net.minecraft.nbt.ListTag floatList(float... values) {
|
||||
net.minecraft.nbt.ListTag list = new net.minecraft.nbt.ListTag();
|
||||
for (float v : values) {
|
||||
list.add(net.minecraft.nbt.FloatTag.valueOf(v));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/** 按 Tag + 方块附近 AABB 查找已存在的气泡。 */
|
||||
private net.minecraft.world.entity.Display.TextDisplay findBubble() {
|
||||
if (level == null) return null;
|
||||
AABB aabb = new AABB(worldPosition).inflate(0.15, 2.0, 0.15);
|
||||
List<net.minecraft.world.entity.Display.TextDisplay> list = level.getEntitiesOfClass(
|
||||
net.minecraft.world.entity.Display.TextDisplay.class, aabb,
|
||||
e -> e.getTags().contains(BUBBLE_TAG));
|
||||
return list.isEmpty() ? null : list.get(0);
|
||||
}
|
||||
|
||||
/** 销毁气泡(方块拆除/条件不满足时)。 */
|
||||
private void discardBubble() {
|
||||
if (bubble != null && bubble.isAlive()) {
|
||||
bubble.discard();
|
||||
} else {
|
||||
net.minecraft.world.entity.Display.TextDisplay found = findBubble();
|
||||
if (found != null) {
|
||||
found.discard();
|
||||
}
|
||||
}
|
||||
bubble = null;
|
||||
}
|
||||
|
||||
/** 风险数据 → 气泡多行文本(2 行:注魔风险/不稳定度;不显示基础+祭坛细分,细分在聊天栏)。 */
|
||||
private static Component buildBubbleText(RiskData risk) {
|
||||
// 内边距必须用不间断空格(\u00A0):普通空格在行尾会被字体布局裁剪,
|
||||
// 导致背景只包住左侧、右侧贴边。NBSP 有真实字形,两侧都保留。
|
||||
String pad = "\u00A0\u00A0"; // 左右内边距(NBSP)
|
||||
String tierWord = tierWord(risk.tier());
|
||||
|
||||
Component line1 = Component.literal(pad + "注魔风险: " + tierWord + pad)
|
||||
.withStyle(style -> style.withColor(tierColor(risk.tier())));
|
||||
Component line2 = Component.literal(pad + "不稳定度: " + risk.instability() + pad)
|
||||
.withStyle(style -> style.withColor(0xFFFFFFFF));
|
||||
|
||||
// 上下各留一个空行(垂直内边距)
|
||||
return Component.literal("\n")
|
||||
.append(line1).append("\n")
|
||||
.append(line2).append("\n");
|
||||
}
|
||||
|
||||
/** 5 档文字(无星星)。 */
|
||||
private static String tierWord(int tier) {
|
||||
return switch (tier) {
|
||||
case 1 -> "极低";
|
||||
case 2 -> "低";
|
||||
case 3 -> "中";
|
||||
case 4 -> "高";
|
||||
case 5 -> "极高";
|
||||
default -> "?";
|
||||
};
|
||||
}
|
||||
|
||||
/** 5 档描述(神秘时代风)。 */
|
||||
private static String tierDesc(int tier) {
|
||||
return switch (tier) {
|
||||
case 1 -> "灵光如镜,仪式安然";
|
||||
case 2 -> "灵光微澜,无碍仪式";
|
||||
case 3 -> "符文低鸣,灵光流转不宁";
|
||||
case 4 -> "裂隙于虚空中睁开,注视着祭坛";
|
||||
case 5 -> "咒波翻涌,裂隙将吞没一切";
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
|
||||
/** 档位颜色:1 绿 → 5 红。 */
|
||||
private static int tierColor(int tier) {
|
||||
return switch (tier) {
|
||||
case 1 -> 0xFF55FF55;
|
||||
case 2 -> 0xFFAAFF55;
|
||||
case 3 -> 0xFFFFFF55;
|
||||
case 4 -> 0xFFFFAA55;
|
||||
default -> 0xFFFF5555;
|
||||
};
|
||||
display.update(shouldShow, shouldShow ? InfusionMonitorText.bubble(cachedRisk) : Component.empty());
|
||||
}
|
||||
|
||||
/** 放入魔导手册(方块右键拦截后调用,防止书自身 use 打开界面)。 */
|
||||
@@ -585,10 +420,8 @@ public class TileInfusionMonitor extends ThETileBase implements IInWorldGridNode
|
||||
public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider reg) {
|
||||
super.handleUpdateTag(tag, reg);
|
||||
loadRiskFromTag(tag);
|
||||
if (tag.contains("Book")) {
|
||||
inventory.setItem(BOOK_SLOT, ItemStack.parseOptional(reg, tag.getCompound("Book")));
|
||||
}
|
||||
}
|
||||
|
||||
private void saveRiskToTag(CompoundTag tag) {
|
||||
tag.putBoolean("RiskFound", cachedRisk.found());
|
||||
|
||||
@@ -12,6 +12,7 @@ import net.neoforged.neoforge.registries.DeferredBlock;
|
||||
import net.neoforged.neoforge.registries.DeferredRegister;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.blocks.BrainOfProbabilityBlock;
|
||||
import thaumicenergistics.common.blocks.FumoBlock;
|
||||
import thaumicenergistics.common.blocks.BrainOfProbabilityTopBlock;
|
||||
import thaumicenergistics.common.blocks.OrientableEntityBlock;
|
||||
import thaumicenergistics.common.blocks.ThEBaseEntityBlock;
|
||||
@@ -351,6 +352,24 @@ public final class ModBlocks {
|
||||
}
|
||||
});
|
||||
|
||||
/** 玩偶通用:拿起方块到手(空手进主手,否则进背包),并移除方块。 */
|
||||
private static void pickUpFumo(Level level, BlockPos pos, Player player, Block block) {
|
||||
if (level.isClientSide) return;
|
||||
ItemStack item = new ItemStack(block.asItem());
|
||||
if (player.getMainHandItem().isEmpty()) {
|
||||
player.setItemInHand(InteractionHand.MAIN_HAND, item);
|
||||
} else if (!player.getInventory().add(item)) {
|
||||
Containers.dropItemStack(level, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, item);
|
||||
}
|
||||
level.removeBlock(pos, false);
|
||||
}
|
||||
|
||||
// Preserve the registered IDs; both dolls now share Alkusure86's two-state interaction.
|
||||
public static final DeferredBlock<Block> MAIQILIN_FUMO = REGISTRY.register("maiqilinfumo",
|
||||
() -> new FumoBlock(PD));
|
||||
public static final DeferredBlock<Block> BEIWUCN_FUMO = REGISTRY.register("beiwucnfumo",
|
||||
() -> new FumoBlock(PD));
|
||||
|
||||
// ==================== 源质无线接收器 ====================
|
||||
|
||||
/** 是否已连接源质供应器(off/on 模型切换)。 */
|
||||
|
||||
@@ -18,9 +18,21 @@ public final class ModCreativeTab {
|
||||
.displayItems((params, output) -> {
|
||||
output.accept(ModItems.ESSENTIA_CELL_1K.get()); output.accept(ModItems.ESSENTIA_CELL_4K.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_16K.get()); output.accept(ModItems.ESSENTIA_CELL_64K.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_256K.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_1M.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_4M.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_16M.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_64M.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_256M.get());
|
||||
output.accept(ModItems.ESSENTIA_CELL_CREATIVE.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_1K.get()); output.accept(ModItems.STORAGE_COMPONENT_4K.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_16K.get()); output.accept(ModItems.STORAGE_COMPONENT_64K.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_256K.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_1M.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_4M.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_16M.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_64M.get());
|
||||
output.accept(ModItems.STORAGE_COMPONENT_256M.get());
|
||||
output.accept(ModItems.STORAGE_CASING.get());
|
||||
output.accept(ModItems.COALESCENCE_CORE.get()); output.accept(ModItems.DIFFUSION_CORE.get());
|
||||
output.accept(ModItems.KNOWLEDGE_CORE.get());
|
||||
@@ -38,7 +50,7 @@ public final class ModCreativeTab {
|
||||
output.accept(ModItems.ESSENTIA_UPGRADE_CARD.get());
|
||||
output.accept(ModItems.PROBABILITY_ACCELERATOR_CARD.get());
|
||||
output.accept(ModItems.BRAIN_OF_PROBABILITY_ITEM.get());
|
||||
// 玩偶不进创造物品栏:需 /give @p thaumicenergistics:alkusure86fumo 手动获取
|
||||
// 玩偶不进创造物品栏:使用切石机切割任意颜色羊毛获取
|
||||
// output.accept(ModItems.ALKUSURE86_FUMO_ITEM.get());
|
||||
|
||||
// 源质虚拟物品不再在创造标签页中注册(避免玩家拿到物品栏)
|
||||
|
||||
@@ -2,9 +2,11 @@ package thaumicenergistics.init;
|
||||
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.neoforged.fml.ModList;
|
||||
import net.neoforged.neoforge.registries.DeferredItem;
|
||||
import net.neoforged.neoforge.registries.DeferredRegister;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.integration.ae2wt.AE2WTCompat;
|
||||
import thaumicenergistics.common.items.*;
|
||||
import appeng.core.AEConfig;
|
||||
import thaumicenergistics.common.items.WirelessConnectorItem;
|
||||
@@ -17,11 +19,23 @@ public final class ModItems {
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_4K = REGISTRY.registerItem("essentia_cell_4k", ItemEssentiaCell::create4k);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_16K = REGISTRY.registerItem("essentia_cell_16k", ItemEssentiaCell::create16k);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_64K = REGISTRY.registerItem("essentia_cell_64k", ItemEssentiaCell::create64k);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_256K = REGISTRY.registerItem("essentia_cell_256k", ItemEssentiaCell::create256k);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_1M = REGISTRY.registerItem("essentia_cell_1m", ItemEssentiaCell::create1m);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_4M = REGISTRY.registerItem("essentia_cell_4m", ItemEssentiaCell::create4m);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_16M = REGISTRY.registerItem("essentia_cell_16m", ItemEssentiaCell::create16m);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_64M = REGISTRY.registerItem("essentia_cell_64m", ItemEssentiaCell::create64m);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_256M = REGISTRY.registerItem("essentia_cell_256m", ItemEssentiaCell::create256m);
|
||||
public static final DeferredItem<ItemEssentiaCell> ESSENTIA_CELL_CREATIVE = REGISTRY.registerItem("essentia_cell_creative", ItemEssentiaCell::createCreative);
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_1K = REGISTRY.registerSimpleItem("storage_component_1k");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_4K = REGISTRY.registerSimpleItem("storage_component_4k");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_16K = REGISTRY.registerSimpleItem("storage_component_16k");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_64K = REGISTRY.registerSimpleItem("storage_component_64k");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_256K = REGISTRY.registerSimpleItem("storage_component_256k");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_1M = REGISTRY.registerSimpleItem("storage_component_1m");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_4M = REGISTRY.registerSimpleItem("storage_component_4m");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_16M = REGISTRY.registerSimpleItem("storage_component_16m");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_64M = REGISTRY.registerSimpleItem("storage_component_64m");
|
||||
public static final DeferredItem<Item> STORAGE_COMPONENT_256M = REGISTRY.registerSimpleItem("storage_component_256m");
|
||||
public static final DeferredItem<Item> STORAGE_CASING = REGISTRY.registerSimpleItem("storage_casing");
|
||||
public static final DeferredItem<Item> COALESCENCE_CORE = REGISTRY.registerSimpleItem("coalescence_core");
|
||||
public static final DeferredItem<Item> DIFFUSION_CORE = REGISTRY.registerSimpleItem("diffusion_core");
|
||||
@@ -29,9 +43,16 @@ public final class ModItems {
|
||||
() -> new Item(new Item.Properties().stacksTo(1)));
|
||||
public static final DeferredItem<ItemFocusAEWrench> FOCUS_AEWRENCH = REGISTRY.register("focus_aewrench",
|
||||
() -> new ItemFocusAEWrench());
|
||||
public static final DeferredItem<WirelessArcaneCraftingTerminalItem> WIRELESS_ARCANE_CRAFTING_TERMINAL =
|
||||
/**
|
||||
* 无线奥术合成终端:注册 ID 恒定,按运行环境选实现——ae2wtlib 完整模组存在时用
|
||||
* {@code ItemWT} 体系实现(纳入通用终端合并/模式切换),否则用独立实现。
|
||||
* 两实现参数一致(AEConfig 无线终端电池 + stacksTo(1))。
|
||||
*/
|
||||
public static final DeferredItem<Item> WIRELESS_ARCANE_CRAFTING_TERMINAL =
|
||||
REGISTRY.register("wireless_arcane_crafting_terminal",
|
||||
() -> new WirelessArcaneCraftingTerminalItem(
|
||||
() -> ModList.get().isLoaded("ae2wtlib")
|
||||
? AE2WTCompat.createTerminalItem()
|
||||
: new WirelessArcaneCraftingTerminalItem(
|
||||
AEConfig.instance().getWirelessTerminalBattery(),
|
||||
new Item.Properties().stacksTo(1)));
|
||||
public static final DeferredItem<VisConnectorCardItem> VIS_CONNECTOR_CARD = REGISTRY.register(
|
||||
@@ -61,6 +82,8 @@ public final class ModItems {
|
||||
public static final DeferredItem<BlockItem> DISTILLATION_ENCODER_ITEM = REGISTRY.registerSimpleBlockItem(ModBlocks.DISTILLATION_ENCODER);
|
||||
public static final DeferredItem<BlockItem> INFUSION_MONITOR_ITEM = REGISTRY.registerSimpleBlockItem(ModBlocks.INFUSION_MONITOR);
|
||||
public static final DeferredItem<BlockItem> ALKUSURE86_FUMO_ITEM = REGISTRY.registerSimpleBlockItem(ModBlocks.ALKUSURE86_FUMO);
|
||||
public static final DeferredItem<BlockItem> MAIQILIN_FUMO_ITEM = REGISTRY.registerSimpleBlockItem(ModBlocks.MAIQILIN_FUMO);
|
||||
public static final DeferredItem<BlockItem> BEIWUCN_FUMO_ITEM = REGISTRY.registerSimpleBlockItem(ModBlocks.BEIWUCN_FUMO);
|
||||
public static final DeferredItem<BlockItem> ESSENTIA_PROVIDER_CONNECTION_ITEM =
|
||||
REGISTRY.registerSimpleBlockItem(ModBlocks.ESSENTIA_PROVIDER_CONNECTION);
|
||||
|
||||
|
||||
@@ -34,11 +34,23 @@ public final class ModMenuTypes {
|
||||
REGISTRY.register("arcane_crafting_terminal", () ->
|
||||
MenuTypeBuilder.create(ContainerArcaneCraftingTerminal::new, ITerminalHost.class)
|
||||
.buildUnregistered(ThaumicEnergistics.id("arcane_crafting_terminal")));
|
||||
/** 无线奥术合成终端菜单:复用有线菜单类,仅换 host 类型(手持无线终端,同 wireless_essentia_terminal 先例)。 */
|
||||
/**
|
||||
* 无线奥术合成终端菜单:复用有线菜单类,仅换 host 类型(手持无线终端,同 wireless_essentia_terminal 先例)。
|
||||
* <p>
|
||||
* COMPAT-PLAN:菜单类型对象提前构造(AE2WT 官方 WCTMenu.TYPE 同范式——类加载期
|
||||
* buildUnregistered),WTDefinition 与注册表引用同一实例,避免通用终端注册回调
|
||||
* (RegisterEvent(ITEM) 时 MENU 注册表尚未注册)拿到 null。
|
||||
* 工厂显式传入无线菜单类型:客户端按 menu.getType() 选屏,若沿用三参构造会落回
|
||||
* 有线类型,打开无通用终端切换按钮的有线屏幕。
|
||||
*/
|
||||
public static final MenuType<ContainerArcaneCraftingTerminal> WIRELESS_ARCANE_CRAFTING_TERMINAL_TYPE =
|
||||
MenuTypeBuilder.create(
|
||||
(id, inventory, host) -> new ContainerArcaneCraftingTerminal(
|
||||
ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL.get(), id, inventory, host, true),
|
||||
IPortableTerminal.class)
|
||||
.buildUnregistered(ThaumicEnergistics.id("wireless_arcane_crafting_terminal"));
|
||||
public static final Supplier<MenuType<ContainerArcaneCraftingTerminal>> WIRELESS_ARCANE_CRAFTING_TERMINAL =
|
||||
REGISTRY.register("wireless_arcane_crafting_terminal", () ->
|
||||
MenuTypeBuilder.create(ContainerArcaneCraftingTerminal::new, IPortableTerminal.class)
|
||||
.buildUnregistered(ThaumicEnergistics.id("wireless_arcane_crafting_terminal")));
|
||||
REGISTRY.register("wireless_arcane_crafting_terminal", () -> WIRELESS_ARCANE_CRAFTING_TERMINAL_TYPE);
|
||||
|
||||
public static final Supplier<MenuType<ContainerEssentiaLevelEmitter>> ESSENTIA_LEVEL_EMITTER =
|
||||
REGISTRY.register("essentia_level_emitter", () ->
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package thaumicenergistics.init;
|
||||
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||
import net.neoforged.neoforge.registries.DeferredRegister;
|
||||
import java.util.function.Supplier;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.features.SafeTerminalMergeRecipe;
|
||||
|
||||
public final class ModRecipeSerializers {
|
||||
public static final DeferredRegister<RecipeSerializer<?>> REGISTRY =
|
||||
DeferredRegister.create(Registries.RECIPE_SERIALIZER, ThaumicEnergistics.MODID);
|
||||
public static final Supplier<RecipeSerializer<SafeTerminalMergeRecipe>> SAFE_TERMINAL_MERGE =
|
||||
REGISTRY.register("safe_terminal_merge", SafeTerminalMergeRecipe.Serializer::new);
|
||||
|
||||
private ModRecipeSerializers() {
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,16 @@ import mezz.jei.api.JeiPlugin;
|
||||
import mezz.jei.api.registration.IGuiHandlerRegistration;
|
||||
import mezz.jei.api.registration.IModIngredientRegistration;
|
||||
import mezz.jei.api.registration.IRecipeTransferRegistration;
|
||||
import mezz.jei.api.registration.IRecipeRegistration;
|
||||
import mezz.jei.api.registration.IVanillaCategoryExtensionRegistration;
|
||||
import mezz.jei.api.recipe.category.extensions.vanilla.crafting.ICraftingCategoryExtension;
|
||||
import mezz.jei.api.gui.builder.IRecipeLayoutBuilder;
|
||||
import mezz.jei.api.gui.ingredient.ICraftingGridHelper;
|
||||
import mezz.jei.api.recipe.IFocusGroup;
|
||||
import net.minecraft.world.item.crafting.RecipeHolder;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import thaumicenergistics.common.features.SafeTerminalMergeRecipe;
|
||||
|
||||
import static mezz.jei.api.constants.RecipeTypes.CRAFTING;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
@@ -63,6 +73,30 @@ public class ThEJeiPlugin implements IModPlugin {
|
||||
return ThaumicEnergistics.id("jei");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerVanillaCategoryExtensions(IVanillaCategoryExtensionRegistration registration) {
|
||||
registration.getCraftingCategory().addExtension(SafeTerminalMergeRecipe.class,
|
||||
new ICraftingCategoryExtension<SafeTerminalMergeRecipe>() {
|
||||
@Override
|
||||
public void setRecipe(RecipeHolder<SafeTerminalMergeRecipe> holder, IRecipeLayoutBuilder builder,
|
||||
ICraftingGridHelper grid, IFocusGroup focuses) {
|
||||
grid.createAndSetIngredients(builder, holder.value().getIngredients(), 0, 0);
|
||||
grid.createAndSetOutputs(builder, List.of(holder.value().displayResult()));
|
||||
builder.setShapeless();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerRecipes(IRecipeRegistration registration) {
|
||||
var level = Minecraft.getInstance().level;
|
||||
if (level == null) return;
|
||||
// CustomRecipe 为特殊配方,显式添加已由条件加载的真实配方,避免依赖普通配方收集器。
|
||||
var recipes = level.getRecipeManager().getAllRecipesFor(RecipeType.CRAFTING).stream()
|
||||
.filter(holder -> holder.value() instanceof SafeTerminalMergeRecipe).toList();
|
||||
registration.addRecipes(CRAFTING, recipes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerIngredients(IModIngredientRegistration registration) {
|
||||
List<AspectIngredient> ingredients = new ArrayList<>();
|
||||
@@ -84,13 +118,8 @@ public class ThEJeiPlugin implements IModPlugin {
|
||||
|
||||
@Override
|
||||
public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) {
|
||||
// 注册 IRecipeTransferInfo 让 JEI 显示 "+" 按钮
|
||||
registration.addRecipeTransferHandler(new ArcaneCraftingTransferInfo());
|
||||
registration.addRecipeTransferHandler(new ArcaneRecipeTransferInfo());
|
||||
// 无线奥术合成终端:MenuType 不同,需单独注册槽位映射(转移 handler 按容器类共用)
|
||||
registration.addRecipeTransferHandler(new WirelessArcaneCraftingTransferInfo());
|
||||
registration.addRecipeTransferHandler(new ThEWirelessArcaneCraftingTransferInfo());
|
||||
// 注册 IRecipeTransferHandler 让点击 "+" 时走 ME 网络
|
||||
// One network-aware handler per container class/category covers both menu types.
|
||||
// Separate basic slot mappings would overwrite each other in JEI's registration table.
|
||||
registration.addRecipeTransferHandler(new ThEUseCraftingRecipeTransfer(registration.getTransferHelper()), CRAFTING);
|
||||
registration.addRecipeTransferHandler(new ThEUseArcaneRecipeTransfer(registration.getTransferHelper()), ThaumcraftJeiPlugin.ARCANE);
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import thaumcraft.integration.jei.JeiArcaneRecipe;
|
||||
import thaumcraft.integration.jei.ThaumcraftJeiPlugin;
|
||||
import thaumicenergistics.common.container.ContainerArcaneCraftingTerminal;
|
||||
import thaumicenergistics.init.ModMenuTypes;
|
||||
|
||||
import static appeng.integration.modules.itemlists.TransferHelper.BLUE_PLUS_BUTTON_COLOR;
|
||||
import static appeng.integration.modules.itemlists.TransferHelper.BLUE_SLOT_HIGHLIGHT_COLOR;
|
||||
@@ -55,7 +54,9 @@ public class ThEUseArcaneRecipeTransfer
|
||||
|
||||
@Override
|
||||
public Optional<MenuType<ContainerArcaneCraftingTerminal>> getMenuType() {
|
||||
return Optional.of(ModMenuTypes.ARCANE_CRAFTING_TERMINAL.get());
|
||||
// JEI stores one handler per container class and recipe category, not per menu type.
|
||||
// Both wired and wireless arcane terminals use this exact container class.
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -30,7 +30,6 @@ import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import thaumicenergistics.ThaumicEnergistics;
|
||||
import thaumicenergistics.common.container.ContainerArcaneCraftingTerminal;
|
||||
import thaumicenergistics.init.ModMenuTypes;
|
||||
|
||||
import static appeng.integration.modules.itemlists.TransferHelper.BLUE_PLUS_BUTTON_COLOR;
|
||||
import static appeng.integration.modules.itemlists.TransferHelper.BLUE_SLOT_HIGHLIGHT_COLOR;
|
||||
@@ -66,7 +65,9 @@ public class ThEUseCraftingRecipeTransfer
|
||||
|
||||
@Override
|
||||
public Optional<MenuType<ContainerArcaneCraftingTerminal>> getMenuType() {
|
||||
return Optional.of(ModMenuTypes.ARCANE_CRAFTING_TERMINAL.get());
|
||||
// JEI stores one handler per container class and recipe category, not per menu type.
|
||||
// Both wired and wireless arcane terminals use this exact container class.
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ public class ThEWirelessArcaneCraftingTransferInfo
|
||||
|
||||
@Override
|
||||
public Optional<MenuType<ContainerArcaneCraftingTerminal>> getMenuType() {
|
||||
return Optional.of(ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL.get());
|
||||
return Optional.of(ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL_TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ public class WirelessArcaneCraftingTransferInfo
|
||||
|
||||
@Override
|
||||
public Optional<MenuType<ContainerArcaneCraftingTerminal>> getMenuType() {
|
||||
return Optional.of(ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL.get());
|
||||
return Optional.of(ModMenuTypes.WIRELESS_ARCANE_CRAFTING_TERMINAL_TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package thaumicenergistics.mixins;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
|
||||
import net.neoforged.fml.loading.LoadingModList;
|
||||
|
||||
/** 在目标类加载前排除缺席的可选模组,不依赖尚未创建的 ModList。 */
|
||||
public final class ThEOptionalMixinPlugin implements IMixinConfigPlugin {
|
||||
@Override public void onLoad(String mixinPackage) { }
|
||||
@Override public String getRefMapperConfig() { return null; }
|
||||
@Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
|
||||
if (mixinClassName.contains(".compat.aae.")) {
|
||||
return loaded("advanced_ae") && (mixinClassName.endsWith("Essentia") || !loaded("appflux"));
|
||||
}
|
||||
if (mixinClassName.contains(".compat.ae2lt.")) return loaded("ae2lt");
|
||||
if (!mixinClassName.contains(".eap.")) return true;
|
||||
return loaded("extendedae_plus");
|
||||
}
|
||||
|
||||
private static boolean loaded(String id) {
|
||||
var mods = LoadingModList.get();
|
||||
return mods != null && mods.getMods().stream()
|
||||
.anyMatch(mod -> mod.getModId().equals(id));
|
||||
}
|
||||
@Override public void acceptTargets(Set<String> mine, Set<String> others) { }
|
||||
@Override public List<String> getMixins() { return null; }
|
||||
@Override public void preApply(String target, ClassNode node, String mixin, IMixinInfo info) { }
|
||||
@Override public void postApply(String target, ClassNode node, String mixin, IMixinInfo info) { }
|
||||
}
|
||||
@@ -29,40 +29,11 @@ import appeng.util.ConfigInventory;
|
||||
|
||||
import thaumicenergistics.common.essentia.capability.EssentiaTransfer;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaConversionHelper;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/**
|
||||
* 让 AE2 <b>原版输出总线</b>在插入「源质访问卡」后额外具备「ME 网络 → 相邻容器」的源质搬运能力
|
||||
* (T-M1-007-⑦a)。
|
||||
* <p>
|
||||
* <b>additive</b>:只在 {@code ExportBusPart.doBusWork} 末尾({@code @At("TAIL")})追加源质搬运,
|
||||
* 原版物品/流体导出逻辑一行不改。装卡后两种能力<b>并存</b>;不装卡则完全不干预。
|
||||
* <p>
|
||||
* <b>要导出哪些要素(卡路径独有)</b>:T-M1-011 起,源质过滤改由宿主<b>原生 config 槽</b>承载
|
||||
* (物品/流体/源质共存一格;由 {@code MixinIOBusPart} 的 {@code @ModifyArg} 使 config 接受源质键):
|
||||
* <ul>
|
||||
* <li><b>配置了源质 = 只搬选中的要素</b>——遍历配置的源质键轮询(round-robin),逐个尝试,搬成功即停;</li>
|
||||
* <li><b>未配置源质 = 不搬</b>(R-2 口径)——必须显式配置源质才导出;对齐 AE2 原版输出总线
|
||||
* 「空配置不导出」语义,避免插卡未配置就把网络内全部源质倒向相邻容器。</li>
|
||||
* </ul>
|
||||
* 轮询游标跨 tick 保留(不持久化),避免每次只搬列表首项造成饥饿。
|
||||
* <p>
|
||||
* 速率({@code 8 × getOperationsPerTick()})与能量口径沿用 T-M1 批次对齐的原 ThE 导出总线(T-M2-REMOVE 已删):
|
||||
* 导出侧<b>不做</b>能量实扣,只把折算值记进 {@link #thE$storedEnergy}。
|
||||
* <p>
|
||||
* 已知既有瑕疵被照搬:原实现记录的是 {@code injected * (int) AE_PER_ESSENTIA},
|
||||
* {@code injected * (int) AE_PER_ESSENTIA},而 {@code AE_PER_ESSENTIA = 0.3},{@code (int) 0.3 == 0},
|
||||
* 故该字段恒为 0。本类照搬该表达式以保持行为等价,并原样保留该既有瑕疵(不在本任务内修正)。
|
||||
* <p>
|
||||
* <b>T-M1-010 根因修正(去 @Shadow)</b>:{@code IOBusPart.source}(:84)与
|
||||
* {@code IOBusPart.getOperationsPerTick()}(:194-202)均声明在<b>父类</b>,{@code ExportBusPart} 未覆写;
|
||||
* Mixin {@code @Shadow} 只解析<b>目标类自身</b>声明的成员、不沿父类查找 → 原实现整类被拒绝应用
|
||||
* ({@code InvalidMixinException: @Shadow method getOperationsPerTick ... was not located})。
|
||||
* 改为经父类公开接口等价重建(见 {@code thE$source()} / {@code thE$operationsPerTick()})。
|
||||
* <p>
|
||||
* <b>T-M1-011</b>:过滤来源由退役的鸭子接口 {@code EssentiaFilterHolder}(NBT)改为宿主原生 config;
|
||||
* config 经公开 getter {@code IOBusPart.getConfig()} 读取(字段声明在父类,禁 {@code @Shadow})。
|
||||
* 原版导出总线插入源质访问卡后,追加显式配置要素的轮询输出。
|
||||
* 模拟不扣料;实际转移由统一服务结算,退回失败的余量持久化并优先重试。
|
||||
*/
|
||||
@Mixin(ExportBusPart.class)
|
||||
public abstract class MixinExportBusPart {
|
||||
@@ -103,10 +74,6 @@ public abstract class MixinExportBusPart {
|
||||
@Unique
|
||||
private int thE$roundRobinIndex = 0;
|
||||
|
||||
/** 已折算的能量记账(照搬三总线:只记不扣)。无 GUI 展示位,不持久化。 */
|
||||
@Unique
|
||||
private long thE$storedEnergy = 0;
|
||||
|
||||
@Inject(method = "doBusWork", at = @At("TAIL"), cancellable = true)
|
||||
private void thE$essentiaExport(IGrid grid, CallbackInfoReturnable<Boolean> cir) {
|
||||
if (!thE$hasEssentiaCard()) {
|
||||
@@ -131,6 +98,19 @@ public abstract class MixinExportBusPart {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((Object) this instanceof thaumicenergistics.common.essentia.capability.EssentiaTransferBuffer buffer
|
||||
&& !buffer.thE$getTransferBuffer().isEmpty()) {
|
||||
var pending = buffer.thE$getTransferBuffer();
|
||||
long delivered = thaumicenergistics.common.essentia.capability.EssentiaEnergy.transfer(
|
||||
grid, pending.amount(), allowed -> EssentiaTransfer.insertOwned(
|
||||
AEssentiaKey.of(pending.aspectId()), allowed, adjacentBE, side.getOpposite()));
|
||||
buffer.thE$setTransferBuffer(delivered == pending.amount()
|
||||
? thaumicenergistics.api.storage.AspectStack.EMPTY
|
||||
: new thaumicenergistics.api.storage.AspectStack(pending.aspectId(), pending.amount() - delivered));
|
||||
if (delivered > 0) cir.setReturnValue(true);
|
||||
return;
|
||||
}
|
||||
|
||||
int rate = 8 * Math.max(1, thE$operationsPerTick());
|
||||
if (rate <= 0) {
|
||||
return;
|
||||
@@ -146,16 +126,27 @@ public abstract class MixinExportBusPart {
|
||||
for (int i = 0; i < count; i++) {
|
||||
int index = (this.thE$roundRobinIndex + i) % count;
|
||||
AEssentiaKey key = candidates.get(index);
|
||||
long injected = EssentiaTransfer.push(
|
||||
var transfer = EssentiaTransfer.push(
|
||||
grid, thE$source(), key, rate, adjacentBE, side.getOpposite());
|
||||
if (!transfer.leftover().isEmpty()
|
||||
&& (Object) this instanceof thaumicenergistics.common.essentia.capability.EssentiaTransferBuffer buffer) {
|
||||
buffer.thE$setTransferBuffer(transfer.leftover());
|
||||
}
|
||||
long injected = transfer.moved();
|
||||
if (injected > 0) {
|
||||
this.thE$roundRobinIndex = (index + 1) % count;
|
||||
this.thE$storedEnergy = injected * (int) EssentiaConversionHelper.AE_PER_ESSENTIA;
|
||||
if (!Boolean.TRUE.equals(cir.getReturnValue())) {
|
||||
cir.setReturnValue(true); // 见 MixinImportBusPart#thE$reportWork 的同类说明
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (transfer.leftover().isEmpty()
|
||||
&& thaumicenergistics.common.essentia.capability.ExportBusEssentiaTransport.reserveForConsumer(
|
||||
(ExportBusPart) (Object) this, key, rate, adjacentBE, side.getOpposite(), grid, thE$source())) {
|
||||
this.thE$roundRobinIndex = (index + 1) % count;
|
||||
cir.setReturnValue(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@ package thaumicenergistics.mixins.ae2.bus;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Unique;
|
||||
@@ -17,43 +19,45 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
import appeng.api.stacks.AEKeyType;
|
||||
import appeng.parts.AEBasePart;
|
||||
import appeng.parts.automation.IOBusPart;
|
||||
import appeng.parts.automation.UpgradeablePart;
|
||||
import appeng.api.parts.IPartItem;
|
||||
import appeng.api.stacks.GenericStack;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
|
||||
import thaumicenergistics.api.storage.AspectStack;
|
||||
import thaumicenergistics.common.essentia.capability.EssentiaTransferBuffer;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKeyType;
|
||||
|
||||
/**
|
||||
* 给 AE2 <b>原版</b>输入/输出总线提供两件事(导入/导出总线共用父类 {@code IOBusPart},一处覆盖两条总线):
|
||||
* <ul>
|
||||
* <li><b>源质键类型支持</b>(T-M1-011,P2):{@code @ModifyArg} 把宿主 config 的键类型集合扩入源质键类型,
|
||||
* 使 IO 总线的<b>原生过滤槽</b>可容纳源质键(物品/流体/源质共存一格),JEI 拖拽由此天然可用;</li>
|
||||
* <li><b>抽取缓冲</b>(T-M1-007-⑦a):在父类 {@code readFromNBT}/{@code writeToNBT} 末尾追加缓冲 NBT 键
|
||||
* ({@link EssentiaTransferBuffer#NBT_KEY_ASPECT}),承载「已从容器抽出但未入网」的残留源质。</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* <b>非纯 additive 说明</b>:{@code @ModifyArg} 修改的是原版构造器传给
|
||||
* {@code ConfigInventory.Builder.supportedTypes(Collection)} 的键类型集合——<b>只增不减</b>
|
||||
* (在原有集合上追加源质键类型;已含则原样返回)。这是 T-M1-011 唯一的非纯 additive 注入;
|
||||
* 其目标 {@code IOBusPart} 构造器是本模组三总线与两条原版总线的共同父类,故会同时惠及它们(可接受)。
|
||||
* <p>
|
||||
* <b>T-M1-011 退役项</b>:原「源质过滤 NBT」({@code ThEEssentiaFilterAspects})与鸭子接口
|
||||
* {@code EssentiaFilterHolder} 已随本任务删除——过滤数据改由宿主<b>原生 config inventory</b> 持久化,
|
||||
* 本节不再承载过滤,只保留抽取缓冲。
|
||||
* <p>
|
||||
* 抽取缓冲必须落在 {@code IOBusPart} 层(而非子类的 Mixin):{@code ImportBusPart} /
|
||||
* {@code ExportBusPart} 都不覆写 {@code readFromNBT}/{@code writeToNBT},若在子类 Mixin 里注入会解析到
|
||||
* 父类方法,从而在本模组三总线实例上执行(字段却只并入子类)→ 运行期 {@code NoSuchFieldError}。
|
||||
* <p>
|
||||
* 说明:本模组自有源质三总线亦继承 {@code IOBusPart},同样会获得该实现——但从不产生缓冲,
|
||||
* 键恒空(写入时会被移除),行为与改动前一致;且二者的键与本模组三总线自身的缓冲键
|
||||
* ({@code ThEBufferAspect}/{@code ThEBufferAmount})不同,互不干扰。
|
||||
* 在导入/导出总线共用父类追加源质过滤类型和持久化余量缓冲。
|
||||
* 余量由宿主拥有,拆除时保存为可回收物品;原版升级卡和 NBT 保持不变。
|
||||
*/
|
||||
@Mixin(IOBusPart.class)
|
||||
public abstract class MixinIOBusPart implements EssentiaTransferBuffer {
|
||||
public abstract class MixinIOBusPart extends UpgradeablePart implements EssentiaTransferBuffer {
|
||||
|
||||
protected MixinIOBusPart(IPartItem<?> partItem) {
|
||||
super(partItem);
|
||||
}
|
||||
|
||||
@Unique
|
||||
private AspectStack thE$transferBuffer = AspectStack.EMPTY;
|
||||
|
||||
// IOBusPart 未声明这两个方法,覆写并调用父类,避免向继承方法注入导致字段作用域错误。
|
||||
@Override
|
||||
public void addAdditionalDrops(List<ItemStack> drops, boolean wrenched) {
|
||||
super.addAdditionalDrops(drops, wrenched);
|
||||
if (!thE$transferBuffer.isEmpty()) {
|
||||
drops.add(GenericStack.wrapInItemStack(AEssentiaKey.of(thE$transferBuffer.aspectId()),
|
||||
thE$transferBuffer.amount()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearContent() {
|
||||
super.clearContent();
|
||||
thE$transferBuffer = AspectStack.EMPTY;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把源质键类型补进原版 IO 总线 config 的支持类型集合(只增不减)。
|
||||
* <p>
|
||||
|
||||
@@ -16,7 +16,6 @@ import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
import appeng.api.config.Actionable;
|
||||
import appeng.api.config.PowerMultiplier;
|
||||
import appeng.api.networking.IGrid;
|
||||
import appeng.api.networking.security.IActionHost;
|
||||
import appeng.api.networking.security.IActionSource;
|
||||
@@ -34,35 +33,11 @@ import thaumicenergistics.api.storage.AspectStack;
|
||||
import thaumicenergistics.common.essentia.capability.EssentiaTransfer;
|
||||
import thaumicenergistics.common.essentia.capability.EssentiaTransferBuffer;
|
||||
import thaumicenergistics.common.integration.appeng.AEssentiaKey;
|
||||
import thaumicenergistics.common.integration.tc.EssentiaConversionHelper;
|
||||
import thaumicenergistics.common.integration.tc.TCReflection;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/**
|
||||
* 让 AE2 <b>原版输入总线</b>在插入「源质访问卡」后额外具备「相邻容器 → ME 网络」的源质搬运能力
|
||||
* (T-M1-007-⑦a)。
|
||||
* <p>
|
||||
* <b>additive</b>:只在 {@code ImportBusPart.doBusWork} 末尾({@code @At("TAIL")})追加源质搬运,
|
||||
* 原版物品/流体搬运逻辑一行不改。装卡后两种能力<b>并存</b>(同一个 tick 内先由原版逻辑搬物品,
|
||||
* 末尾再搬源质);不装卡则完全不干预。
|
||||
* <p>
|
||||
* 挂载点说明:{@code IOBusPart.doBusWork} 是 {@code protected abstract}(无方法体,无法注入),
|
||||
* 其实现分别在 {@code ImportBusPart} / {@code ExportBusPart} 中,故需两处独立注入(本类负责导入侧)。
|
||||
* <p>
|
||||
* 行为沿用 T-M1 批次对齐的原 ThE 导入总线(T-M2-REMOVE 已删):抽取顺序、速率({@code 8 × getOperationsPerTick()})、
|
||||
* 残留缓冲重试、能量按实际入网量实扣({@code AE_PER_ESSENTIA})全部一致。
|
||||
* <p>
|
||||
* 卡路径特性:读取宿主<b>原生 config 槽</b>里配置的源质键(T-M1-011,物品/流体/源质共存一格)——
|
||||
* <b>未配置源质 = 全搬</b>(抽到什么都行),<b>配置了源质 = 只搬选中的要素</b>。
|
||||
* <p>
|
||||
* <b>T-M1-010 根因修正(去 @Shadow)</b>:{@code IOBusPart.source}(:84)与
|
||||
* {@code IOBusPart.getOperationsPerTick()}(:194-202)均声明在<b>父类</b>,{@code ImportBusPart} 未覆写;
|
||||
* Mixin {@code @Shadow} 只解析<b>目标类自身</b>声明的成员、不沿父类查找 → 原实现整类被拒绝应用
|
||||
* ({@code InvalidMixinException: @Shadow method getOperationsPerTick ... was not located})。
|
||||
* 改为经父类公开接口等价重建(见 {@code thE$source()} / {@code thE$operationsPerTick()})。
|
||||
* <p>
|
||||
* <b>T-M1-011</b>:过滤来源由退役的鸭子接口 {@code EssentiaFilterHolder}(NBT)改为宿主原生 config;
|
||||
* config 经公开 getter {@code IOBusPart.getConfig()} 读取(字段声明在父类,禁 {@code @Shadow})。
|
||||
* 原版导入总线插入源质访问卡后,追加相邻容器的源质导入。
|
||||
* 优先清空已持有的余量;外部抽取受过滤、容量和能量预算限制。
|
||||
*/
|
||||
@Mixin(ImportBusPart.class)
|
||||
public abstract class MixinImportBusPart {
|
||||
@@ -152,32 +127,13 @@ public abstract class MixinImportBusPart {
|
||||
|
||||
// 卡路径过滤(T-M1-011):宿主 config 配置了源质键 → 只搬选中的要素(配置外要素本轮跳过,留在容器里)
|
||||
List<AEssentiaKey> configured = thE$configuredEssentia();
|
||||
if (!configured.isEmpty()) {
|
||||
AspectStack offered = TCReflection.peekEssentia(adjacentBE, rate);
|
||||
if (offered == null || offered.isEmpty()) {
|
||||
thE$reportWork(worked, cir);
|
||||
return;
|
||||
}
|
||||
AEssentiaKey offeredKey = AEssentiaKey.of(offered.aspectId());
|
||||
if (offeredKey == null || !configured.contains(offeredKey)) {
|
||||
thE$reportWork(worked, cir);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 容器 → 网络(能力模块:窥视 → 模拟测容量 → 定向抽取 → 实插)
|
||||
EssentiaTransfer.Pull pull = EssentiaTransfer.pull(adjacentBE, grid, thE$source(), rate);
|
||||
EssentiaTransfer.Pull pull = EssentiaTransfer.pull(adjacentBE, grid, thE$source(), rate,
|
||||
side.getOpposite(), id -> configured.isEmpty() || configured.contains(AEssentiaKey.of(id)));
|
||||
|
||||
if (!pull.leftover().isEmpty()) {
|
||||
// 模拟与实插不一致 → 剩余留在缓冲里重试,绝不归还 / 丢弃
|
||||
buffer.thE$setTransferBuffer(pull.leftover());
|
||||
}
|
||||
if (pull.moved() > 0 || !pull.leftover().isEmpty()) {
|
||||
// 能量按实际入网量结算(与三总线一致:抽到但一分为入网时也为 0 消耗)
|
||||
grid.getEnergyService().extractAEPower(
|
||||
pull.moved() * EssentiaConversionHelper.AE_PER_ESSENTIA,
|
||||
Actionable.MODULATE, PowerMultiplier.CONFIG);
|
||||
}
|
||||
|
||||
thE$reportWork(worked || pull.moved() > 0, cir);
|
||||
}
|
||||
@@ -216,16 +172,13 @@ public abstract class MixinImportBusPart {
|
||||
buffer.thE$setTransferBuffer(AspectStack.EMPTY);
|
||||
return false;
|
||||
}
|
||||
long injected = grid.getStorageService().getInventory().insert(
|
||||
key, pending.amount(), Actionable.MODULATE, thE$source());
|
||||
long injected = thaumicenergistics.common.essentia.capability.EssentiaEnergy.transfer(grid, pending.amount(),
|
||||
allowed -> grid.getStorageService().getInventory().insert(key, allowed, Actionable.MODULATE, thE$source()));
|
||||
if (injected <= 0) {
|
||||
return false;
|
||||
}
|
||||
long left = pending.amount() - injected;
|
||||
buffer.thE$setTransferBuffer(left > 0 ? new AspectStack(pending.aspectId(), left) : AspectStack.EMPTY);
|
||||
grid.getEnergyService().extractAEPower(
|
||||
injected * EssentiaConversionHelper.AE_PER_ESSENTIA,
|
||||
Actionable.MODULATE, PowerMultiplier.CONFIG);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,30 +27,14 @@ import thaumicenergistics.common.essentia.capability.EssentiaContainerStorage;
|
||||
import thaumicenergistics.init.ModItems;
|
||||
|
||||
/**
|
||||
* 给 AE2 <b>原版</b>存储总线挂载源质支持(T-M1-007-⑦b):{@code mountInventories} TAIL 插卡后把相邻源质容器
|
||||
* 挂载为网络存储。纯 additive,不碰原版挂载存储 / 优先级等既有逻辑。存储总线不继承 {@code IOBusPart},
|
||||
* 故需独立一处注入。
|
||||
* <p>
|
||||
* <b>T-M1-011 退役项</b>:原「源质过滤 NBT」({@code ThEEssentiaFilterAspects})持久化与鸭子接口
|
||||
* {@code EssentiaFilterHolder} 已随本任务删除——本宿主的分区/过滤改由<b>原生 config inventory</b> 承载
|
||||
* ({@code StorageBusPart.getConfig()},AE2 自身以其构建 {@code IPartitionList} 施加到挂载句柄),
|
||||
* 本节不再承载任何过滤数据。
|
||||
* <p>
|
||||
* ⑦b 的两条要点:
|
||||
* <ul>
|
||||
* <li><b>追加不替换</b>:AE2 自己的 {@code handler}(items/fluids 视图)照旧挂载,本类只往
|
||||
* {@link IStorageMounts} 里<b>再</b>挂一个源质视图({@link EssentiaContainerStorage});</li>
|
||||
* <li><b>避让</b>:相邻方块自身已暴露 {@code AECapabilities.ME_STORAGE}(AE2 原版存储总线会直接挂它)
|
||||
* 时不再挂源质视图,避免同一个容器出现两套视图。</li>
|
||||
* </ul>
|
||||
* 挂载视图与优先级跟随总线自身({@link IPriorityHost#getPriority()});卡插拔时通过
|
||||
* {@code upgradesChanged} TAIL 触发一次重新挂载,使存储增删即时生效。
|
||||
* 插卡后追加相邻源质容器视图,经过总线访问模式和分区过滤。
|
||||
* 对已经提供 ME_STORAGE 的目标不重复挂载;卡片变化后请求重新挂载。
|
||||
*/
|
||||
@Mixin(StorageBusPart.class)
|
||||
public abstract class MixinStorageBusPart {
|
||||
|
||||
@Unique
|
||||
private EssentiaContainerStorage thE$containerStorage;
|
||||
private MEStorage thE$containerStorage;
|
||||
|
||||
// ===== T-M1-007-⑦b:插卡后追加源质容器挂载 =====
|
||||
|
||||
@@ -90,12 +74,15 @@ public abstract class MixinStorageBusPart {
|
||||
}
|
||||
|
||||
@Unique
|
||||
private EssentiaContainerStorage thE$getContainerStorage() {
|
||||
private MEStorage thE$getContainerStorage() {
|
||||
if (this.thE$containerStorage == null) {
|
||||
this.thE$containerStorage = new EssentiaContainerStorage(
|
||||
this.thE$containerStorage = new thaumicenergistics.common.storage.EssentiaStorageBusInventory(
|
||||
new EssentiaContainerStorage(
|
||||
this::thE$getAdjacentBlockEntity,
|
||||
// T-M2-REMOVE:本模组存储总线已删,描述名改挂 AE2 原版存储总线(宿主本体)
|
||||
AEParts.STORAGE_BUS.asItem().getDescription());
|
||||
AEParts.STORAGE_BUS.asItem().getDescription(),
|
||||
() -> ((AEBasePart) (Object) this).getSide().getOpposite()),
|
||||
() -> (StorageBusPart) (Object) this);
|
||||
}
|
||||
return this.thE$containerStorage;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user