From 06cb06a0c0ecfa41d5480518ab6ae7b431d9074c Mon Sep 17 00:00:00 2001 From: Keridos <2742845+Keridos@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:11:25 +0100 Subject: [PATCH] feat: Serial Port addon, computer control and CC: Tweaked support Ports the computer-control base from 1.21.1 (Serial Port addon, computer control, turret aim and fire API) and adds the CC: Tweaked peripheral turret_base, with the methods of the OpenComputers: Rebooted component and 1.12.2, through the shared BaseComputerCommands. CC: Tweaked is compile-only (never bundled), optional in the metadata, and runs in the dev runs and on the game test servers. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 3 + CLAUDE.md | 6 +- README.md | 2 + build.fabric.gradle.kts | 16 ++ build.neoforge.gradle.kts | 19 ++ docs/architecture.md | 22 +- docs/id-mapping.md | 2 +- .../client/tooltip/ModuleTooltip.java | 4 + src/gametest/CLAUDE.md | 1 + .../gametest/ComputerControlGameTests.java | 201 +++++++++++++++++ .../gametest/ComputerCraftGameTests.java | 122 +++++++++++ src/gametest/resources/fabric.mod.json | 4 +- .../java/omtteam/openmodularturrets/CLAUDE.md | 10 +- .../blockentity/TurretBaseBlockEntity.java | 14 ++ .../blockentity/base/BaseComputerTurrets.java | 51 +++++ .../blockentity/base/TurretBaseNbt.java | 4 +- .../blockentity/turret/RayWeapons.java | 42 +++- .../blockentity/turret/TurretBlockEntity.java | 111 +++++++++- .../computercraft/ServerPlayerNames.java | 65 ++++++ .../computercraft/TurretBasePeripheral.java | 206 ++++++++++++++++++ .../openmodularturrets/config/ConfigData.java | 2 +- .../datagen/OMTRecipeProvider.java | 10 +- .../entity/projectile/RocketProjectile.java | 6 +- .../platform/fabric/OMTFabric.java | 4 + .../computercraft/FabricComputerCraft.java | 24 ++ .../platform/neoforge/OMTNeoForge.java | 13 +- .../computercraft/NeoForgeComputerCraft.java | 25 +++ .../openmodularturrets/registry/ModItems.java | 3 +- .../resources/META-INF/neoforge.mods.toml | 8 + .../items/addon_serial_port.json | 6 + .../assets/openmodularturrets/lang/de_de.json | 4 + .../assets/openmodularturrets/lang/en_gb.json | 4 + .../assets/openmodularturrets/lang/en_us.json | 4 + .../assets/openmodularturrets/lang/pt_br.json | 4 + .../assets/openmodularturrets/lang/ru_ru.json | 4 + .../assets/openmodularturrets/lang/zh_cn.json | 4 + .../models/item/addon_serial_port.json | 6 + .../textures/item/addon_serial_port.png | Bin 0 -> 478 bytes src/main/resources/fabric.mod.json | 3 +- versions/1.21.11-fabric/gradle.properties | 3 + .../recipes/misc/addon_serial_port.json | 40 ++++ .../recipe/addon_serial_port.json | 25 +++ versions/1.21.11-neoforge/gradle.properties | 3 + 43 files changed, 1076 insertions(+), 34 deletions(-) create mode 100644 src/gametest/java/omtteam/openmodularturrets/gametest/ComputerControlGameTests.java create mode 100644 src/gametest/java/omtteam/openmodularturrets/gametest/ComputerCraftGameTests.java create mode 100644 src/main/java/omtteam/openmodularturrets/blockentity/base/BaseComputerTurrets.java create mode 100644 src/main/java/omtteam/openmodularturrets/compat/computercraft/ServerPlayerNames.java create mode 100644 src/main/java/omtteam/openmodularturrets/compat/computercraft/TurretBasePeripheral.java create mode 100644 src/main/java/omtteam/openmodularturrets/platform/fabric/computercraft/FabricComputerCraft.java create mode 100644 src/main/java/omtteam/openmodularturrets/platform/neoforge/computercraft/NeoForgeComputerCraft.java create mode 100644 src/main/resources/assets/openmodularturrets/items/addon_serial_port.json create mode 100644 src/main/resources/assets/openmodularturrets/models/item/addon_serial_port.json create mode 100644 src/main/resources/assets/openmodularturrets/textures/item/addon_serial_port.png create mode 100644 versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/advancement/recipes/misc/addon_serial_port.json create mode 100644 versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/recipe/addon_serial_port.json diff --git a/CHANGELOG.md b/CHANGELOG.md index f9f5da0c6..67b34d394 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ Before a release, `./gradlew releaseChangelog` turns *Unreleased* into the relea ### Added +- Serial Port addon, with the recipe from 1.12.2 (quartz and I/O buses): lets computers use turret bases of tiers 2–4 (tier 5 bases accept them without it) +- Computer control: `setComputerControl(true)` stops a base's turrets from targeting on their own, so a computer aims and fires them (`isComputerControl` tells whether it is on) +- CC: Tweaked support: turret bases are the peripheral `turret_base`, with the computer commands of the Serial Port addon. - Turrets on a base with a damage amp addon show a small red light on each corner of their base plate - Config sections `upgrades` and `addons` switch each upgrade and addon off: it loses its recipe and does nothing in a machine, which shows it with a red slot frame, a "no" symbol over the icon and a red tooltip line - Range falloff (#539): turrets deal full damage up to a share of their range (`optimalRange`), then less down to `falloffDamage` at the end of the range; configurable per turret, off for the grenade, rocket, railgun and effect turrets diff --git a/CLAUDE.md b/CLAUDE.md index d65e075c7..a7ad315e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,6 +35,8 @@ Core gameplay: Jar-in-jar it (approved). - **Jade** (optional integration, `compat/jade/` for the server half and `client/compat/jade/` for the tooltips, registered through the `jade` entrypoint on Fabric and `@WailaPlugin` on NeoForge). Compile-only (`modCompileOnly`, Modrinth maven), never bundled and never required at runtime. +- **CC: Tweaked** (`cc.tweaked`, from `maven.squiddev.cc`), on both nodes (approved by the user on 2026-11-27): compile-only against its `-api` jar, never bundled, an optional dependency in the loader metadata (`suggests` on Fabric, an optional dependency in `neoforge.mods.toml`); the full mod is in the dev runs (`modLocalRuntime` / `localRuntime`), on the game test servers and in `runenv`. + Gated on `cctweaked_version` in `versions//gradle.properties` (1.117.1, the only version for 1.21.11; its artifacts are named `fabric` and `forge` on that maven, the NeoForge jar is the `-forge` one); the code is loaded behind `isModLoaded("computercraft")`. - **NeoForge** 21.11.x, built with **ModDevGradle** (approved by the user; build-time only). On NeoForge, the Fabric-only APIs above are replaced by NeoForge's own (capabilities, events, payload registration); see §4 "Loaders". - **OpenModularCore** (the team's shared core, `../../OpenModularCore`, module `omt-core` from JitPack, approved by the user on 2026-11-16): the game rules (`omtteam.openmodularturrets.core`), the same on every Minecraft version; compile-only, its classes are bundled into the mod's jar (see "Core Game Logic Source"). @@ -231,7 +233,9 @@ The § numbers and headings of the moved sections are kept, so references such a - Every variant (base tier, ammo type, upgrade, addon) is an **individual registered block/item** with a lowercase snake_case ID. `docs/id-mapping.md` maps the 1.12.2 IDs to the current ones. -- OpenComputers / ComputerCraft integration is **out of scope for now** (ask before adding). +- Computers: the loader-free base is present: the commands in `core/computer` (`BaseComputerCommands`, a port of 1.12.2's, plus computer control), `TurretBaseBlockEntity.getTurret(face)`, `blockentity.base.BaseComputerTurrets`, `TurretBlockEntity.setYawPitch` / `setAutoFire` / `forceShot`, the Serial Port addon (`addon_serial_port`, 1.12.2 recipe and texture), `ComputerControlGameTests`. + **CC: Tweaked** is supported on both nodes (decided by the user, 2026-11-27): `compat/computercraft/TurretBasePeripheral` (one loader-free class, the peripheral `turret_base`, the same methods as the 1.12.2 callbacks) reuses `BaseComputerCommands`; only its registration is per loader (`platform//computercraft`); `ComputerCraftGameTests` tests it. + OpenComputers (1.21.1 only) is **not present** here (ask before adding). ### Designing APIs diff --git a/README.md b/README.md index a5c3b94a8..425a86af4 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ The other Minecraft versions have their own branches: - **Turret API for other mods:** add turrets with their own weapons, ammo, models and custom hit logic; see [docs/turret-api.md](docs/turret-api.md) - Uses **Team Reborn Energy** on Fabric, so it works with energy from other Fabric tech mods; the NeoForge build uses its energy capability (FE) instead - Optional **Jade** support for turret bases and turrets, on both loaders +- Optional **CC: Tweaked** support (both loaders): turret bases are the peripheral `turret_base`, with the same functions as 1.12.2's computer callbacks, with a Serial Port addon or on tier 5 +- **Computer control** base: turret bases with a Serial Port addon (or on tier 5) accept computer commands, and a computer can aim and fire the turrets itself ## Requirements diff --git a/build.fabric.gradle.kts b/build.fabric.gradle.kts index 0d2eada5a..25d358ec6 100644 --- a/build.fabric.gradle.kts +++ b/build.fabric.gradle.kts @@ -63,6 +63,14 @@ tasks.withType().configureEach { doFirst { clientResources.get().asFile.mkdirs() } } +// CC: Tweaked comes only from its own maven +repositories { + exclusiveContent { + forRepository { maven("https://maven.squiddev.cc") { name = "CC-Tweaked" } } + filter { includeGroup("cc.tweaked") } + } +} + dependencies { minecraft("com.mojang:minecraft:$minecraftVersion") mappings(loom.officialMojangMappings()) @@ -79,6 +87,14 @@ dependencies { // Jade tooltips (optional, not bundled: the mod only registers the plugin when Jade is installed) modCompileOnly("maven.modrinth:jade:${property("jade_version")}") + // CC: Tweaked (optional, not bundled: the peripheral in compat/computercraft is only registered when it is + // installed): its API compile-only, the full mod in the dev runs and on the game test server for the peripheral test + findProperty("cctweaked_version")?.let { cc -> + val mc = property("minecraft_version") + modCompileOnly("cc.tweaked:cc-tweaked-$mc-fabric-api:$cc") + modLocalRuntime("cc.tweaked:cc-tweaked-$mc-fabric:$cc") + } + // Architecture rules (src/test/.../architecture): they read the compiled main and client classes testImplementation("com.tngtech.archunit:archunit-junit5:${property("archunit_version")}") testRuntimeOnly(sourceSets["client"].output) diff --git a/build.neoforge.gradle.kts b/build.neoforge.gradle.kts index 421c2e1a9..7d35077d1 100644 --- a/build.neoforge.gradle.kts +++ b/build.neoforge.gradle.kts @@ -72,6 +72,14 @@ configurations.runtimeClasspath { extendsFrom(localRuntime) } // Not on the GameTest server: Jade there sends its ping to the vanilla mock players of the tests, which NeoForge // refuses (no negotiated channels). +// CC: Tweaked comes only from its own maven +repositories { + exclusiveContent { + forRepository { maven("https://maven.squiddev.cc") { name = "CC-Tweaked" } } + filter { includeGroup("cc.tweaked") } + } +} + dependencies { // OMLib (git submodule omlib, built by :buildOmlib): a mod of its own, jar-in-jar. The client and game test source // sets only see main's classes, not its dependencies. @@ -91,6 +99,17 @@ dependencies { // Jade plugin (compat/jade, client/compat/jade): optional, not bundled; present in dev runs to try it compileOnly("maven.modrinth:jade:${property("jade_version")}") localRuntime("maven.modrinth:jade:${property("jade_version")}") + + // CC: Tweaked: the turret base peripheral (compat/computercraft, platform/neoforge/computercraft) compiles against + // its API jars, never bundled, only used when CC: Tweaked is installed; the full mod is in the dev runs and on the + // GameTest server for its test (its artifacts are named -forge on the CC maven). + (findProperty("cctweaked_version") as String?)?.let { cc -> + val mc = property("minecraft_version") + compileOnly("cc.tweaked:cc-tweaked-$mc-forge-api:$cc") + localRuntime("cc.tweaked:cc-tweaked-$mc-forge:$cc") + "gametestCompileOnly"("cc.tweaked:cc-tweaked-$mc-forge-api:$cc") + "gametestRuntimeOnly"("cc.tweaked:cc-tweaked-$mc-forge:$cc") + } } // The client half of the Jade plugin (client/compat/jade) compiles against it too, as with Loom's client source set configurations.named("clientCompileOnly") { extendsFrom(configurations.compileOnly.get()) } diff --git a/docs/architecture.md b/docs/architecture.md index 704fd82ed..03190348f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -64,6 +64,7 @@ This is the only place where the two meet, and the reason the core can be tested | `item.ItemSlot` | `blockentity.base.ContainerItemSlot` | one inventory slot: count, what the item is (ammo, upgrade, addon, fuel), extract | | `target.TargetEntity` | `blockentity.base.LivingTargetEntity` | one living entity: position and eyes (in the base's coordinates), health, armor, category, owner (pets) | | `settings.LogicSettings` | `config.ConfigLogicSettings` | config values (turret stats, base tiers, entity lists) | +| `computer.ComputerTurrets` | `blockentity.base.BaseComputerTurrets` | the turrets on a base's faces: aim, auto fire, forced shot | | `security.SecurityEnvironment` (OMLib) | `security.LevelSecurityEnvironment` (OMLib, with `OMTOwnershipSettings`) | scoreboard teams, operator rights | All positions the core sees are in the base's coordinates. @@ -106,6 +107,7 @@ Packages below `omtteam.openmodularturrets` (main): | `core.target` | `TargetSelector`: who is a valid target and who is the best one | | `core.security` | `DamageRules` (who turret damage may hit); the owner, trusted players and access levels (`TrustManager`) are in OMLib | | `core.generator`, `core.card` | generator burning, the memory card's copy rules for a base's settings (`BaseCardRules`; the card data and the trust list copy rules are OMLib's `core.card`, camouflage permissions OMLib's `core.camo`, machine mode and targeting settings OMLib's `core.machine`) | +| `core.computer` | `BaseComputerCommands`: the commands a computer may send to a turret base (1.12.2's, plus computer control), with the interfaces it needs from the game | | `core.item`, `core.settings`, `core.world` | upgrade/addon types, config value types, the world interfaces above | | `core.storage` | `SlotCapacity`: how much an ammo or fuel slot holds with the attached inventory expanders; `AmmoSort`: the order of the sort button (`TurretBaseInventory.sortAmmo`) | | `api`, `api.weapon` | public turret API for other mods; the built-in turrets use it too | @@ -118,8 +120,8 @@ Packages below `omtteam.openmodularturrets` (main): | `network` | packets: client→server requests (always re-validated) and server→client sync (OMLib's `ConfigSync` sends the configs on join) | | `config` | the JSON config: fields, comments, ranges, migration, the server's config on clients | | `security`, `camo` | the mod's ownership rules (`OMTOwnershipSettings`); the trust lists' Minecraft side (NBT, player lookup) is in OMLib, and camouflage rules | -| `compat` | the porting helpers that keep call sites identical on the version branches (`VersionCompat`, `CompatBlockEntity`, networking, menus; `compat.nbt.NbtCompat` for all NBT reads and `compat.block.BlockCompat` depend on Minecraft only, so any package may use them), small loader differences (`//? if fabric` / `neoforge`), Jade (server half here, tooltips in `client.compat.jade`), and the contraption pose hooks (`SubLevelCompat`, `client.compat.ClientSubLevelCompat`; always the identity pose here, as there is no Sable) | -| `platform` | the loader services shared code calls (`Platform`: `LoaderInfo`, `Fuel`, `Network`, `Menus`, `Energy`); `platform.fabric` / `platform.neoforge` hold the entrypoints, the implementations and the energy/item adapters, and only compile for their loader | +| `compat` | the porting helpers that keep call sites identical on the version branches (`VersionCompat`, `CompatBlockEntity`, networking, menus; `compat.nbt.NbtCompat` for all NBT reads and `compat.block.BlockCompat` depend on Minecraft only, so any package may use them), small loader differences (`//? if fabric` / `neoforge`), Jade (server half here, tooltips in `client.compat.jade`), the CC: Tweaked peripheral (`compat.computercraft`), and the contraption pose hooks (`SubLevelCompat`, `client.compat.ClientSubLevelCompat`; always the identity pose here, as there is no Sable) | +| `platform` | the loader services shared code calls (`Platform`: `LoaderInfo`, `Fuel`, `Network`, `Menus`, `Energy`); `platform.fabric` / `platform.neoforge` hold the entrypoints, the implementations and the energy/item adapters, and only compile for their loader; `platform..computercraft` registers the CC: Tweaked peripheral | | `datagen` | recipes, loot tables, tags, damage types (Fabric only; the NeoForge build converts the Fabric output) | `./gradlew dependencyMap` draws these packages and every import between them as an interactive page. @@ -216,6 +218,22 @@ The base learns of its expanders through `Neighbour.Expanders` in `TurretBaseLog The stacks above one stack are OMLib's large stacks: `TurretBaseInventory` and `FuelContainer` implement `LargeStackContainer` (also on the client, with the bonus stacks synced as menu data), the menus extend `LargeStackMenu` with `LargeStackSlot`s, the screens `LargeStackScreen`, and `VersionCompat.saveItems` saves the counts. Removing an expander leaves larger stacks in the slots; they only cannot grow until they are below the new limit. +### Computers + +A computer reaches a turret base through these layers; this version has all three, for CC: Tweaked: + +1. `core.computer.BaseComputerCommands` holds the commands (1.12.2's, ported with their names, arguments and messages): plain Java values in, an `Object[]` result out, a wrong argument gives an error message, not an exception. + Every command first asks `TurretBaseLogic.acceptsComputers()` (tier 5, or a Serial Port addon); trust changes act as the base's owner through its `TrustManager`, which saves and syncs. + The turrets are reached through `ComputerTurrets` (`blockentity.base.BaseComputerTurrets` over the turrets mounted on the base), player names through `PlayerNames` (the integration provides it). +2. Computer control (`setComputerControl`, `TurretBaseLogic.isComputerControlled()`, saved with the base): the base drops its targets and searches none, and its turrets stay deployed and fire only when told to (`TurretBlockEntity.setYawPitch`, `setAutoFire`, `forceShot`; forced shots ignore the turn rate). + Control and auto fire only apply while the base accepts computers (tier 5 or a Serial Port): a base that lost its Serial Port targets on its own again, since no computer could switch control off. +3. The mod integration: **CC: Tweaked** (both loaders, `compat.computercraft`). + `TurretBasePeripheral` is the peripheral `turret_base`, one class for both loaders; its `@LuaFunction(mainThread = true)` methods have the names of 1.12.2's callbacks (`changeAccessLevel` and `forceShootAllTurrets` as well) and call the commands, so CC runs them on the server thread. + Only the registration is per loader, and only when `computercraft` is loaded: `platform.fabric.computercraft.FabricComputerCraft` (`PeripheralLookup`) and `platform.neoforge.computercraft.NeoForgeComputerCraft` (`PeripheralCapability`, in `RegisterCapabilitiesEvent`). + `ServerPlayerNames` (the `PlayerNames` of the peripheral) reads the server's `usercache.json` itself, as the profile cache has no lookup that never asks Mojang. + CC: Tweaked is compile-only (its API from `maven.squiddev.cc`, never bundled), and the full mod runs in the dev runs and on the game test servers (`cctweaked_version` in `versions//gradle.properties`). + OpenComputers has no integration here (it exists for NeoForge 1.21.1 only). + ## How to add … ### A turret diff --git a/docs/id-mapping.md b/docs/id-mapping.md index 563fe15ed..13cb6952f 100644 --- a/docs/id-mapping.md +++ b/docs/id-mapping.md @@ -108,7 +108,7 @@ The inventory expanders of 4.x (`inventory_expander_tier_one` to `_three`, the m | `openmodularturrets:addon_meta` | 2 | *(not ported: potentia converter, no function in oldmod)* | | `openmodularturrets:addon_meta` | 3 | `openmodularturrets:addon_recycler` | | `openmodularturrets:addon_meta` | 4 | `openmodularturrets:addon_redstone_reactor` | -| `openmodularturrets:addon_meta` | 5 | *(not ported: serial port, computer integration out of scope)* | +| `openmodularturrets:addon_meta` | 5 | `openmodularturrets:addon_serial_port` | | `openmodularturrets:addon_meta` | 6 | `openmodularturrets:addon_solar_panel` | | `openmodularturrets:addon_meta` | 7 | `openmodularturrets:addon_fake_drops` | diff --git a/src/client/java/omtteam/openmodularturrets/client/tooltip/ModuleTooltip.java b/src/client/java/omtteam/openmodularturrets/client/tooltip/ModuleTooltip.java index feb702cbd..b5c3927e9 100644 --- a/src/client/java/omtteam/openmodularturrets/client/tooltip/ModuleTooltip.java +++ b/src/client/java/omtteam/openmodularturrets/client/tooltip/ModuleTooltip.java @@ -160,6 +160,10 @@ private static void appendAddon(AddonItem item, List lines) { lines.add(flavour("addon.fakedrops.flavour")); } case SERIAL_PORT -> { + lines.add(text("addon.serial.a")); + lines.add(text("addon.serial.b")); + lines.add(Component.empty()); + lines.add(flavour("addon.serial.flavour")); } } } diff --git a/src/gametest/CLAUDE.md b/src/gametest/CLAUDE.md index 4dcea27a8..5478cd55b 100644 --- a/src/gametest/CLAUDE.md +++ b/src/gametest/CLAUDE.md @@ -29,6 +29,7 @@ The test mod's loader entrypoints (`gametest/platform/`) run its registr A local test run keeps its config file, and the merge keeps old values of addon turrets: delete `versions/1.21.11-fabric/build/run/gameTest/config/openmodularturrets*` and `versions/1.21.11-neoforge/run/config/openmodularturrets*` after a default changes. - `BaseGuiGameTests` clicks a base through `ServerPlayerGameMode#useItemOn` (the real server path, including the loader's block-use event) and checks that the menu opens for the owner only. The loaders' `FakePlayer`s refuse to open menus, so the test uses `GuiTestPlayer`, a small subclass that opens them without sending a packet (NeoForge opens block menus through the two-argument `openMenu`, which it overrides too); `CamoMenuGameTests` uses it for the camouflage menu and its "Back" to the base GUI. +- `ComputerCraftGameTests` asks the loader's own peripheral lookup (Fabric `PeripheralLookup`, NeoForge `PeripheralCapability`) for the base, as a computer or wired modem does, and calls the `turret_base` methods with arguments as CC passes them; CC: Tweaked is on both test servers (`cctweaked_version`), and the commands themselves are tested in `ComputerControlGameTests`. - `TrustListGameTests`, `CamoMenuGameTests` and the light tests in `CamoGameTests` call OMLib's packet handlers (`TrustPacketHandler`, `CamoPacketHandler`) directly with fake players placed next to the block, as the server does on a packet, and check permission, reach and the access level steps. Fake players are not on the server's player list, so the test that adds an online player by name puts one there for the (synchronous) request only (`TrustListGameTests.online`), on Fabric only: NeoForge returns a read-only view of the list, and vanilla's mock players would log in for real. Names of players who are not online go to the server's name cache: the test server has one (offline mode, so the name's offline UUID). diff --git a/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerControlGameTests.java b/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerControlGameTests.java new file mode 100644 index 000000000..3b3f4a305 --- /dev/null +++ b/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerControlGameTests.java @@ -0,0 +1,201 @@ +package omtteam.openmodularturrets.gametest; + +import net.minecraft.core.BlockPos; +import net.minecraft.gametest.framework.GameTestHelper; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.phys.AABB; +import omtteam.omlib.core.security.AccessLevel; +import omtteam.omlib.core.security.PlayerIdentity; +import omtteam.omlib.core.security.TrustManager; +import omtteam.omlib.core.security.TrustedPlayer; +import omtteam.omlib.core.world.Face; +import omtteam.openmodularturrets.blockentity.TurretBaseBlockEntity; +import omtteam.openmodularturrets.blockentity.base.BaseComputerTurrets; +import omtteam.openmodularturrets.blockentity.turret.TurretBlockEntity; +import omtteam.openmodularturrets.core.computer.BaseComputerCommands; +import omtteam.openmodularturrets.core.computer.BaseComputerCommands.Command; +import omtteam.openmodularturrets.core.computer.PlayerNames; +import omtteam.openmodularturrets.core.turret.TurretType; +import omtteam.openmodularturrets.entity.projectile.TurretProjectile; +import omtteam.openmodularturrets.inventory.TurretBaseInventory; +import omtteam.openmodularturrets.registry.ModBlocks; +import omtteam.openmodularturrets.registry.ModItems; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +/** + * The computer commands ({@link BaseComputerCommands}, shared by the OpenComputers component) on a real base, with its + * turrets through {@link BaseComputerTurrets}: which bases accept computers, computer control (no own targeting), + * aiming and firing the turrets, and trust changes. The arguments are passed as a computer passes them (Lua numbers + * as {@code Double}). + */ +@SuppressWarnings({"unused", "RedundantCast"}) +public class ComputerControlGameTests implements OMTGameTests { + private static final int TIMEOUT_TICKS = 200; + /** How long a computer-controlled turret is watched for not firing at a target in range. */ + private static final int WATCH_TICKS = 60; + /** The face of the turret in {@link TurretScene} (on top of the base), as a computer passes it. */ + private static final Double UP = (double) Face.UP.ordinal(); + /** Aim of the forced shots: east, down into the floor, so the projectiles stay in the scene. */ + private static final Double YAW = 90.0D; + private static final Double PITCH = -30.0D; + /** The cheapest turret on a base with addon slots (tier 2), so the serial port is needed. */ + private static final TurretType TURRET = TurretType.MACHINE_GUN_TURRET; + + private static final PlayerIdentity FRIEND = new PlayerIdentity(UUID.randomUUID(), "Computer_Friend"); + /** Knows only {@link #FRIEND} (any case), like the server's player list and name cache. */ + private static final PlayerNames NAMES = name -> name.equalsIgnoreCase(FRIEND.name()) ? Optional.of(FRIEND) + : Optional.empty(); + + /** + * Tier 1 bases never accept computers, tier 2 to 4 only with a serial port addon, tier 5 always; a refused base + * answers every command with {@link BaseComputerCommands#NO_ACCESS} and changes nothing. + */ + @GameTest(template = EMPTY_STRUCTURE, batch = "computer_commands", timeoutTicks = TIMEOUT_TICKS) + public void onlyTierFiveOrASerialPortAcceptComputers(GameTestHelper helper) { + TurretBaseBlockEntity tierOne = base(helper, new BlockPos(1, 1, 1), ModBlocks.TURRET_BASES.get(0)); + TurretBaseBlockEntity tierTwo = base(helper, new BlockPos(3, 1, 1), ModBlocks.TURRET_BASES.get(1)); + TurretBaseBlockEntity serialPort = base(helper, new BlockPos(5, 1, 1), ModBlocks.TURRET_BASES.get(1)); + serialPort.getInventory().setItem(TurretBaseInventory.ADDON_START, new ItemStack(ModItems.ADDON_SERIAL_PORT)); + TurretBaseBlockEntity tierFive = base(helper, new BlockPos(1, 1, 3), ModBlocks.TURRET_BASES.get(4)); + + for (TurretBaseBlockEntity refused : new TurretBaseBlockEntity[]{tierOne, tierTwo}) { + assertAnswer(helper, commands(refused).call(Command.getOwner, new Object[0]), BaseComputerCommands.NO_ACCESS); + assertAnswer(helper, commands(refused).call(Command.setComputerControl, new Object[]{true}), + BaseComputerCommands.NO_ACCESS); + helper.assertFalse(refused.getLogic().isComputerControlled(), + "A tier " + refused.getTier() + " base without serial port was put under computer control"); + } + for (TurretBaseBlockEntity accepted : new TurretBaseBlockEntity[]{serialPort, tierFive}) { + assertAnswer(helper, commands(accepted).call(Command.getType, new Object[0]), BaseComputerCommands.TYPE); + assertAnswer(helper, commands(accepted).call(Command.setComputerControl, new Object[]{true}), true); + helper.assertTrue(accepted.getLogic().isComputerControlled(), + "setComputerControl did not reach the tier " + accepted.getTier() + " base"); + assertAnswer(helper, commands(accepted).call(Command.isComputerControl, new Object[0]), true); + } + helper.succeed(); + } + + /** Under computer control the base does not target a mob in range, so its turret neither turns nor fires. */ + @GameTest(template = EMPTY_STRUCTURE, batch = "computer_control_targeting", timeoutTicks = TIMEOUT_TICKS) + public void computerControlStopsTargeting(GameTestHelper helper) { + TurretBaseBlockEntity base = controlledScene(helper); + int ammo = ammo(base); + LivingEntity target = TurretScene.spawnTarget(helper, TurretScene.TARGET_IN_FRONT); + TurretScene.onEachTick(helper, () -> { + helper.assertTrue(base.getLogic().getTarget(Face.UP).isEmpty(), "A computer-controlled base picked a target"); + helper.assertTrue(ammo(base) == ammo, "A computer-controlled turret fired on its own"); + helper.assertTrue(target.getHealth() == target.getMaxHealth(), "The target was damaged"); + if (helper.getTick() >= WATCH_TICKS) { + TurretScene.succeed(helper); + } + }); + } + + /** + * {@code setTurretYawPitch} aims the turret, {@code forceShootTurret} fires one shot along the aim once the turret + * is ready: a projectile appears at the turret and one bullet is used. + */ + @GameTest(template = EMPTY_STRUCTURE, batch = "computer_force_shot", timeoutTicks = TIMEOUT_TICKS) + public void forceShootTurretFires(GameTestHelper helper) { + TurretBaseBlockEntity base = controlledScene(helper); + BaseComputerCommands commands = commands(base); + assertAnswer(helper, commands.call(Command.setTurretYawPitch, new Object[]{UP, YAW, PITCH}), true); + assertAnswer(helper, commands.call(Command.forceShootTurret, new Object[]{(double) Face.DOWN.ordinal()}), false); + int ammo = ammo(base); + TurretScene.succeedWhen(helper, () -> { + Object[] answer = commands.call(Command.forceShootTurret, new Object[]{UP}); + helper.assertTrue(Boolean.TRUE.equals(answer[0]), "forceShootTurret answered " + Arrays.toString(answer)); + helper.assertFalse(projectilesAt(helper).isEmpty(), "The forced shot spawned no projectile"); + helper.assertTrue(ammo(base) < ammo, "The forced shot used no ammo"); + }); + } + + /** With auto fire on, a computer-controlled turret fires along its aim whenever it is ready. */ + @GameTest(template = EMPTY_STRUCTURE, batch = "computer_auto_fire", timeoutTicks = TIMEOUT_TICKS) + public void autoFireFiresRepeatedly(GameTestHelper helper) { + TurretBaseBlockEntity base = controlledScene(helper); + BaseComputerCommands commands = commands(base); + assertAnswer(helper, commands.call(Command.setAllYawPitch, new Object[]{YAW, PITCH}), + "set yaw and pitch successfully"); + assertAnswer(helper, commands.call(Command.setTurretAutoForceFire, new Object[]{UP, true}), true); + TurretBlockEntity turret = base.getTurret(Face.UP).orElseThrow(); + helper.assertTrue(turret.isAutoFire(), "setTurretAutoForceFire did not reach the turret"); + int ammo = ammo(base); + TurretScene.succeedWhen(helper, () -> helper.assertTrue(ammo - ammo(base) >= 3, + "Auto fire used " + (ammo - ammo(base)) + " bullets, expected at least 3")); + } + + /** + * Trust changes through the commands act as the owner and reach the base's trust list: a known name is added with + * the given access level, its level changes, and it is removed again (names in any case); an unknown name is + * refused. + */ + @GameTest(template = EMPTY_STRUCTURE, batch = "computer_commands", timeoutTicks = TIMEOUT_TICKS) + public void trustChangesReachTheTrustManager(GameTestHelper helper) { + TurretBaseBlockEntity base = base(helper, new BlockPos(1, 1, 1), ModBlocks.TURRET_BASES.get(4)); + TrustManager trust = base.getTrustManager(); + trust.setOwner(new PlayerIdentity(UUID.randomUUID(), "ComputerOwner")); + BaseComputerCommands commands = commands(base); + + assertAnswer(helper, commands.call(Command.addTrustedPlayer, new Object[]{"Nobody_Known"}), "Name not valid!"); + helper.assertTrue(trust.getTrustedPlayers().isEmpty(), "An unknown name was added"); + + assertAnswer(helper, commands.call(Command.addTrustedPlayer, + new Object[]{"computer_friend", (double) AccessLevel.CHANGE_SETTINGS.ordinal()}), true); + assertLevel(helper, trust, AccessLevel.CHANGE_SETTINGS); + + assertAnswer(helper, commands.call(Command.changeAccessLevel, + new Object[]{"COMPUTER_FRIEND", (double) AccessLevel.OPEN_GUI.ordinal()}), true); + assertLevel(helper, trust, AccessLevel.OPEN_GUI); + + assertAnswer(helper, commands.call(Command.removeTrustedPlayer, new Object[]{"Computer_Friend"}), true); + helper.assertTrue(trust.getTrustedPlayer(FRIEND.uuid()).isEmpty(), "removeTrustedPlayer did not remove the player"); + helper.succeed(); + } + + /** + * {@link TurretScene} with a {@link #TURRET} on a tier 2 base with a serial port addon, under computer control. + */ + private static TurretBaseBlockEntity controlledScene(GameTestHelper helper) { + TurretBaseBlockEntity base = TurretScene.build(helper, TURRET, TIMEOUT_TICKS); + base.getInventory().setItem(TurretBaseInventory.ADDON_START, new ItemStack(ModItems.ADDON_SERIAL_PORT)); + assertAnswer(helper, commands(base).call(Command.setComputerControl, new Object[]{true}), true); + return base; + } + + /** A base without owner and turrets. */ + private static TurretBaseBlockEntity base(GameTestHelper helper, BlockPos pos, Block block) { + helper.setBlock(pos, block); + return (TurretBaseBlockEntity) helper.getLevel().getBlockEntity(helper.absolutePos(pos)); + } + + private static BaseComputerCommands commands(TurretBaseBlockEntity base) { + return new BaseComputerCommands(base.getLogic(), new BaseComputerTurrets(base), NAMES); + } + + private static int ammo(TurretBaseBlockEntity base) { + return base.getInventory().getItem(TurretBaseInventory.AMMO_START).getCount(); + } + + /** The turret projectiles around the scene's turret. */ + private static List projectilesAt(GameTestHelper helper) { + return helper.getLevel().getEntitiesOfClass(TurretProjectile.class, + new AABB(helper.absolutePos(TurretScene.TURRET)).inflate(3.0D)); + } + + private static void assertAnswer(GameTestHelper helper, Object[] answer, Object expected) { + helper.assertTrue(answer.length >= 1 && expected.equals(answer[0]), + "Expected " + expected + ", the command answered " + Arrays.toString(answer)); + } + + private static void assertLevel(GameTestHelper helper, TrustManager trust, AccessLevel expected) { + Optional level = trust.getTrustedPlayer(FRIEND.uuid()).map(TrustedPlayer::getAccessLevel); + helper.assertTrue(level.equals(Optional.of(expected)), "Computer_Friend has " + level + ", expected " + expected); + } +} diff --git a/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerCraftGameTests.java b/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerCraftGameTests.java new file mode 100644 index 000000000..96b9c3c93 --- /dev/null +++ b/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerCraftGameTests.java @@ -0,0 +1,122 @@ +package omtteam.openmodularturrets.gametest; + +import dan200.computercraft.api.lua.LuaException; +import dan200.computercraft.api.lua.MethodResult; +import dan200.computercraft.api.lua.ObjectArguments; +import dan200.computercraft.api.peripheral.IPeripheral; +//? if fabric { +import dan200.computercraft.api.peripheral.PeripheralLookup; +//?} +//? if neoforge { +/*import dan200.computercraft.api.peripheral.PeripheralCapability; +*///?} +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.gametest.framework.GameTestHelper; +import net.minecraft.world.level.block.Blocks; +import omtteam.omlib.core.security.PlayerIdentity; +import omtteam.openmodularturrets.blockentity.TurretBaseBlockEntity; +import omtteam.openmodularturrets.compat.computercraft.TurretBasePeripheral; +import omtteam.openmodularturrets.core.computer.BaseComputerCommands; +import omtteam.openmodularturrets.registry.ModBlocks; + +import java.util.Arrays; +import java.util.UUID; + +/** + * The CC: Tweaked peripheral of the turret base (CC: Tweaked is on the game test server of both loaders). The + * loader's own peripheral lookup (what a computer or wired modem asks) finds the base and names the peripheral + * {@code turret_base}, and the methods work with arguments as CC passes them (Lua numbers as doubles). The commands + * themselves are tested in the unit tests of {@code BaseComputerCommands} and in {@code ComputerControlGameTests}. + */ +@SuppressWarnings("unused") +public class ComputerCraftGameTests implements OMTGameTests { + private static final BlockPos TIER_FIVE = new BlockPos(1, 1, 1); + private static final BlockPos TIER_ONE = new BlockPos(4, 1, 1); + private static final PlayerIdentity OWNER = new PlayerIdentity(UUID.randomUUID(), "CcTestOwner"); + + @GameTest(template = EMPTY_STRUCTURE, batch = "computercraft") + public void computersFindTheTurretBasePeripheral(GameTestHelper helper) { + BlockPos pos = helper.absolutePos(TIER_FIVE); + TurretBaseBlockEntity base = base(helper, TIER_FIVE, ModBlocks.TURRET_BASES.size() - 1); + try { + for (Direction side : Direction.values()) { + IPeripheral peripheral = lookup(helper, pos, side); + helper.assertTrue(peripheral != null, "CC: Tweaked has no peripheral on the " + side + " side of the base"); + helper.assertTrue(BaseComputerCommands.TYPE.equals(peripheral.getType()), + "The peripheral is not a turret_base: " + peripheral.getType()); + helper.assertTrue(peripheral.getTarget() == base, "The peripheral's target is not the base"); + helper.assertTrue(peripheral.equals(lookup(helper, pos, Direction.UP)), + "Two peripherals of one base are not equal, so a computer would detach and attach again"); + } + } finally { + helper.setBlock(TIER_FIVE, Blocks.AIR); + } + helper.succeed(); + } + + @GameTest(template = EMPTY_STRUCTURE, batch = "computercraft") + public void methodsControlTheBase(GameTestHelper helper) throws LuaException { + TurretBaseBlockEntity base = base(helper, TIER_FIVE, ModBlocks.TURRET_BASES.size() - 1); + TurretBaseBlockEntity tierOne = base(helper, TIER_ONE, 0); + try { + TurretBasePeripheral peripheral = TurretBasePeripheral.of(base); + helper.assertTrue(peripheral != null, "No peripheral for a base on a server level"); + assertResult(helper, peripheral.getOwner(args()), OWNER.name(), "getOwner"); + assertResult(helper, peripheral.setComputerControl(args(true)), true, "setComputerControl"); + helper.assertTrue(base.getLogic().isComputerControlled(), "setComputerControl did not reach the base"); + assertResult(helper, peripheral.isComputerControl(args()), true, "isComputerControl"); + assertResult(helper, peripheral.setAttacksMobs(args(false)), true, "setAttacksMobs"); + assertResult(helper, peripheral.isAttacksMobs(args()), false, "isAttacksMobs"); + assertResult(helper, peripheral.getMaxEnergyStorage(args()), base.getLogic().getEnergy().getCapacity(), + "getMaxEnergyStorage"); + // neither online nor in the server's name cache + assertResult(helper, peripheral.addTrustedPlayer(args("Never_Joined_OMT")), "Name not valid!", + "addTrustedPlayer of an unknown name"); + helper.assertTrue(peripheral.getMode().getResult() != null, "getMode returned nothing"); + + TurretBasePeripheral denied = TurretBasePeripheral.of(tierOne); + assertResult(helper, denied.getOwner(args()), BaseComputerCommands.NO_ACCESS, "getOwner on tier 1"); + assertResult(helper, denied.setComputerControl(args(true)), BaseComputerCommands.NO_ACCESS, + "setComputerControl on tier 1"); + helper.assertFalse(tierOne.getLogic().isComputerControlled(), "A tier 1 base accepted computer control"); + } finally { + helper.setBlock(TIER_FIVE, Blocks.AIR); + helper.setBlock(TIER_ONE, Blocks.AIR); + } + helper.succeed(); + } + + /** A base of the given tier index with {@link #OWNER} at {@code pos}. */ + private static TurretBaseBlockEntity base(GameTestHelper helper, BlockPos pos, int tierIndex) { + helper.setBlock(pos, ModBlocks.TURRET_BASES.get(tierIndex)); + TurretBaseBlockEntity base = (TurretBaseBlockEntity) helper.getLevel().getBlockEntity(helper.absolutePos(pos)); + base.getTrustManager().setOwner(OWNER); + return base; + } + + /** What a computer next to {@code pos} would get, through the loader's own lookup. */ + private static IPeripheral lookup(GameTestHelper helper, BlockPos pos, Direction side) { +//? if fabric { + return PeripheralLookup.get().find(helper.getLevel(), pos, side); +//?} +//? if neoforge { + /*return helper.getLevel().getCapability(PeripheralCapability.get(), pos, side); +*///?} + } + + /** The first value of a method's result equals {@code expected} (numbers compared as doubles). */ + private static void assertResult(GameTestHelper helper, MethodResult result, Object expected, String call) { + Object[] values = result.getResult(); + helper.assertTrue(values != null && values.length > 0, call + " returned nothing"); + Object actual = values[0]; + boolean equal = expected instanceof Number number && actual instanceof Number value + ? number.doubleValue() == value.doubleValue() + : expected.equals(actual); + helper.assertTrue(equal, call + " returned " + Arrays.toString(values) + ", expected " + expected); + } + + private static ObjectArguments args(Object... values) { + return new ObjectArguments(values); + } +} diff --git a/src/gametest/resources/fabric.mod.json b/src/gametest/resources/fabric.mod.json index 6749a8a0d..43204d88e 100644 --- a/src/gametest/resources/fabric.mod.json +++ b/src/gametest/resources/fabric.mod.json @@ -27,7 +27,9 @@ "omtteam.openmodularturrets.gametest.CompatGameTests", "omtteam.openmodularturrets.gametest.SolarPanelGameTests", "omtteam.openmodularturrets.gametest.ExpanderGameTests", - "omtteam.openmodularturrets.gametest.AmmoSortGameTests" + "omtteam.openmodularturrets.gametest.AmmoSortGameTests", + "omtteam.openmodularturrets.gametest.ComputerControlGameTests", + "omtteam.openmodularturrets.gametest.ComputerCraftGameTests" ], "openmodularturrets": [ "omtteam.openmodularturrets.gametest.ApiTestTurrets" diff --git a/src/main/java/omtteam/openmodularturrets/CLAUDE.md b/src/main/java/omtteam/openmodularturrets/CLAUDE.md index 33675bc8b..57075cee7 100644 --- a/src/main/java/omtteam/openmodularturrets/CLAUDE.md +++ b/src/main/java/omtteam/openmodularturrets/CLAUDE.md @@ -20,12 +20,13 @@ omtteam.openmodularturrets │ └── misc/ # crank (LeverBlock), generator, inventory expanders ├── blockentity/ │ ├── TurretBaseBlockEntity # forwards to core.base.TurretBaseLogic; inventory, energy, trust list -│ ├── base/ # adapters to core (BlockEntityBaseWorld, ContainerItemSlot, LivingTargetEntity) +│ ├── base/ # adapters to core (BlockEntityBaseWorld, ContainerItemSlot, LivingTargetEntity), BaseComputerTurrets │ ├── turret/ # TurretBlockEntity (one type for all turrets), TurretMount, RayWeapons, EffectWeapons │ ├── defense/ # PassiveDefenseBlockEntity, CamoTrapBlockEntity │ └── misc/ # GeneratorBlockEntity, LeverBlockEntity ├── core/ # (from OpenModularCore, omt-core; bundled, not in src/) game rules without Minecraft: -│ # base, turret, target, security (DamageRules), generator, card, item, settings, storage, world +│ # base, turret, target, security (DamageRules), generator, card, item, settings, storage, world, +│ # computer (BaseComputerCommands, the computer commands of 1.12.2; ComputerTurrets, PlayerNames) ├── camo/ # CamoRules, CamoLightProperties (CamoHost, CamoData and the menu are in OMLib) ├── security/ # OMTOwnershipSettings (trust lists, access levels and claiming are in OMLib) ├── inventory/ # TurretBaseInventory, FuelContainer, AmmoRules @@ -35,9 +36,10 @@ omtteam.openmodularturrets ├── network/ # OMTPackets, BasePackets + BasePacketHandler (C2S), RayPacket (S2C) ├── config/ # self-written config (JSON via Gson, OMLib's machinery), no library ├── turret/ # TurretStatLines (range falloff and turn rate lines for tooltips and Jade) -├── compat/ # ModuleEnabledCondition, SubLevelCompat (contraption poses, always the identity pose here), jade/ (server half); the porting helpers are in OMLib +├── compat/ # ModuleEnabledCondition, SubLevelCompat (contraption poses, always the identity pose here), jade/ (server half), computercraft/ (the CC: Tweaked peripheral turret_base); the porting helpers are in OMLib ├── mixin/ # LivingEntityMixin -├── platform/ # fabric/, neoforge/: entrypoints, services, adapters (each built for its loader only) +├── platform/ # fabric/, neoforge/: entrypoints, services, adapters (each built for its loader only); +│ # /computercraft: registers the CC: Tweaked peripheral └── datagen/ # recipes, loot tables, tags, damage types (Fabric only) ``` diff --git a/src/main/java/omtteam/openmodularturrets/blockentity/TurretBaseBlockEntity.java b/src/main/java/omtteam/openmodularturrets/blockentity/TurretBaseBlockEntity.java index 1a27582cb..6cc96db40 100644 --- a/src/main/java/omtteam/openmodularturrets/blockentity/TurretBaseBlockEntity.java +++ b/src/main/java/omtteam/openmodularturrets/blockentity/TurretBaseBlockEntity.java @@ -18,6 +18,7 @@ import omtteam.openmodularturrets.block.turret.TurretBlock; import omtteam.openmodularturrets.blockentity.base.BlockEntityBaseWorld; import omtteam.openmodularturrets.blockentity.base.TurretBaseNbt; +import omtteam.openmodularturrets.blockentity.turret.TurretBlockEntity; import omtteam.omlib.camo.CamoData; import omtteam.omlib.camo.DisguiseRules; import omtteam.omlib.camo.CamoHost; @@ -157,6 +158,19 @@ public int getTier() { return logic.getTier(); } + /** + * The turret block entity mounted on a face, if any: a turret next to the face that faces away from this base + * (like {@link #scanNeighbour}), in a loaded chunk. + */ + public Optional getTurret(Face face) { + if (level == null) return Optional.empty(); + Direction direction = Direction.valueOf(face.name()); + BlockPos pos = worldPosition.relative(direction); + if (!level.isLoaded(pos)) return Optional.empty(); + return level.getBlockEntity(pos) instanceof TurretBlockEntity turret && turret.getFacing() == direction + ? Optional.of(turret) : Optional.empty(); + } + /** What the attached inventory expanders add to the ammo slots ({@link TurretBaseLogic#getSlotCapacity}). */ public SlotCapacity getSlotCapacity() { return logic.getSlotCapacity(); diff --git a/src/main/java/omtteam/openmodularturrets/blockentity/base/BaseComputerTurrets.java b/src/main/java/omtteam/openmodularturrets/blockentity/base/BaseComputerTurrets.java new file mode 100644 index 000000000..53efa5503 --- /dev/null +++ b/src/main/java/omtteam/openmodularturrets/blockentity/base/BaseComputerTurrets.java @@ -0,0 +1,51 @@ +package omtteam.openmodularturrets.blockentity.base; + +import omtteam.omlib.core.world.Face; +import omtteam.openmodularturrets.blockentity.TurretBaseBlockEntity; +import omtteam.openmodularturrets.blockentity.turret.TurretBlockEntity; +import omtteam.openmodularturrets.core.computer.ComputerTurrets; + +import java.util.EnumSet; +import java.util.Optional; +import java.util.Set; + +/** + * The turrets of a turret base for the computer commands (1.12.2 {@code TurretBase.setTurretYawPitch}, + * {@code setTurretForceFire} and {@code forceShootTurret}): the turret block entities on its faces + * ({@link TurretBaseBlockEntity#getTurret}). + */ +public final class BaseComputerTurrets implements ComputerTurrets { + private final TurretBaseBlockEntity base; + + public BaseComputerTurrets(TurretBaseBlockEntity base) { + this.base = base; + } + + @Override + public boolean setYawPitch(Face face, float yaw, float pitch) { + Optional turret = base.getTurret(face); + turret.ifPresent(t -> t.setYawPitch(yaw, pitch)); + return turret.isPresent(); + } + + @Override + public boolean setAutoFire(Face face, boolean autoFire) { + Optional turret = base.getTurret(face); + turret.ifPresent(t -> t.setAutoFire(autoFire)); + return turret.isPresent(); + } + + @Override + public boolean forceShot(Face face) { + return base.getTurret(face).map(TurretBlockEntity::forceShot).orElse(false); + } + + @Override + public Set faces() { + Set faces = EnumSet.noneOf(Face.class); + for (Face face : Face.values()) { + if (base.getTurret(face).isPresent()) faces.add(face); + } + return faces; + } +} diff --git a/src/main/java/omtteam/openmodularturrets/blockentity/base/TurretBaseNbt.java b/src/main/java/omtteam/openmodularturrets/blockentity/base/TurretBaseNbt.java index 44d2df430..09e2c536c 100644 --- a/src/main/java/omtteam/openmodularturrets/blockentity/base/TurretBaseNbt.java +++ b/src/main/java/omtteam/openmodularturrets/blockentity/base/TurretBaseNbt.java @@ -26,6 +26,7 @@ public static void save(TurretBaseLogic.State state, CompoundTag tag) { tag.putBoolean("MultiTargeting", state.multiTargeting()); tag.putInt("Kills", state.kills()); tag.putInt("PlayerKills", state.playerKills()); + tag.putBoolean("ComputerControl", state.computerControlled()); } public static TurretBaseLogic.State load(CompoundTag tag) { @@ -43,6 +44,7 @@ public static TurretBaseLogic.State load(CompoundTag tag) { NbtCompat.getInt(targeting, "MaxRange", 0), NbtCompat.getBoolean(tag, "MultiTargeting", false), NbtCompat.getInt(tag, "Kills", 0), - NbtCompat.getInt(tag, "PlayerKills", 0)); + NbtCompat.getInt(tag, "PlayerKills", 0), + NbtCompat.getBoolean(tag, "ComputerControl", false)); } } diff --git a/src/main/java/omtteam/openmodularturrets/blockentity/turret/RayWeapons.java b/src/main/java/omtteam/openmodularturrets/blockentity/turret/RayWeapons.java index b66cb0f23..b3c41cd66 100644 --- a/src/main/java/omtteam/openmodularturrets/blockentity/turret/RayWeapons.java +++ b/src/main/java/omtteam/openmodularturrets/blockentity/turret/RayWeapons.java @@ -5,7 +5,9 @@ import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Marker; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; @@ -37,6 +39,8 @@ public final class RayWeapons { /** 1.12.2 {@code blockRange} when nothing was hit. */ private static final double NO_BLOCK_HIT = 500; + /** 1.12.2 {@code RayTracingTurret.forceShot}: forced rays scatter like a shot at a target one block high. */ + private static final double FORCED_TARGET_HEIGHT = 1.0D; private RayWeapons() { } @@ -57,19 +61,51 @@ public static void shoot(TurretBlockEntity turret, TurretBaseBlockEntity base, R if (!(turret.getLevel() instanceof ServerLevel level)) { return; } + shoot(level, turret, base, weapon, new Vec3(target.getX(), target.getEyeY(), target.getZ()), + target.getBbHeight(), target, origin, renderOrigin); + } + + /** + * 1.12.2 {@code RayTracingTurret.forceShot}: a ray without a target (computer control, + * {@link TurretBlockEntity#forceShot()}), scattered like a shot at a target one block high at {@code end}. + * Energy and ammo are already consumed. + * + * @param end the aim point, a few blocks in front of the turret + * @param renderOrigin where a hit is drawn from if the weapon {@linkplain RayWeapon#drawFromTip() draws from the tip} + */ + static void shoot(TurretBlockEntity turret, TurretBaseBlockEntity base, RayWeapon weapon, Vec3 end, Vec3 origin, + Vec3 renderOrigin) { + if (!(turret.getLevel() instanceof ServerLevel level)) { + return; + } + // the block trace takes an entity as collision context (the same call on every version branch); a marker at + // the turret behaves like none + Marker context = new Marker(EntityType.MARKER, level); + context.setPos(origin); + shoot(level, turret, base, weapon, end, FORCED_TARGET_HEIGHT, context, origin, renderOrigin); + } + + /** + * The rays of one shot towards {@code aim}. + * + * @param targetHeight height of the target, for the scatter of small targets + * @param context the collision context of the block trace (the target) + */ + private static void shoot(ServerLevel level, TurretBlockEntity turret, TurretBaseBlockEntity base, + RayWeapon weapon, Vec3 aim, double targetHeight, Entity context, Vec3 origin, + Vec3 renderOrigin) { TurretType type = turret.getTurretType(); TurretBaseLogic logic = base.getLogic(); double accuracy = logic.getAccuracyDeviation(type); - Vec3 aim = new Vec3(target.getX(), target.getEyeY(), target.getZ()); for (int i = 0; i <= logic.getScattershotCount(type); i++) { - double scale = ProjectileMath.raySpread(accuracy, target.getBbHeight(), aim.distanceTo(origin), logic.getRange(type)); + double scale = ProjectileMath.raySpread(accuracy, targetHeight, aim.distanceTo(origin), logic.getRange(type)); Vec3 end = aim.add(level.random.nextGaussian() * scale, level.random.nextGaussian() * scale, level.random.nextGaussian() * scale); Vec3 start = origin.add(end.subtract(origin).normalize().scale(0.8D)); playSound(level, turret.getBlockPos(), weapon.launchSound()); BlockHitResult blockHit = level.clip(new ClipContext(start, end, ClipContext.Block.COLLIDER, - ClipContext.Fluid.NONE, target)); + ClipContext.Fluid.NONE, context)); double blockRange = blockHit.getType() == HitResult.Type.BLOCK ? blockHit.getLocation().distanceTo(start) : NO_BLOCK_HIT; Entity hit = null; diff --git a/src/main/java/omtteam/openmodularturrets/blockentity/turret/TurretBlockEntity.java b/src/main/java/omtteam/openmodularturrets/blockentity/turret/TurretBlockEntity.java index 88521220c..e7fe3f737 100644 --- a/src/main/java/omtteam/openmodularturrets/blockentity/turret/TurretBlockEntity.java +++ b/src/main/java/omtteam/openmodularturrets/blockentity/turret/TurretBlockEntity.java @@ -63,6 +63,8 @@ public class TurretBlockEntity extends CompatBlockEntity { private static final float CLIENT_TURN_RATE = 0.5F; /** Degrees the melee turret's top piece turns per tick while active. */ private static final float CLIENT_SPIN_RATE = 36.0F; + /** 1.12.2 {@code RayTracingTurret.forceShot}: forced shots aim at the point 5 blocks along the aim. */ + private static final double FORCED_SHOT_DISTANCE = 5D; /** Cooldown and concealment (see {@link TurretState}). */ private final TurretState state = new TurretState(); @@ -74,6 +76,8 @@ public class TurretBlockEntity extends CompatBlockEntity { private float syncedPitch; private int ticksSinceSync; private boolean active; + /** 1.12.2 {@code autoFire}: fire along the aim whenever ready (computer control); saved, not synced. */ + private boolean autoFire; /** Whether the base has a damage amp addon; synced to clients (the turret shows its damage amp LEDs). */ private boolean damageAmp; @@ -175,19 +179,26 @@ public static void serverTick(Level level, BlockPos pos, BlockState state, Turre turret.ticksSinceSync++; TurretBaseLogic logic = base.get().getLogic(); boolean engaging = false; - if (logic.isActive() && turret.getWeapon() instanceof AreaWeapon area) { + if (!logic.isActive()) { + turret.forgetTarget(); + } else if (logic.isComputerControlled()) { + turret.computerControlledTick(logic, type); + } else if (turret.getWeapon() instanceof AreaWeapon area) { engaging = turret.strikeInReach((ServerLevel) level, base.get(), area); - } else if (logic.isActive() && turret.getWeapon() instanceof SelfTargetingWeapon weapon) { + } else if (turret.getWeapon() instanceof SelfTargetingWeapon weapon) { engaging = turret.pickAndFire((ServerLevel) level, base.get(), weapon); - } else if (logic.isActive()) { + } else { Optional target = logic.getTarget(turret.getFace()) .filter(LivingTargetEntity.class::isInstance) .map(t -> ((LivingTargetEntity) t).getEntity()); turret.updateConcealment(logic, target.isPresent()); target.ifPresentOrElse(turret::engage, turret::forgetTarget); engaging = target.isPresent(); - } else { - turret.forgetTarget(); + // 1.12.2 AbstractDirectedTurret.update: without a target, auto fire shoots along the aim (only while the + // base accepts computers, which could switch it off again) + if (target.isEmpty() && turret.autoFire && logic.acceptsComputers() && turret.state.isReady(logic, type)) { + turret.forceShot(); + } } boolean amped = logic.getDamageAmpLevel() > 0; if (engaging != turret.active || amped != turret.damageAmp) { @@ -198,6 +209,19 @@ public static void serverTick(Level level, BlockPos pos, BlockState state, Turre turret.syncAimIfChanged(); } + /** + * A computer controls the turrets ({@link TurretBaseLogic#isComputerControlled()}): no weapon looks for targets, + * the turret stays deployed and only fires along its aim, with {@linkplain #isAutoFire() auto fire} whenever it + * is ready (or through {@link #forceShot()}). + */ + private void computerControlledTick(TurretBaseLogic logic, TurretType type) { + forgetTarget(); + updateConcealment(logic, true); + if (autoFire && state.isReady(logic, type)) { + forceShot(); + } + } + /** * Whether the base is active and this turret has a target (melee turret: something in reach); synced to clients * (melee blades spin). @@ -245,17 +269,22 @@ private void engage(Entity target) { fire(toBody, velocity, target); } else if (weapon instanceof RayWeapon ray) { Optional base = beginShot(); - if (base.isPresent()) { - // rays start 0.1 blocks above the turret centre, the arc is drawn from its tip - Vec3 origin = centre.add(mount.up().scale(0.1D)); - Vec3 tip = centre.add(mount.up().scale(0.5D)); - RayWeapons.shoot(this, base.get(), ray, target, origin, tip); - } + base.ifPresent(shooter -> RayWeapons.shoot(this, shooter, ray, target, rayOrigin(mount), rayTip(mount))); } else if (weapon instanceof EffectWeapon effect) { beginShot().ifPresent(base -> EffectWeapons.fireEffect(this, base, effect, target)); } } + /** Rays start 0.1 blocks above the turret centre (in the world). */ + private static Vec3 rayOrigin(TurretMount mount) { + return mount.centre().add(mount.up().scale(0.1D)); + } + + /** The tip of the turret, where the arc is drawn from (in the world). */ + private static Vec3 rayTip(TurretMount mount) { + return mount.centre().add(mount.up().scale(0.5D)); + } + /** * Turns towards the target's eyes, within {@link TurretMath#limit} (angles relative to the face, in the plot), at * most the turret type's {@code turnRate} degrees per tick on each axis ({@link TurretMath#turnTowards}; 0 turns @@ -468,6 +497,64 @@ public boolean fire(Vector3 toAim, Vector3 velocity, @Nullable Entity target) { return true; } + // ---- Computer control (1.12.2 3.x API, used by the computer commands) ---- + + /** + * Aims the turret; the angles are relative to the face ({@link TurretMath}), in degrees, and clamped by + * {@link TurretMath#limit}. Clients see the new aim within {@link #SYNC_INTERVAL} ticks. While the base has a + * target for this turret, the turret turns back to it. Any angles work (a pitch of 270 is -90, which the limit + * then raises); non-finite ones are ignored. + */ + public void setYawPitch(float yaw, float pitch) { + if (!Float.isFinite(yaw) || !Float.isFinite(pitch)) return; + // through the direction, so the limit sees the yaw in (-180, 180] and the pitch in [-90, 90] + Face face = getFace(); + TurretMath.Angles angles = TurretMath.limit( + TurretMath.anglesFor(face, TurretMath.direction(face, new TurretMath.Angles(yaw, pitch)))); + this.yaw = angles.yaw(); + this.pitch = angles.pitch(); + setChanged(); + } + + /** Whether the turret fires along its aim whenever it is ready (1.12.2 {@code autoFire}); saved, not synced. */ + public boolean isAutoFire() { + return autoFire; + } + + /** See {@link #isAutoFire()}. */ + public void setAutoFire(boolean autoFire) { + if (this.autoFire != autoFire) { + this.autoFire = autoFire; + setChanged(); + } + } + + /** + * 1.12.2 {@code forceShot}: one shot along the current aim, at the point {@link #FORCED_SHOT_DISTANCE} blocks + * ahead (on a contraption along the turned aim). Only projectile and ray turrets can do that; the shot needs the + * cooldown to have passed, energy, ammo and an active base, like any other. The turn rate does not hold it back. + * + * @return whether it fired (always false on the client) + */ + public boolean forceShot() { + if (!(level instanceof ServerLevel)) return false; + TurretWeapon weapon = getWeapon(); + if (!(weapon instanceof ProjectileWeapon) && !(weapon instanceof RayWeapon)) return false; + TurretMount mount = getMount(); + // the aim is relative to the face in the plot; the contraption's pose turns it into the world + Vector3 aim = mount.pose().directionToWorld(TurretMath.direction(getFace(), new TurretMath.Angles(yaw, pitch))); + Vector3 toAim = aim.scale(FORCED_SHOT_DISTANCE / aim.length()); + if (weapon instanceof ProjectileWeapon) { + return fire(toAim, Vector3.ZERO, null); + } + Optional base = beginShot(); + if (base.isEmpty()) return false; + Vec3 origin = rayOrigin(mount); + RayWeapons.shoot(this, base.get(), (RayWeapon) weapon, origin.add(TurretMount.toVec3(toAim)), origin, + rayTip(mount)); + return true; + } + private void playSound(SoundEvent sound) { if (level != null) { level.playSound(null, worldPosition, sound, SoundSource.BLOCKS, @@ -538,6 +625,7 @@ protected void readData(CompoundTag tag, HolderLookup.Provider registries) { pitch = NbtCompat.getFloat(tag, "Pitch", 0); active = NbtCompat.getBoolean(tag, "Active", false); damageAmp = NbtCompat.getBoolean(tag, "DamageAmp", false); + autoFire = NbtCompat.getBoolean(tag, "AutoFire", false); if (!renderInitialised) { renderYaw = prevRenderYaw = yaw; renderPitch = prevRenderPitch = pitch; @@ -549,6 +637,7 @@ protected void readData(CompoundTag tag, HolderLookup.Provider registries) { protected void writeData(CompoundTag tag, HolderLookup.Provider registries) { writeClientData(tag, registries); tag.putInt("TicksSinceShot", state.getTicksSinceShot()); + tag.putBoolean("AutoFire", autoFire); } /** Clients only need the aim, whether the turret is active and whether it shows the damage amp LEDs. */ diff --git a/src/main/java/omtteam/openmodularturrets/compat/computercraft/ServerPlayerNames.java b/src/main/java/omtteam/openmodularturrets/compat/computercraft/ServerPlayerNames.java new file mode 100644 index 000000000..2403597a7 --- /dev/null +++ b/src/main/java/omtteam/openmodularturrets/compat/computercraft/ServerPlayerNames.java @@ -0,0 +1,65 @@ +package omtteam.openmodularturrets.compat.computercraft; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import omtteam.omlib.core.security.PlayerIdentity; +import omtteam.omlib.security.PlayerAdapter; +import omtteam.openmodularturrets.core.computer.PlayerNames; + +import java.io.IOException; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; + +/** + * Player names for computers on both loaders: a player online on {@code server}, else one in the server's + * {@code usercache.json} (every player who joined before and whose entry has not expired). The file is read here + * because the profile cache only offers lookups that ask Mojang for an unknown name, and a computer's call runs on + * the server thread; a missing or unreadable file means no cached players. Names match without regard to case. + */ +final class ServerPlayerNames implements PlayerNames { + private static final String CACHE_FILE = "usercache.json"; + + private final MinecraftServer server; + + ServerPlayerNames(MinecraftServer server) { + this.server = server; + } + + @Override + public Optional find(String name) { + for (ServerPlayer player : server.getPlayerList().getPlayers()) { + PlayerIdentity identity = PlayerAdapter.identity(player); + if (identity.name().equalsIgnoreCase(name)) { + return Optional.of(identity); + } + } + return cached(name); + } + + private Optional cached(String name) { + Path file = server.getFile(CACHE_FILE); + if (!Files.isRegularFile(file)) { + return Optional.empty(); + } + try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + for (JsonElement entry : JsonParser.parseReader(reader).getAsJsonArray()) { + JsonObject object = entry.getAsJsonObject(); + if (object.get("name").getAsString().equalsIgnoreCase(name)) { + return Optional.of(new PlayerIdentity(UUID.fromString(object.get("uuid").getAsString()), + object.get("name").getAsString())); + } + } + } catch (IOException | RuntimeException e) { + // unreadable or malformed cache: the same as an unknown name + return Optional.empty(); + } + return Optional.empty(); + } +} diff --git a/src/main/java/omtteam/openmodularturrets/compat/computercraft/TurretBasePeripheral.java b/src/main/java/omtteam/openmodularturrets/compat/computercraft/TurretBasePeripheral.java new file mode 100644 index 000000000..08b46a9d6 --- /dev/null +++ b/src/main/java/omtteam/openmodularturrets/compat/computercraft/TurretBasePeripheral.java @@ -0,0 +1,206 @@ +package omtteam.openmodularturrets.compat.computercraft; + +import dan200.computercraft.api.lua.IArguments; +import dan200.computercraft.api.lua.LuaException; +import dan200.computercraft.api.lua.LuaFunction; +import dan200.computercraft.api.lua.MethodResult; +import dan200.computercraft.api.peripheral.IPeripheral; +import net.minecraft.server.MinecraftServer; +import omtteam.openmodularturrets.blockentity.TurretBaseBlockEntity; +import omtteam.openmodularturrets.blockentity.base.BaseComputerTurrets; +import omtteam.openmodularturrets.core.computer.BaseComputerCommands; +import omtteam.openmodularturrets.core.computer.BaseComputerCommands.Command; +import omtteam.openmodularturrets.core.computer.PlayerNames; +import org.jetbrains.annotations.Nullable; + +/** + * The peripheral {@code turret_base} of one turret base for CC: Tweaked (the same on Fabric and NeoForge; only its + * registration is per loader, see {@code platform//computercraft}). The methods have the names, arguments and + * results of the 1.12.2 peripheral; the OpenComputers component's names ({@code TurretBaseEnvironment}: + * {@code changeTrustedPlayerAccess}, {@code forceShootAll}) work as aliases. The commands are + * {@link BaseComputerCommands}, so whether a computer may use the base is up to it + * ({@code TurretBaseLogic.acceptsComputers()}, checked by every command). Every method runs on the server thread, as it + * changes or reads the world. The peripheral keeps no state: a computer attached to two sides of one base uses the same + * commands on the same base. + */ +public final class TurretBasePeripheral implements IPeripheral { + private final TurretBaseBlockEntity base; + private final BaseComputerCommands commands; + + /** + * @param base the base + * @param names resolves the names given to {@code addTrustedPlayer} + */ + public TurretBasePeripheral(TurretBaseBlockEntity base, PlayerNames names) { + this.base = base; + this.commands = new BaseComputerCommands(base.getLogic(), new BaseComputerTurrets(base), names); + } + + /** + * A peripheral for the base, or null when its level is no server's (a computer only exists on a server). + */ + @Nullable + public static TurretBasePeripheral of(TurretBaseBlockEntity base) { + if (base.getLevel() == null) { + return null; + } + MinecraftServer server = base.getLevel().getServer(); + return server == null ? null : new TurretBasePeripheral(base, new ServerPlayerNames(server)); + } + + @Override + public String getType() { + return BaseComputerCommands.TYPE; + } + + /** Two peripherals of one base are the same peripheral, so a computer does not detach and attach again. */ + @Override + public boolean equals(@Nullable IPeripheral other) { + return this == other || other instanceof TurretBasePeripheral peripheral && peripheral.base == base; + } + + @Override + public Object getTarget() { + return base; + } + + private MethodResult call(Command command, IArguments args) throws LuaException { + return MethodResult.of((Object[]) commands.call(command, args.getAll())); + } + + @LuaFunction(mainThread = true) + public MethodResult getOwner(IArguments args) throws LuaException { + return call(Command.getOwner, args); + } + + @LuaFunction(mainThread = true) + public MethodResult isAttacksMobs(IArguments args) throws LuaException { + return call(Command.isAttacksMobs, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setAttacksMobs(IArguments args) throws LuaException { + return call(Command.setAttacksMobs, args); + } + + @LuaFunction(mainThread = true) + public MethodResult isAttacksNeutrals(IArguments args) throws LuaException { + return call(Command.isAttacksNeutrals, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setAttacksNeutrals(IArguments args) throws LuaException { + return call(Command.setAttacksNeutrals, args); + } + + @LuaFunction(mainThread = true) + public MethodResult isAttacksPlayers(IArguments args) throws LuaException { + return call(Command.isAttacksPlayers, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setAttacksPlayers(IArguments args) throws LuaException { + return call(Command.setAttacksPlayers, args); + } + + @LuaFunction(mainThread = true) + public MethodResult getTrustedPlayers(IArguments args) throws LuaException { + return call(Command.getTrustedPlayers, args); + } + + @LuaFunction(mainThread = true) + public MethodResult getTrustedPlayer(IArguments args) throws LuaException { + return call(Command.getTrustedPlayer, args); + } + + @LuaFunction(mainThread = true) + public MethodResult addTrustedPlayer(IArguments args) throws LuaException { + return call(Command.addTrustedPlayer, args); + } + + @LuaFunction(mainThread = true) + public MethodResult removeTrustedPlayer(IArguments args) throws LuaException { + return call(Command.removeTrustedPlayer, args); + } + + @LuaFunction(value = {"changeAccessLevel", "changeTrustedPlayerAccess"}, mainThread = true) + public MethodResult changeAccessLevel(IArguments args) throws LuaException { + return call(Command.changeAccessLevel, args); + } + + /** {@code getType()} of the 1.12.2 peripheral (not {@link #getType()}, which CC reads as the peripheral type). */ + @LuaFunction(value = "getType", mainThread = true) + public MethodResult typeName(IArguments args) throws LuaException { + return call(Command.getType, args); + } + + @LuaFunction(mainThread = true) + public MethodResult getMaxEnergyStorage(IArguments args) throws LuaException { + return call(Command.getMaxEnergyStorage, args); + } + + @LuaFunction(mainThread = true) + public MethodResult getCurrentEnergyStorage(IArguments args) throws LuaException { + return call(Command.getCurrentEnergyStorage, args); + } + + @LuaFunction(mainThread = true) + public MethodResult getActive(IArguments args) throws LuaException { + return call(Command.getActive, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setMode(IArguments args) throws LuaException { + return call(Command.setMode, args); + } + + @LuaFunction(mainThread = true) + public MethodResult getMode() { + return MethodResult.of((Object[]) commands.modeDescription()); + } + + @LuaFunction(mainThread = true) + public MethodResult getRedstone(IArguments args) throws LuaException { + return call(Command.getRedstone, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setAllYawPitch(IArguments args) throws LuaException { + return call(Command.setAllYawPitch, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setTurretYawPitch(IArguments args) throws LuaException { + return call(Command.setTurretYawPitch, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setAllAutoForceFire(IArguments args) throws LuaException { + return call(Command.setAllAutoForceFire, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setTurretAutoForceFire(IArguments args) throws LuaException { + return call(Command.setTurretAutoForceFire, args); + } + + @LuaFunction(value = {"forceShootAllTurrets", "forceShootAll"}, mainThread = true) + public MethodResult forceShootAllTurrets(IArguments args) throws LuaException { + return call(Command.forceShootAllTurrets, args); + } + + @LuaFunction(mainThread = true) + public MethodResult forceShootTurret(IArguments args) throws LuaException { + return call(Command.forceShootTurret, args); + } + + @LuaFunction(mainThread = true) + public MethodResult setComputerControl(IArguments args) throws LuaException { + return call(Command.setComputerControl, args); + } + + @LuaFunction(mainThread = true) + public MethodResult isComputerControl(IArguments args) throws LuaException { + return call(Command.isComputerControl, args); + } +} diff --git a/src/main/java/omtteam/openmodularturrets/config/ConfigData.java b/src/main/java/omtteam/openmodularturrets/config/ConfigData.java index 9b9472de0..234f11d2f 100644 --- a/src/main/java/omtteam/openmodularturrets/config/ConfigData.java +++ b/src/main/java/omtteam/openmodularturrets/config/ConfigData.java @@ -482,7 +482,7 @@ public static class Addons { @Comment("Fake drops addon.") public boolean fakeDrops = true; - /** Whether the addon works and can be crafted; addons without an item have no switch. */ + /** Whether the addon works and can be crafted; the serial port has no switch (it only lets computers in). */ public boolean isEnabled(AddonType type) { return switch (type) { case CONCEALER -> concealer; diff --git a/src/main/java/omtteam/openmodularturrets/datagen/OMTRecipeProvider.java b/src/main/java/omtteam/openmodularturrets/datagen/OMTRecipeProvider.java index 91fb16f15..282428e75 100644 --- a/src/main/java/omtteam/openmodularturrets/datagen/OMTRecipeProvider.java +++ b/src/main/java/omtteam/openmodularturrets/datagen/OMTRecipeProvider.java @@ -345,7 +345,7 @@ private ShapedRecipeBuilder upgrade(ItemLike result) { .unlockedBy("has_io_bus", has(ModItems.IO_BUS)); } - /** 1.12.2 {@code addon_meta_0,1,3,4,6,7_vanilla.json}. */ + /** 1.12.2 {@code addon_meta_0,1,3..7_vanilla.json}. */ private void addons(Consumer save) { save.accept(shaped(RecipeCategory.MISC, ModItems.ADDON_CONCEALER) .pattern("IQI") @@ -401,6 +401,14 @@ private void addons(Consumer save) { .define('E', Items.ENDER_EYE) .define('B', ModItems.IO_BUS) .unlockedBy("has_io_bus", has(ModItems.IO_BUS))); + // serial port: unconditional (1.12.2 only had it with a computer mod) + save.accept(shaped(RecipeCategory.MISC, ModItems.ADDON_SERIAL_PORT) + .pattern(" Q ") + .pattern("BQB") + .pattern(" Q ") + .define('Q', CommonTags.QUARTZ_GEMS) + .define('B', ModItems.IO_BUS) + .unlockedBy("has_io_bus", has(ModItems.IO_BUS))); } /** diff --git a/src/main/java/omtteam/openmodularturrets/entity/projectile/RocketProjectile.java b/src/main/java/omtteam/openmodularturrets/entity/projectile/RocketProjectile.java index 6239d00db..e4bfa1d91 100644 --- a/src/main/java/omtteam/openmodularturrets/entity/projectile/RocketProjectile.java +++ b/src/main/java/omtteam/openmodularturrets/entity/projectile/RocketProjectile.java @@ -45,12 +45,12 @@ public float getGravityEffect() { /** * 1.12.2 {@code onEntityUpdate}: with homing enabled the rocket steers towards its target every tick and is * removed when the target is gone. (In 1.12.2 this code was never reached because {@code onUpdate} did not call - * it.) + * it.) A rocket fired without a target (computer: forced shot, auto fire) flies straight on. */ @Override public void tick() { - if (!level().isClientSide() && OMTConfig.get().turrets.canRocketsHome) { - if (target == null || !target.isAlive()) { + if (!level().isClientSide() && OMTConfig.get().turrets.canRocketsHome && target != null) { + if (!target.isAlive()) { discard(); return; } diff --git a/src/main/java/omtteam/openmodularturrets/platform/fabric/OMTFabric.java b/src/main/java/omtteam/openmodularturrets/platform/fabric/OMTFabric.java index d2c62edff..64e1883d1 100644 --- a/src/main/java/omtteam/openmodularturrets/platform/fabric/OMTFabric.java +++ b/src/main/java/omtteam/openmodularturrets/platform/fabric/OMTFabric.java @@ -6,6 +6,7 @@ import net.fabricmc.loader.api.FabricLoader; import omtteam.openmodularturrets.api.OMTPlugin; import omtteam.openmodularturrets.entity.projectile.KillCounter; +import omtteam.openmodularturrets.platform.fabric.computercraft.FabricComputerCraft; import omtteam.openmodularturrets.registry.TurretRegistry; import omtteam.openmodularturrets.registry.ModBlockEntities; import omtteam.openmodularturrets.startup.OMTStartup; @@ -23,6 +24,9 @@ public void onInitialize() { OMTStartup.registrationSteps().forEach(step -> step.register().run()); FabricBlockLookups.register(ModBlockEntities.transferTypes()); FabricModuleEnabledCondition.register(); + if (FabricLoader.getInstance().isModLoaded(FabricComputerCraft.MOD_ID)) { + FabricComputerCraft.register(); + } ServerLivingEntityEvents.AFTER_DEATH.register(KillCounter::onDeath); } diff --git a/src/main/java/omtteam/openmodularturrets/platform/fabric/computercraft/FabricComputerCraft.java b/src/main/java/omtteam/openmodularturrets/platform/fabric/computercraft/FabricComputerCraft.java new file mode 100644 index 000000000..18c46b6ea --- /dev/null +++ b/src/main/java/omtteam/openmodularturrets/platform/fabric/computercraft/FabricComputerCraft.java @@ -0,0 +1,24 @@ +package omtteam.openmodularturrets.platform.fabric.computercraft; + +import dan200.computercraft.api.peripheral.PeripheralLookup; +import omtteam.openmodularturrets.OMT; +import omtteam.openmodularturrets.compat.computercraft.TurretBasePeripheral; +import omtteam.openmodularturrets.registry.ModBlockEntities; + +/** + * CC: Tweaked on Fabric: a computer next to a turret base (or a wired modem on it) sees the peripheral + * {@code turret_base}. Only loaded when CC: Tweaked is installed (compile-only, never bundled). + */ +public final class FabricComputerCraft { + public static final String MOD_ID = "computercraft"; + + private FabricComputerCraft() { + } + + /** Registers the peripheral for the turret base block entity, on every side. */ + public static void register() { + PeripheralLookup.get().registerForBlockEntity((base, side) -> TurretBasePeripheral.of(base), + ModBlockEntities.TURRET_BASE); + OMT.LOGGER.info("CC: Tweaked found: turret bases are peripherals (turret_base)"); + } +} diff --git a/src/main/java/omtteam/openmodularturrets/platform/neoforge/OMTNeoForge.java b/src/main/java/omtteam/openmodularturrets/platform/neoforge/OMTNeoForge.java index f9f19b9f5..cb9034f0a 100644 --- a/src/main/java/omtteam/openmodularturrets/platform/neoforge/OMTNeoForge.java +++ b/src/main/java/omtteam/openmodularturrets/platform/neoforge/OMTNeoForge.java @@ -17,6 +17,7 @@ import omtteam.openmodularturrets.api.OMTPlugin; import omtteam.openmodularturrets.compat.ModuleEnabledCondition; import omtteam.openmodularturrets.entity.projectile.KillCounter; +import omtteam.openmodularturrets.platform.neoforge.computercraft.NeoForgeComputerCraft; import omtteam.omlib.platform.Platform; import omtteam.omlib.registry.RegistrationStep; import omtteam.openmodularturrets.registry.TurretRegistry; @@ -40,8 +41,12 @@ public OMTNeoForge(IEventBus modBus) { OMTStartup.init(NeoForgePlugins.find(OMTPlugin.Register.class, OMTPlugin.class, TurretRegistry.Plugin::new)); modBus.addListener(this::onRegister); modBus.addListener(this::onCommonSetup); - modBus.addListener((RegisterCapabilitiesEvent event) -> - NeoForgeCapabilities.register(event, ModBlockEntities.transferTypes())); + modBus.addListener((RegisterCapabilitiesEvent event) -> { + NeoForgeCapabilities.register(event, ModBlockEntities.transferTypes()); + if (Platform.loaderInfo().isModLoaded(NeoForgeComputerCraft.MOD_ID)) { + NeoForgeComputerCraft.register(event); + } + }); modBus.addListener((RegisterPayloadHandlersEvent event) -> ((NeoForgeNetwork) Platform.network()).applyRegistrations(event, OMT.MOD_ID)); // lowest priority: mods that cancel the death have run, and cancelled deaths do not arrive here @@ -60,7 +65,9 @@ private void onRegister(RegisterEvent event) { } /** - * A step whose registry fired no event would leave its content unregistered: fail loudly instead. + * A step whose registry fired no event would leave its content unregistered: fail loudly instead. With CC: Tweaked + * installed, turret bases are peripherals ({@code NeoForgeComputerCraft}, registered in the capability event, a + * class that is only loaded then). */ private void onCommonSetup(FMLCommonSetupEvent event) { if (done.size() != steps.size()) { diff --git a/src/main/java/omtteam/openmodularturrets/platform/neoforge/computercraft/NeoForgeComputerCraft.java b/src/main/java/omtteam/openmodularturrets/platform/neoforge/computercraft/NeoForgeComputerCraft.java new file mode 100644 index 000000000..8fa395643 --- /dev/null +++ b/src/main/java/omtteam/openmodularturrets/platform/neoforge/computercraft/NeoForgeComputerCraft.java @@ -0,0 +1,25 @@ +package omtteam.openmodularturrets.platform.neoforge.computercraft; + +import dan200.computercraft.api.peripheral.PeripheralCapability; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import omtteam.openmodularturrets.OMT; +import omtteam.openmodularturrets.compat.computercraft.TurretBasePeripheral; +import omtteam.openmodularturrets.registry.ModBlockEntities; + +/** + * CC: Tweaked on NeoForge: a computer next to a turret base (or a wired modem on it) sees the peripheral + * {@code turret_base}. Only loaded when CC: Tweaked is installed (compile-only, never bundled). + */ +public final class NeoForgeComputerCraft { + public static final String MOD_ID = "computercraft"; + + private NeoForgeComputerCraft() { + } + + /** Registers the peripheral for the turret base block entity, on every side; called from the capability event. */ + public static void register(RegisterCapabilitiesEvent event) { + event.registerBlockEntity(PeripheralCapability.get(), ModBlockEntities.TURRET_BASE, + (base, side) -> TurretBasePeripheral.of(base)); + OMT.LOGGER.info("CC: Tweaked found: turret bases are peripherals (turret_base)"); + } +} diff --git a/src/main/java/omtteam/openmodularturrets/registry/ModItems.java b/src/main/java/omtteam/openmodularturrets/registry/ModItems.java index f8b49edc3..0f79746eb 100644 --- a/src/main/java/omtteam/openmodularturrets/registry/ModItems.java +++ b/src/main/java/omtteam/openmodularturrets/registry/ModItems.java @@ -83,13 +83,14 @@ public final class ModItems { "upgrade_" + GeneratorUpgradeType.ENERGY_MULTIPLIER.getSerializedName(), properties -> new GeneratorUpgradeItem(GeneratorUpgradeType.ENERGY_MULTIPLIER, properties), new Item.Properties()); - // Addons (1.12.2 AddonMetaItem; the potentia converter is gone, the serial port has no item, see AddonType) + // Addons (1.12.2 AddonMetaItem; the potentia converter is gone, see AddonType) public static final AddonItem ADDON_CONCEALER = registerAddon(AddonType.CONCEALER); public static final AddonItem ADDON_DAMAGE_AMP = registerAddon(AddonType.DAMAGE_AMP); public static final AddonItem ADDON_RECYCLER = registerAddon(AddonType.RECYCLER); public static final AddonItem ADDON_REDSTONE_REACTOR = registerAddon(AddonType.REDSTONE_REACTOR); public static final AddonItem ADDON_SOLAR_PANEL = registerAddon(AddonType.SOLAR_PANEL); public static final AddonItem ADDON_FAKE_DROPS = registerAddon(AddonType.FAKE_DROPS); + public static final AddonItem ADDON_SERIAL_PORT = registerAddon(AddonType.SERIAL_PORT); // Misc and passive defense blocks public static final BlockItem LEVER = registerBlock(ModBlocks.LEVER); diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index 8d0fbd9f5..537b0202d 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -41,3 +41,11 @@ type = "optional" versionRange = "*" ordering = "NONE" side = "BOTH" + +# CC: Tweaked: the turret base becomes a peripheral when it is installed +[[dependencies.${mod_id}]] +modId = "computercraft" +type = "optional" +versionRange = "*" +ordering = "NONE" +side = "BOTH" diff --git a/src/main/resources/assets/openmodularturrets/items/addon_serial_port.json b/src/main/resources/assets/openmodularturrets/items/addon_serial_port.json new file mode 100644 index 000000000..09d2c6c8b --- /dev/null +++ b/src/main/resources/assets/openmodularturrets/items/addon_serial_port.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "openmodularturrets:item/addon_serial_port" + } +} diff --git a/src/main/resources/assets/openmodularturrets/lang/de_de.json b/src/main/resources/assets/openmodularturrets/lang/de_de.json index 6d04061b0..b691637da 100644 --- a/src/main/resources/assets/openmodularturrets/lang/de_de.json +++ b/src/main/resources/assets/openmodularturrets/lang/de_de.json @@ -45,6 +45,7 @@ "item.openmodularturrets.addon_fake_drops": "Addon - Fake Drops", "item.openmodularturrets.addon_recycler": "Addon - Recycler", "item.openmodularturrets.addon_redstone_reactor": "Addon - Redstone Reaktor", + "item.openmodularturrets.addon_serial_port": "Addon - Serieller Port", "item.openmodularturrets.addon_solar_panel": "Addon - Solarmodul", "item.openmodularturrets.ammo_blazing_clay": "Munition - Glühender Ton", "item.openmodularturrets.ammo_bolt": "Munition - Armbrustbolzen", @@ -173,6 +174,9 @@ "tooltip.openmodularturrets.addon.redstone.b": "RF pro", "tooltip.openmodularturrets.addon.redstone.c": "Redstone Staub im Munitionslager.", "tooltip.openmodularturrets.addon.redstone.flavour": "Sublimation, verbessert.", + "tooltip.openmodularturrets.addon.serial.a": "Erlaubt Computer-", + "tooltip.openmodularturrets.addon.serial.b": "Kompatibilität.", + "tooltip.openmodularturrets.addon.serial.flavour": "Wer braucht OOP?", "tooltip.openmodularturrets.addon.solar.a": "Erzeugt", "tooltip.openmodularturrets.addon.solar.b": "RF/t im Sonnenlicht.", "tooltip.openmodularturrets.addon.solar.flavour": "Gutes Licht!", diff --git a/src/main/resources/assets/openmodularturrets/lang/en_gb.json b/src/main/resources/assets/openmodularturrets/lang/en_gb.json index 27f36bae6..46ff666fc 100644 --- a/src/main/resources/assets/openmodularturrets/lang/en_gb.json +++ b/src/main/resources/assets/openmodularturrets/lang/en_gb.json @@ -45,6 +45,7 @@ "item.openmodularturrets.addon_fake_drops": "Addon - Fake Drops", "item.openmodularturrets.addon_recycler": "Addon - Recycler", "item.openmodularturrets.addon_redstone_reactor": "Addon - Redstone Reactor", + "item.openmodularturrets.addon_serial_port": "Addon - Serial Port", "item.openmodularturrets.addon_solar_panel": "Addon - Solar Panel", "item.openmodularturrets.ammo_blazing_clay": "Ammo - Blazing Clay", "item.openmodularturrets.ammo_bolt": "Ammo - Crossbow Bolt", @@ -170,6 +171,9 @@ "tooltip.openmodularturrets.addon.redstone.b": "RF per", "tooltip.openmodularturrets.addon.redstone.c": "redstone dust in Ammo inventory.", "tooltip.openmodularturrets.addon.redstone.flavour": "Sublimation, refined.", + "tooltip.openmodularturrets.addon.serial.a": "Enables computer", + "tooltip.openmodularturrets.addon.serial.b": "compatibility.", + "tooltip.openmodularturrets.addon.serial.flavour": "Who needs OOP?", "tooltip.openmodularturrets.addon.solar.a": "Generates", "tooltip.openmodularturrets.addon.solar.b": "RF/t in sunlight.", "tooltip.openmodularturrets.addon.solar.flavour": "Good Helios!", diff --git a/src/main/resources/assets/openmodularturrets/lang/en_us.json b/src/main/resources/assets/openmodularturrets/lang/en_us.json index f28ed5b3f..20feb0915 100644 --- a/src/main/resources/assets/openmodularturrets/lang/en_us.json +++ b/src/main/resources/assets/openmodularturrets/lang/en_us.json @@ -45,6 +45,7 @@ "item.openmodularturrets.addon_fake_drops": "Addon - Fake Drops", "item.openmodularturrets.addon_recycler": "Addon - Recycler", "item.openmodularturrets.addon_redstone_reactor": "Addon - Redstone Reactor", + "item.openmodularturrets.addon_serial_port": "Addon - Serial Port", "item.openmodularturrets.addon_solar_panel": "Addon - Solar Panel", "item.openmodularturrets.ammo_blazing_clay": "Ammo - Blazing Clay", "item.openmodularturrets.ammo_bolt": "Ammo - Crossbow Bolt", @@ -170,6 +171,9 @@ "tooltip.openmodularturrets.addon.redstone.b": "RF per", "tooltip.openmodularturrets.addon.redstone.c": "redstone dust in Ammo inventory.", "tooltip.openmodularturrets.addon.redstone.flavour": "Sublimation, refined.", + "tooltip.openmodularturrets.addon.serial.a": "Enables computer", + "tooltip.openmodularturrets.addon.serial.b": "compatibility.", + "tooltip.openmodularturrets.addon.serial.flavour": "Who needs OOP?", "tooltip.openmodularturrets.addon.solar.a": "Generates", "tooltip.openmodularturrets.addon.solar.b": "RF/t in sunlight.", "tooltip.openmodularturrets.addon.solar.flavour": "Good Helios!", diff --git a/src/main/resources/assets/openmodularturrets/lang/pt_br.json b/src/main/resources/assets/openmodularturrets/lang/pt_br.json index 1d057c2d6..231f6e23c 100644 --- a/src/main/resources/assets/openmodularturrets/lang/pt_br.json +++ b/src/main/resources/assets/openmodularturrets/lang/pt_br.json @@ -45,6 +45,7 @@ "item.openmodularturrets.addon_fake_drops": "Extensão - Drops Falsos", "item.openmodularturrets.addon_recycler": "Extensão - Reciclador", "item.openmodularturrets.addon_redstone_reactor": "Addon - Redstone Reactor", + "item.openmodularturrets.addon_serial_port": "Extensão - Porta serial", "item.openmodularturrets.addon_solar_panel": "Extensão - Painel Solar", "item.openmodularturrets.ammo_blazing_clay": "Munição - Argila Ardente", "item.openmodularturrets.ammo_bolt": "Ammo - Crossbow Bolt", @@ -170,6 +171,9 @@ "tooltip.openmodularturrets.addon.redstone.b": "RF", "tooltip.openmodularturrets.addon.redstone.c": "pó de redstone no inventário para funcionar.", "tooltip.openmodularturrets.addon.redstone.flavour": "Sublimação, refinado.", + "tooltip.openmodularturrets.addon.serial.a": "Ativa compatibilidade", + "tooltip.openmodularturrets.addon.serial.b": "com computadores.", + "tooltip.openmodularturrets.addon.serial.flavour": "Quem precisa de OOP?", "tooltip.openmodularturrets.addon.solar.a": "Gera", "tooltip.openmodularturrets.addon.solar.b": "RF/t na luz do sol.", "tooltip.openmodularturrets.addon.solar.flavour": "Bom Helios!", diff --git a/src/main/resources/assets/openmodularturrets/lang/ru_ru.json b/src/main/resources/assets/openmodularturrets/lang/ru_ru.json index a936e77f0..95cd0c3d8 100644 --- a/src/main/resources/assets/openmodularturrets/lang/ru_ru.json +++ b/src/main/resources/assets/openmodularturrets/lang/ru_ru.json @@ -45,6 +45,7 @@ "item.openmodularturrets.addon_fake_drops": "Addon - Fake Drops", "item.openmodularturrets.addon_recycler": "Addon - Recycler", "item.openmodularturrets.addon_redstone_reactor": "Addon - Redstone Reactor", + "item.openmodularturrets.addon_serial_port": "Addon - Serial Port", "item.openmodularturrets.addon_solar_panel": "Addon - Solar Panel", "item.openmodularturrets.ammo_blazing_clay": "Ammo - Blazing Clay", "item.openmodularturrets.ammo_bolt": "Ammo - Crossbow Bolt", @@ -170,6 +171,9 @@ "tooltip.openmodularturrets.addon.redstone.b": "RF per", "tooltip.openmodularturrets.addon.redstone.c": "redstone dust in Ammo inventory.", "tooltip.openmodularturrets.addon.redstone.flavour": "Sublimation, refined.", + "tooltip.openmodularturrets.addon.serial.a": "Enables computer", + "tooltip.openmodularturrets.addon.serial.b": "compatibility.", + "tooltip.openmodularturrets.addon.serial.flavour": "Who needs OOP?", "tooltip.openmodularturrets.addon.solar.a": "Generates", "tooltip.openmodularturrets.addon.solar.b": "RF/t in sunlight.", "tooltip.openmodularturrets.addon.solar.flavour": "Good Helios!", diff --git a/src/main/resources/assets/openmodularturrets/lang/zh_cn.json b/src/main/resources/assets/openmodularturrets/lang/zh_cn.json index 6c308ec11..da987e64e 100644 --- a/src/main/resources/assets/openmodularturrets/lang/zh_cn.json +++ b/src/main/resources/assets/openmodularturrets/lang/zh_cn.json @@ -45,6 +45,7 @@ "item.openmodularturrets.addon_fake_drops": "附件-模拟玩家掉落", "item.openmodularturrets.addon_recycler": "附件-弹药循环", "item.openmodularturrets.addon_redstone_reactor": "附件-红石能源芯片", + "item.openmodularturrets.addon_serial_port": "附件-串行端口", "item.openmodularturrets.addon_solar_panel": "附件-太阳能芯片", "item.openmodularturrets.ammo_blazing_clay": "弹药-燃烧弹", "item.openmodularturrets.ammo_bolt": "Ammo - Crossbow Bolt", @@ -170,6 +171,9 @@ "tooltip.openmodularturrets.addon.redstone.b": "RF/红石", "tooltip.openmodularturrets.addon.redstone.c": "红石需放在弹药槽内充当燃料.", "tooltip.openmodularturrets.addon.redstone.flavour": "升华,精炼.", + "tooltip.openmodularturrets.addon.serial.a": "兼容计算机", + "tooltip.openmodularturrets.addon.serial.b": "兼容性.", + "tooltip.openmodularturrets.addon.serial.flavour": "谁要OOP?", "tooltip.openmodularturrets.addon.solar.a": "在日照下产能", "tooltip.openmodularturrets.addon.solar.b": "RF/t", "tooltip.openmodularturrets.addon.solar.flavour": "伟大的太阳神!", diff --git a/src/main/resources/assets/openmodularturrets/models/item/addon_serial_port.json b/src/main/resources/assets/openmodularturrets/models/item/addon_serial_port.json new file mode 100644 index 000000000..408dc256a --- /dev/null +++ b/src/main/resources/assets/openmodularturrets/models/item/addon_serial_port.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/generated", + "textures": { + "layer0": "openmodularturrets:item/addon_serial_port" + } +} diff --git a/src/main/resources/assets/openmodularturrets/textures/item/addon_serial_port.png b/src/main/resources/assets/openmodularturrets/textures/item/addon_serial_port.png new file mode 100644 index 0000000000000000000000000000000000000000..0c2e8adc956933f1e1bd61adc9f5d0f2e809dd6f GIT binary patch literal 478 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdzwj^(N7l!{JxM1({$v_d#0*}aI z1_r((Aj~*bn@<`j$X?><>&kwgU6{{;cTdCFas~#*Y)==*kch*{fByfsKkUFHmeUlr zYE?<$)s45eOU{&FlUUHwFmKJ9dNww;w#5$vc|c%4pX{xn0L`ve+} zTAq2nT}&q>0SGL<{uYmHYg?I}@O9_K&EjB%&zGpMMRFWq&^ecAxBu63^S16z#_s$3 z+YA=i_1AtC%aYbUvd3{cTLELqeEHqAvnPriPR!(F|NsB}g2y*p zTWz+5*Inzt)5p$EOkfXBm$OfkxufWCdf$TwKFrLV42c_hX17J$+5n6R22WQ%mvv4F FO#rJVxcUG9 literal 0 HcmV?d00001 diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index f455b451f..b7cd018bb 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -39,7 +39,8 @@ } ], "suggests": { - "jade": "*" + "jade": "*", + "computercraft": "*" }, "depends": { "fabricloader": ">=${loader_version}", diff --git a/versions/1.21.11-fabric/gradle.properties b/versions/1.21.11-fabric/gradle.properties index 6cbe5de8b..ee0a55191 100644 --- a/versions/1.21.11-fabric/gradle.properties +++ b/versions/1.21.11-fabric/gradle.properties @@ -3,3 +3,6 @@ minecraft_dependency=1.21.11 fabric_api_version=0.141.6+1.21.11 java_version=21 jade_version=21.1.6+fabric +# CC: Tweaked (maven.squiddev.cc): compile-only API for the turret base peripheral; the full mod is only in the dev +# runs and on the game test server (1.117.1 is the only version for 1.21.11) +cctweaked_version=1.117.1 diff --git a/versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/advancement/recipes/misc/addon_serial_port.json b/versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/advancement/recipes/misc/addon_serial_port.json new file mode 100644 index 000000000..86383b7a5 --- /dev/null +++ b/versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/advancement/recipes/misc/addon_serial_port.json @@ -0,0 +1,40 @@ +{ + "fabric:load_conditions": [ + { + "condition": "openmodularturrets:module_enabled", + "items": [ + "addon_serial_port" + ] + } + ], + "parent": "minecraft:recipes/root", + "criteria": { + "has_io_bus": { + "conditions": { + "items": [ + { + "items": "openmodularturrets:io_bus" + } + ] + }, + "trigger": "minecraft:inventory_changed" + }, + "has_the_recipe": { + "conditions": { + "recipe": "openmodularturrets:addon_serial_port" + }, + "trigger": "minecraft:recipe_unlocked" + } + }, + "requirements": [ + [ + "has_the_recipe", + "has_io_bus" + ] + ], + "rewards": { + "recipes": [ + "openmodularturrets:addon_serial_port" + ] + } +} \ No newline at end of file diff --git a/versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/recipe/addon_serial_port.json b/versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/recipe/addon_serial_port.json new file mode 100644 index 000000000..9b2c82b5c --- /dev/null +++ b/versions/1.21.11-fabric/src/main/generated/data/openmodularturrets/recipe/addon_serial_port.json @@ -0,0 +1,25 @@ +{ + "fabric:load_conditions": [ + { + "condition": "openmodularturrets:module_enabled", + "items": [ + "addon_serial_port" + ] + } + ], + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "B": "openmodularturrets:io_bus", + "Q": "#c:gems/quartz" + }, + "pattern": [ + " Q ", + "BQB", + " Q " + ], + "result": { + "count": 1, + "id": "openmodularturrets:addon_serial_port" + } +} \ No newline at end of file diff --git a/versions/1.21.11-neoforge/gradle.properties b/versions/1.21.11-neoforge/gradle.properties index 122ce7c36..c0c5c9bda 100644 --- a/versions/1.21.11-neoforge/gradle.properties +++ b/versions/1.21.11-neoforge/gradle.properties @@ -6,5 +6,8 @@ neoforge_version=21.11.48 # FML version range in neoforge.mods.toml (FML 4 = NeoForge 21.x) neoforge_loader_range=[4,) jade_version=21.1.7+neoforge +# CC: Tweaked (maven.squiddev.cc): compile-only API for the turret base peripheral; the full mod is only in the dev +# runs and on the game test server (1.117.1 is the only version for 1.21.11) +cctweaked_version=1.117.1 # Data (recipes, loot tables, tags …) is copied from this node's datagen output, with NeoForge load conditions datagen_from=1.21.11-fabric