From 2f757943835c82be737bf1c1278ffe6fd698ce4a 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 | 5 +- README.md | 2 + build.fabric.gradle.kts | 15 ++ build.forge.gradle.kts | 30 +++ docs/architecture.md | 19 +- docs/id-mapping.md | 2 +- .../client/tooltip/ModuleTooltip.java | 4 + src/gametest/CLAUDE.md | 1 + .../gametest/ComputerControlGameTests.java | 211 ++++++++++++++++++ .../gametest/ComputerCraftGameTests.java | 134 +++++++++++ src/gametest/resources/fabric.mod.json | 4 +- .../java/omtteam/openmodularturrets/CLAUDE.md | 8 +- .../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 +++++++++++++++++ .../datagen/OMTRecipeProvider.java | 10 +- .../entity/projectile/RocketProjectile.java | 6 +- .../platform/fabric/OMTFabric.java | 4 + .../computercraft/FabricComputerCraft.java | 24 ++ .../platform/forge/OMTForge.java | 10 +- .../computercraft/ForgeComputerCraft.java | 36 +++ .../openmodularturrets/registry/ModItems.java | 3 +- src/main/resources/META-INF/mods.toml | 8 + .../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.20.1-fabric/gradle.properties | 3 + .../recipes/misc/addon_serial_port.json | 43 ++++ .../recipes/addon_serial_port.json | 29 +++ versions/1.20.1-forge/gradle.properties | 3 + 41 files changed, 1114 insertions(+), 29 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/forge/computercraft/ForgeComputerCraft.java 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.20.1-fabric/src/main/generated/data/openmodularturrets/advancements/recipes/misc/addon_serial_port.json create mode 100644 versions/1.20.1-fabric/src/main/generated/data/openmodularturrets/recipes/addon_serial_port.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 30d98753a..e145edfd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ Before a release, `./gradlew releaseChangelog` turns *Unreleased* into the relea - The turret item tooltip (with shift) and the Jade tooltip of a turret show its optimal range and its turn rate - Turret API: `TurretStats.Builder.falloff(optimalShare, damageAtMaxRange)` and `turnRate(degreesPerTick)`; `TurretProjectile` has `damage(Entity)`, `damage(float, Entity)`, `damageFactor(…)`, `ampDamage(…)` and `hitPoint(…)` for projectiles with the range falloff - Config: `turrets.aimTolerance` and, in every turret section, `optimalRange`, `falloffDamage` and `turnRate` +- 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: a computer can stop a base's turrets from targeting on their own, so it aims and fires them itself +- CC: Tweaked support: turret bases are the peripheral `turret_base`, with the computer commands of the Serial Port addon. ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index 2d6231247..477ddc805 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,6 +43,8 @@ Core gameplay: - **MixinExtras** (`io.github.llamalad7:mixinextras-forge`), jar-in-jar in the **Forge jar only** (approved by the user on 2026-10-24): Fabric Loader ships it, Forge 1.20.1 does not, and `LivingEntityMixin` needs it. - **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"). - **OMLib** (the user's own library, `../OMLib`, branch `1.20.1`), mounted as the git submodule `omlib` and bundled into every jar (jar-in-jar; requested by the user on 2026-10-27); see §4 "OMLib". +- **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 (on Forge also `-core-api`, as its `-forge-api` module lists no dependencies), never bundled, an optional dependency in the loader metadata (`suggests` on Fabric, an optional dependency in `mods.toml`); the full mod is in the dev runs (`modLocalRuntime`), on the game test servers and in `runenv`. + Gated on `cctweaked_version` in `versions//gradle.properties` (1.121.0: 1.122.0 needs Loom 1.19, this branch has 1.18); the code is loaded behind `isModLoaded("computercraft")`. - Nothing else without asking the user first. No Architectury, no Cloth Config, no Kotlin. @@ -223,7 +225,8 @@ 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** on this branch (OpenComputers: Rebooted belongs to `1.21.1` only; 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; computer control of a base and its turrets, `blockentity/base/BaseComputerTurrets`; the Serial Port addon, `addon_serial_port`), and **CC: Tweaked** is supported on both nodes (added on 2026-11-27, decided by the user): `compat/computercraft/TurretBasePeripheral` (one loader-free class, the peripheral `turret_base`) reuses `BaseComputerCommands`; only its registration is per loader (`platform//computercraft`: `PeripheralLookup` on Fabric, `ForgeComputerCraftAPI.registerPeripheralProvider` on Forge). + OpenComputers: Rebooted belongs to `1.21.1` only. - New APIs (public interfaces for other mods, such as `api/`, and new cross-cutting interfaces inside the mod) are designed step by step with the user: workspace `CLAUDE.md`, "Designing APIs". --- diff --git a/README.md b/README.md index ae617dee4..c68727bbc 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,8 @@ The other Minecraft versions have their own branches: - Uses **Team Reborn Energy** on Fabric, so it works with energy from other Fabric tech mods; the Forge build uses its energy capability (FE) instead - Optional **NEEPMeat** support (Fabric): vascular conduits power turret bases, 1 eJ per energy unit - Optional **Jade** support for turret bases and turrets, on both loaders +- Computer control of turret bases (a Serial Port addon, or tier 5): a computer can aim and fire the turrets itself +- Optional **CC: Tweaked** support (both loaders): turret bases are the peripheral `turret_base`, with the same functions as 1.12.2's computer commands, so a computer finds and controls a base with the Serial Port addon or at tier 5 ## Requirements diff --git a/build.fabric.gradle.kts b/build.fabric.gradle.kts index 51e9f32d1..f8dde1dd0 100644 --- a/build.fabric.gradle.kts +++ b/build.fabric.gradle.kts @@ -65,6 +65,14 @@ tasks.withType().configureEach { doFirst { clientResources.get().asFile.mkdirs() } } +repositories { + // CC: Tweaked comes only from its own maven + exclusiveContent { + forRepository { maven("https://maven.squiddev.cc") { name = "CC-Tweaked" } } + filter { includeGroup("cc.tweaked") } + } +} + dependencies { minecraft("com.mojang:minecraft:$minecraftVersion") mappings(loom.officialMojangMappings()) @@ -81,6 +89,13 @@ 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 -> + modCompileOnly("cc.tweaked:cc-tweaked-$minecraftVersion-fabric-api:$cc") + modLocalRuntime("cc.tweaked:cc-tweaked-$minecraftVersion-fabric:$cc") + } + // NEEPMeat: OMLib's FabricNeepMeatPower lets its vascular network charge the bases. Not bundled, the mod needs // nothing of it; NEEPMeat (with the mods nested in its jar, which Loom leaves out of its remapped copy: // nestedModJars in omlib/build-logic) and GeckoLib (which it requires, also with the library nested in its jar) are diff --git a/build.forge.gradle.kts b/build.forge.gradle.kts index d353da681..b56ebd7a5 100644 --- a/build.forge.gradle.kts +++ b/build.forge.gradle.kts @@ -93,6 +93,22 @@ val localRuntime: Configuration = configurations.create("localRuntime") val modLocalRuntime: Configuration = obfuscation.createRemappingConfiguration(localRuntime) configurations.runtimeClasspath { extendsFrom(localRuntime) } // Not on the GameTest server. +// The same for the game test source set (CC: Tweaked, see dependencies): configurations of their own, so the remapping +// leaves the game test's other dependencies (OMLib) alone +val gametestLocalCompile: Configuration = configurations.create("gametestLocalCompile") +val gametestModLocalCompile: Configuration = obfuscation.createRemappingConfiguration(gametestLocalCompile) +configurations.getByName("gametestCompileOnly").extendsFrom(gametestLocalCompile) +val gametestLocalRuntime: Configuration = configurations.create("gametestLocalRuntime") +val gametestModLocalRuntime: Configuration = obfuscation.createRemappingConfiguration(gametestLocalRuntime) +configurations.getByName("gametestRuntimeOnly").extendsFrom(gametestLocalRuntime) + +repositories { + // CC: Tweaked comes only from its own maven + exclusiveContent { + forRepository { maven("https://maven.squiddev.cc") { name = "CC-Tweaked" } } + filter { includeGroup("cc.tweaked") } + } +} dependencies { annotationProcessor("org.spongepowered:mixin:0.8.5:processor") @@ -127,6 +143,20 @@ dependencies { // Jade plugin (compat/jade, client/compat/jade): optional, not bundled; present in dev runs to try it "modCompileOnly"("maven.modrinth:jade:${property("jade_version")}") modLocalRuntime("maven.modrinth:jade:${property("jade_version")}") + + // CC: Tweaked (optional, not bundled: the peripheral provider in platform/forge/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. Its jars are SRG-named like the mod's own, so they go through the remapping configurations too. + findProperty("cctweaked_version")?.let { cc -> + val mc = property("minecraft_version") + // the Forge API jar has no dependency metadata, so the core API (IPeripheral, @LuaFunction, MethodResult) is named too + "modCompileOnly"("cc.tweaked:cc-tweaked-$mc-core-api:$cc") + "modCompileOnly"("cc.tweaked:cc-tweaked-$mc-forge-api:$cc") + modLocalRuntime("cc.tweaked:cc-tweaked-$mc-forge:$cc") + // the game test (compile: CC's own peripheral lookup, which the API does not have; run: the mod itself) + gametestModLocalCompile("cc.tweaked:cc-tweaked-$mc-forge:$cc") + gametestModLocalRuntime("cc.tweaked:cc-tweaked-$mc-forge:$cc") + } } // The client half of the Jade plugin (client/compat/jade) compiles against it too (remapped, through compileOnly) configurations.named("clientCompileOnly") { extendsFrom(configurations.compileOnly.get()) } diff --git a/docs/architecture.md b/docs/architecture.md index d0fe2ebbc..365e174f4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -66,6 +66,8 @@ This is the only place where the two meet, and the reason the core can be tested | `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) | | `security.SecurityEnvironment` (OMLib) | `security.LevelSecurityEnvironment` (OMLib, with `OMTOwnershipSettings`) | scoreboard teams, operator rights | +| `computer.ComputerTurrets` | `blockentity.base.BaseComputerTurrets` | the turrets on a base's faces: aim, auto fire, forced shot | +| `computer.PlayerNames` | `compat.computercraft.ServerPlayerNames` | a player's UUID by name (online, or a player who joined before), without asking Mojang | The block entities own one core object each and forward to it: `TurretBaseBlockEntity` → `core.base.TurretBaseLogic`, `TurretBlockEntity` → `core.turret.TurretState`, `GeneratorBlockEntity` → `core.generator.GeneratorLogic`. `TurretBaseBlockEntity` also owns the base's `TrustManager` (OMLib's core): it builds it with a change callback that saves and syncs the base, and hands it to the logic, which only reads it. @@ -106,6 +108,7 @@ Packages below `omtteam.openmodularturrets` (main): | `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.item`, `core.settings`, `core.world` | upgrade/addon types, config value types, the world interfaces above | +| `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.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 | | `registry` | registration of blocks, items, block entities, entities, menus, sounds, creative tab; `TurretRegistry` (turret definitions) | @@ -118,7 +121,7 @@ Packages below `omtteam.openmodularturrets` (main): | `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` / `forge`), 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.forge` hold the entrypoints, the implementations and the energy/item adapters, and only compile for their loader | +| `platform` | the loader services shared code calls (`Platform`: `LoaderInfo`, `Fuel`, `Network`, `Menus`, `Energy`); `platform.fabric` / `platform.forge` 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 Forge build converts the Fabric output) | `./gradlew dependencyMap` draws these packages and every import between them as an interactive page. @@ -215,6 +218,20 @@ 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 three layers: + +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`. +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`). + 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 commands (`changeAccessLevel` and `forceShootAllTurrets` as well as the aliases `changeTrustedPlayerAccess` and `forceShootAll`, `getType`) and call `BaseComputerCommands`, 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.forge.computercraft.ForgeComputerCraft` (`ForgeComputerCraftAPI.registerPeripheralProvider`, in the common setup). + `ServerPlayerNames` 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`). + ## 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 459c539a2..1fdfee057 100644 --- a/src/gametest/CLAUDE.md +++ b/src/gametest/CLAUDE.md @@ -29,6 +29,7 @@ The day still passes: a test that needs daylight sets the time itself (`SolarPan - `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; `CamoMenuGameTests` uses it for the camouflage menu and its "Back" to the base GUI. Cast `getBlockEntity` results, which are a plain `BlockEntity` here. +- `ComputerCraftGameTests` (batch `computercraft`) finds the peripheral through each loader's real CC lookup (`PeripheralLookup` on Fabric, CC's `Peripherals.getPeripheral` on Forge, which sees the registered provider) and calls its methods with `ObjectArguments`; CC: Tweaked itself runs on both test servers (`cctweaked_version`; on Forge through the remapped `gametestLocalRuntime` configuration in `build.forge.gradle.kts`). - `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: Forge returns a read-only view of the list, and vanilla's mock players would log in for real, which breaks Forge's login handling. Names of players who are not online go to the server's name cache: the test server has none (not found). 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..781cdf6bf --- /dev/null +++ b/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerControlGameTests.java @@ -0,0 +1,211 @@ +package omtteam.openmodularturrets.gametest; + +//? if forge { +/*import net.minecraftforge.gametest.GameTestHolder; +import net.minecraftforge.gametest.PrefixGameTestTemplate; +import omtteam.openmodularturrets.OMT; +*///?} +import net.minecraft.core.BlockPos; +import net.minecraft.gametest.framework.GameTest; +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}). + */ +//? if forge { +/*@GameTestHolder(OMT.MOD_ID) +@PrefixGameTestTemplate(false) +*///?} +@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..70a0fed96 --- /dev/null +++ b/src/gametest/java/omtteam/openmodularturrets/gametest/ComputerCraftGameTests.java @@ -0,0 +1,134 @@ +package omtteam.openmodularturrets.gametest; + +//? if forge { +/*import net.minecraftforge.gametest.GameTestHolder; +import net.minecraftforge.gametest.PrefixGameTestTemplate; +import omtteam.openmodularturrets.OMT; +*///?} +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 forge { +/*import dan200.computercraft.impl.Peripherals; +*///?} +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.gametest.framework.GameTest; +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). CC's + * own peripheral lookup (what a computer or wired modem asks: {@code PeripheralLookup} on Fabric, {@code Peripherals} + * with the provider registered by {@code ForgeComputerCraft} on Forge) 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}. + */ +//? if forge { +/*@GameTestHolder(OMT.MOD_ID) +@PrefixGameTestTemplate(false) +*///?} +@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 forge { + /*return Peripherals.getPeripheral(helper.getLevel(), 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 7dce8bd6b..6603d37af 100644 --- a/src/gametest/resources/fabric.mod.json +++ b/src/gametest/resources/fabric.mod.json @@ -28,7 +28,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 fea9879f2..aae484238 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; PlayerNames is implemented by compat/computercraft/ServerPlayerNames) ├── 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 @@ -34,9 +35,10 @@ omtteam.openmodularturrets ├── menu/ # TurretBaseMenu, GeneratorMenu ├── network/ # OMTPackets, BasePackets + BasePacketHandler (C2S), RayPacket (S2C) ├── config/ # self-written config (JSON via Gson, OMLib's machinery), no library -├── compat/ # SubLevelCompat (contraption poses, always the identity pose here), ModuleEnabledCondition, jade/ (server half); the porting helpers are in OMLib +├── compat/ # SubLevelCompat (contraption poses, always the identity pose here), ModuleEnabledCondition, jade/ (server half), computercraft/ (the CC: Tweaked peripheral turret_base); the porting helpers are in OMLib ├── mixin/ # LivingEntityMixin ├── platform/ # fabric/, forge/: 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..9695612ba 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 needs an entity as collision context (1.20.1 has no entity-less one); 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..06fc65502 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. + * + * @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, @@ -537,6 +624,7 @@ protected void readData(CompoundTag tag, HolderLookup.Provider registries) { yaw = NbtCompat.getFloat(tag, "Yaw", 0); pitch = NbtCompat.getFloat(tag, "Pitch", 0); active = NbtCompat.getBoolean(tag, "Active", false); + autoFire = NbtCompat.getBoolean(tag, "AutoFire", false); damageAmp = NbtCompat.getBoolean(tag, "DamageAmp", false); if (!renderInitialised) { renderYaw = prevRenderYaw = yaw; @@ -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..451483b7e --- /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).toPath(); + 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..a002bd909 --- /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 Forge; 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/datagen/OMTRecipeProvider.java b/src/main/java/omtteam/openmodularturrets/datagen/OMTRecipeProvider.java index 8ad8e0c71..48ce4a4b6 100644 --- a/src/main/java/omtteam/openmodularturrets/datagen/OMTRecipeProvider.java +++ b/src/main/java/omtteam/openmodularturrets/datagen/OMTRecipeProvider.java @@ -341,7 +341,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") @@ -397,6 +397,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/forge/OMTForge.java b/src/main/java/omtteam/openmodularturrets/platform/forge/OMTForge.java index 05b685a06..835bfa8e2 100644 --- a/src/main/java/omtteam/openmodularturrets/platform/forge/OMTForge.java +++ b/src/main/java/omtteam/openmodularturrets/platform/forge/OMTForge.java @@ -7,6 +7,7 @@ import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @@ -15,6 +16,7 @@ import omtteam.openmodularturrets.OMT; import omtteam.openmodularturrets.api.OMTPlugin; import omtteam.openmodularturrets.entity.projectile.KillCounter; +import omtteam.openmodularturrets.platform.forge.computercraft.ForgeComputerCraft; import omtteam.omlib.registry.RegistrationStep; import omtteam.openmodularturrets.registry.TurretRegistry; import omtteam.openmodularturrets.startup.OMTStartup; @@ -68,12 +70,18 @@ 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 ForgeComputerCraft}, only loaded then). + */ private void onCommonSetup(FMLCommonSetupEvent event) { if (done.size() != steps.size()) { List missing = steps.stream().filter(step -> !done.contains(step)).toList(); throw new IllegalStateException("Registration steps never ran: " + missing); } + if (ModList.get().isLoaded(ForgeComputerCraft.MOD_ID)) { + event.enqueueWork(ForgeComputerCraft::register); + } } private static void onLivingDeath(LivingDeathEvent event) { diff --git a/src/main/java/omtteam/openmodularturrets/platform/forge/computercraft/ForgeComputerCraft.java b/src/main/java/omtteam/openmodularturrets/platform/forge/computercraft/ForgeComputerCraft.java new file mode 100644 index 000000000..244a4f97a --- /dev/null +++ b/src/main/java/omtteam/openmodularturrets/platform/forge/computercraft/ForgeComputerCraft.java @@ -0,0 +1,36 @@ +package omtteam.openmodularturrets.platform.forge.computercraft; + +import dan200.computercraft.api.ForgeComputerCraftAPI; +import net.minecraftforge.common.util.LazyOptional; +import omtteam.openmodularturrets.OMT; +import omtteam.openmodularturrets.blockentity.TurretBaseBlockEntity; +import omtteam.openmodularturrets.compat.computercraft.TurretBasePeripheral; + +/** + * CC: Tweaked on Forge: 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 ForgeComputerCraft { + public static final String MOD_ID = "computercraft"; + + private ForgeComputerCraft() { + } + + /** + * Registers CC's peripheral provider for turret bases, on every side; called at common setup. The peripherals are + * not cached: CC looks a peripheral up again when a neighbouring block changes, and two peripherals of one base + * are equal, so a computer does not detach and attach again. + */ + public static void register() { + ForgeComputerCraftAPI.registerPeripheralProvider((level, pos, side) -> { + if (level.getBlockEntity(pos) instanceof TurretBaseBlockEntity base) { + TurretBasePeripheral peripheral = TurretBasePeripheral.of(base); + if (peripheral != null) { + return LazyOptional.of(() -> peripheral); + } + } + return LazyOptional.empty(); + }); + 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 38d3f7948..d03656243 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/mods.toml b/src/main/resources/META-INF/mods.toml index bb58f0c6d..9c3a904a0 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -38,3 +38,11 @@ mandatory = false versionRange = "*" ordering = "NONE" side = "BOTH" + +# CC: Tweaked: the turret base becomes a peripheral when it is installed +[[dependencies.${mod_id}]] +modId = "computercraft" +mandatory = false +versionRange = "*" +ordering = "NONE" +side = "BOTH" 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 e17d8e43e..2db1155be 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -40,7 +40,8 @@ ], "suggests": { "jade": "*", - "neepmeat": "*" + "neepmeat": "*", + "computercraft": "*" }, "depends": { "fabricloader": ">=${loader_version}", diff --git a/versions/1.20.1-fabric/gradle.properties b/versions/1.20.1-fabric/gradle.properties index 1f8f2b603..8fe464cec 100644 --- a/versions/1.20.1-fabric/gradle.properties +++ b/versions/1.20.1-fabric/gradle.properties @@ -7,3 +7,6 @@ jade_version=11.13.3+fabric # game test server with GeckoLib, which it requires (4.8.4 Fabric) neepmeat_version=0.34.0-beta+1.20.1 geckolib_version=SD2lOScS +# 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.121.0: 1.122.0 is built with Loom 1.19, this project has 1.18) +cctweaked_version=1.121.0 diff --git a/versions/1.20.1-fabric/src/main/generated/data/openmodularturrets/advancements/recipes/misc/addon_serial_port.json b/versions/1.20.1-fabric/src/main/generated/data/openmodularturrets/advancements/recipes/misc/addon_serial_port.json new file mode 100644 index 000000000..2c57ed5cc --- /dev/null +++ b/versions/1.20.1-fabric/src/main/generated/data/openmodularturrets/advancements/recipes/misc/addon_serial_port.json @@ -0,0 +1,43 @@ +{ + "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_io_bus", + "has_the_recipe" + ] + ], + "rewards": { + "recipes": [ + "openmodularturrets:addon_serial_port" + ] + }, + "sends_telemetry_event": false +} \ No newline at end of file diff --git a/versions/1.20.1-fabric/src/main/generated/data/openmodularturrets/recipes/addon_serial_port.json b/versions/1.20.1-fabric/src/main/generated/data/openmodularturrets/recipes/addon_serial_port.json new file mode 100644 index 000000000..4a59f311b --- /dev/null +++ b/versions/1.20.1-fabric/src/main/generated/data/openmodularturrets/recipes/addon_serial_port.json @@ -0,0 +1,29 @@ +{ + "fabric:load_conditions": [ + { + "condition": "openmodularturrets:module_enabled", + "items": [ + "addon_serial_port" + ] + } + ], + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "B": { + "item": "openmodularturrets:io_bus" + }, + "Q": { + "tag": "c:quartz" + } + }, + "pattern": [ + " Q ", + "BQB", + " Q " + ], + "result": { + "item": "openmodularturrets:addon_serial_port" + }, + "show_notification": true +} \ No newline at end of file diff --git a/versions/1.20.1-forge/gradle.properties b/versions/1.20.1-forge/gradle.properties index c7067b093..bb233348b 100644 --- a/versions/1.20.1-forge/gradle.properties +++ b/versions/1.20.1-forge/gradle.properties @@ -12,3 +12,6 @@ jade_version=11.13.3+forge mixinextras_version=0.5.5 # Data (recipes, loot tables, tags …) is copied from this node's datagen output, with Forge load conditions datagen_from=1.20.1-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 (the same version as the Fabric node; its mods.toml accepts Forge [47.1.0,48)) +cctweaked_version=1.121.0