Compare commits

...
Author SHA1 Message Date
jackowes bd1b8a029c Some attempted cleanup before rebase 2026-07-27 21:10:36 -05:00
jackowes 6e3c2c3b31 look controller smoothing and misc. 2026-04-22 00:15:32 -05:00
Jackson Bowes 12493d2a0d Add an inertial easing util function 2026-04-16 15:05:59 -05:00
Jackson Bowes f4b4e63ca1 Quaternion (quote) simple (end quote) spring damper 2026-04-16 13:44:21 -05:00
jackowes 6fc8349a6f new turn interpolation tests 2026-04-16 07:50:52 -05:00
jackowes aa5609c47d wanders and temp changes galore 2026-04-13 20:41:24 -05:00
jackowes 70dc7a319c Bring in a bunch of steering code 2026-04-12 14:13:02 -05:00
jackowes 4ca12aed32 DefendOwner objective and sense 2026-04-12 12:27:25 -05:00
jackowes e564b443f9 Migrate WalkTowardsParentSpeciesTask.kt -> Bigger Brains 2026-04-12 11:25:20 -05:00
jackowes 40a350b8b4 Move over circleAround task to new system. provide debug keybind for the debug ai and highlight the debugged entity. Also comment out some no longer used tasks on old system. 2026-04-11 20:09:40 -05:00
JazzMcNade 664c0c012c Converted PointToSpawn to BiggerBrains 2026-03-24 01:05:07 -05:00
JazzMcNade ed8c7569f9 Update FocusDuringBattle.kt 2026-03-21 18:55:36 -05:00
JazzMcNade e63a7c474f Migrate kick starting flight for flyers over water 2026-03-21 16:38:40 -05:00
Paul f5580fd83b Merge remote-tracking branch 'origin/bigger-brains' into bigger-brains 2026-03-14 11:40:10 +10:00
Paul a31b533b77 Rhyperior's grooving with better transitioning 2026-03-14 11:39:55 +10:00
JazzMcNade 817ea0bff7 Added "canDance" species configuration option 2026-03-10 23:30:12 -05:00
Paul 35977c0724 Rhyperior's grooving 2026-03-10 21:26:02 +10:00
JazzMcNade 7e08a46f28 Dancing Objective WIP 2026-03-10 01:41:32 -05:00
JazzMcNade cc5d63fd11 Port JumpOutOfWaterTask to BiggerBrains 2026-03-08 01:56:47 -06:00
JazzMcNade 065c5388a0 Fix Combee block jail break, more cleanup 2026-03-02 02:03:04 -06:00
JazzMcNade c20203a8e9 more clean up 2026-03-01 22:57:28 -06:00
JazzMcNade 932ebfa563 Clean up 2026-03-01 22:11:31 -06:00
JazzMcNade 0f57bd35de Comments 2026-03-01 22:05:45 -06:00
JazzMcNade d6974452fb Implemented Bee behavior with biggerbrain tech, allow fliers to wander 2026-03-01 22:02:59 -06:00
JazzMcNade 937393b93d Remove old tasks 2026-02-22 20:37:45 -06:00
JazzMcNade 59fceeefc3 Smarter usage of looktracker 2026-02-22 16:06:26 -06:00
JazzMcNade ec7e106efb Item pickup for items too close to path to 2026-02-22 13:33:14 -06:00
JazzMcNade d95c5687b1 Added eatHeldItem Objective, corrections to PickupItem 2026-02-18 01:35:05 -06:00
JazzMcNade 39ef558b9b Pickup item logic 2026-02-15 23:11:03 -06:00
JazzMcNade 11452de369 class name typo 2026-02-09 01:35:25 -06:00
JazzMcNade fb4e5002a3 Migrate sweet berry bush harvesting 2026-02-08 21:44:28 -06:00
JazzMcNade 6dd7a7bc9a respect distraction rules 2026-02-08 13:30:52 -06:00
JazzMcNade ba718561aa MoveToRestingPlace Correction 2026-02-08 02:43:35 -06:00
JazzMcNade 21411d26ac More clean up, added moveToRestingPlace Objective 2026-02-03 00:49:14 -06:00
JazzMcNade 3f6c5ebc96 Sleep blocks movement, Added comfort distractions, Removed null check from StayAfloat 2026-01-29 23:25:12 -06:00
JazzMcNade 0bbdfd2c5e Added Sleeping 2026-01-26 02:28:20 -06:00
JazzMcNade f43b7d3dd7 Cleanup 2026-01-25 20:35:28 -06:00
JazzMcNade 6291ac0e23 Added MoveIntoWaterObjective 2026-01-25 02:50:46 -06:00
JazzMcNade 4f528c855b Created MoveOutOfWater Objective 2026-01-24 23:08:21 -06:00
Paul 29c291fd7a Minor doc change [skip-ci] 2026-01-18 13:28:13 +10:00
Paul 493f71302e Some brain clarification stuff and some docs for adding to the brains 2026-01-18 13:20:03 +10:00
Paul ab5a54f21e Fixed excessive wander chances 2026-01-17 18:25:59 +10:00
Paul 440e2855c0 Swimmers can tread water when not pathing on new brain 2026-01-17 16:43:44 +10:00
Paul 8ebecc4928 Migrated stay afloat task to new brain 2026-01-17 11:24:13 +10:00
Paul 4f0108c8a2 Replaced busy locks with fixations that implement LockFixation 2026-01-16 22:16:54 +10:00
Paul 32cd79baec Improved wandering so they can look around and (rarely) wander while in a herd, fixed look targeting for wandering 2026-01-15 22:25:19 +10:00
Paul a8ac858918 Migrated herding to bigger brain 2026-01-14 21:48:20 +10:00
Paul d46394cb1d Migrated sheep grass eating to bigger brains 2026-01-09 22:44:45 +10:00
Paul d5cc2de7e5 I want a license to kill this pipeline error 2026-01-03 17:03:01 +10:00
Paul a5088cf264 Migrated objective configs into the objective classes, moved OT type class out of the Pokemon file 2026-01-03 16:18:20 +10:00
Paul 6c5fd6ea1c Added draft of new AI system 2025-12-31 23:00:10 +10:00
184 changed files with 10892 additions and 879 deletions
+11
View File
@@ -0,0 +1,11 @@
### Additions
### Changes
- Replaced the entity AI for Pokémon and NPCs with an entirely custom one. Yeah we changed the entity AI in 1.7 too, you're remembering right.
- Improved performance of entity AI.
### Fixes
### Developer
### Molang & Datapacks
@@ -51,14 +51,14 @@ public abstract class BeeOccupantMixin {
if (state.is(BlockTags.BEEHIVES)) {
// position in front of the entrance, face away from the block
var facing = state.getValue(HorizontalDirectionalBlock.FACING);
newPos = pos.relative(facing).getCenter();
newPos = pos.relative(facing).getBottomCenter();
newYaw = facing.toYRot();
if (brain.checkMemory(CobblemonMemories.HIVE_LOCATION, MemoryStatus.REGISTERED)) {
brain.setMemory(CobblemonMemories.HIVE_LOCATION, pos); // This needs to be set in the case that the hive was picked up and moved.
}
} else {
// Block has likely been destroyed
var center = pos.getCenter();
var center = pos.getBottomCenter();
newPos = new Vec3(
center.x + level.random.nextFloat() * 0.6 - 0.3,
center.y + level.random.nextFloat() * 0.6 - 0.3,
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.mixin.client;
import com.cobblemon.mod.common.client.CobblemonClient;
import net.minecraft.client.Minecraft;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(Minecraft.class)
public class AIDebugGlowMixin {
@Inject(method = "shouldEntityAppearGlowing", at = @At("HEAD"), cancellable = true)
public void cobblemon$debugEntityGlow(Entity entity, CallbackInfoReturnable<Boolean> cir) {
if (entity.getId() == CobblemonClient.INSTANCE.getDebuggedEntityId()) {
cir.setReturnValue(true);
}
}
}
@@ -161,11 +161,13 @@ object Cobblemon {
var wallpapers = mutableMapOf<UUID, Set<ResourceLocation>>()
val serverPlayerStructs = mutableMapOf<UUID, ObjectValue<Player>>()
/** Player UUID to entity UUID that they're brain debuggin' */
val serverPlayerDebuggingPokemonBrainEntities = mutableMapOf<UUID, UUID>()
val statistics: CobblemonStats = CobblemonStats
@JvmStatic
val builtinPacks = listOf<CobblemonPack>(
val builtinPacks = listOf(
CobblemonPack(id = "adorncompatibility", name = "Adorn Compatibility", packType = PackType.CLIENT_RESOURCES, activationBehaviour = ResourcePackActivationBehaviour.ALWAYS_ENABLED, neededMods = setOf("adorn")),
CobblemonPack(id = "gyaradosjump", name = "Gyarados Jump Patterns", packType = PackType.CLIENT_RESOURCES, activationBehaviour = ResourcePackActivationBehaviour.DEFAULT_ENABLED),
CobblemonPack(id = "regionbiasforms", name = "Region Bias Forms", packType = PackType.CLIENT_RESOURCES, activationBehaviour = ResourcePackActivationBehaviour.DEFAULT_ENABLED),
@@ -234,6 +236,7 @@ object Cobblemon {
playerDataManager.onPlayerDisconnect(it.player)
RequestManager.onLogoff(it.player)
serverPlayerStructs.remove(it.player.uuid)
serverPlayerDebuggingPokemonBrainEntities.remove(it.player.uuid)
}
PlatformEvents.PLAYER_DEATH.subscribe {
PCLinkManager.removeLink(it.player.uuid)
@@ -12,6 +12,8 @@ import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.ai.CobblemonBehaviour
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.config.task.TaskConfig
import com.cobblemon.mod.common.api.data.JsonDataRegistry
import com.cobblemon.mod.common.api.data.JsonDataRegistry.Companion.JSON_EXTENSION
@@ -26,6 +28,8 @@ import com.cobblemon.mod.common.util.adapters.ExpressionLikeAdapter
import com.cobblemon.mod.common.util.adapters.ExpressionOrEntityVariableAdapter
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.cobblemon.mod.common.util.adapters.MemoryModuleTypeAdapter
import com.cobblemon.mod.common.util.adapters.ObjectiveConfigAdapter
import com.cobblemon.mod.common.util.adapters.SenseConfigAdapter
import com.cobblemon.mod.common.util.adapters.SensorTypeAdapter
import com.cobblemon.mod.common.util.adapters.TaskConfigAdapter
import com.cobblemon.mod.common.util.adapters.TranslatedTextAdapter
@@ -55,6 +59,8 @@ object CobblemonBehaviours : JsonDataRegistry<CobblemonBehaviour> {
.registerTypeAdapter(SensorType::class.java, SensorTypeAdapter)
.registerTypeAdapter(BehaviourConfig::class.java, BehaviourConfigAdapter)
.registerTypeAdapter(TaskConfig::class.java, TaskConfigAdapter)
.registerTypeAdapter(ObjectiveConfig::class.java, ObjectiveConfigAdapter)
.registerTypeAdapter(SenseConfig::class.java, SenseConfigAdapter)
.registerTypeAdapter(
TypeToken.getParameterized(Either::class.java, Expression::class.java, MoLangConfigVariable::class.java).type,
ExpressionOrEntityVariableAdapter
@@ -76,5 +76,6 @@ object CobblemonCommands {
// with a certain system environment variable set
CobblemonInfoCommand.register(dispatcher)
CalculateSeatPositionCommand.register(dispatcher)
DebugCobblemonAICommand.register(dispatcher)
}
}
@@ -15,12 +15,12 @@ import com.cobblemon.mod.common.api.moves.animations.ActionEffectContext
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.ListCodec
import com.mojang.serialization.codecs.PrimitiveCodec
import java.util.Optional
import java.util.UUID
import net.minecraft.core.BlockPos
import net.minecraft.core.GlobalPos
import net.minecraft.core.UUIDUtil
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import java.util.*
object CobblemonMemories {
val memories = mutableMapOf<String, MemoryModuleType<*>>()
@@ -59,12 +59,8 @@ object CobblemonMemories {
@JvmField
val DISABLE_WALK_TO_BERRY_BUSH = register<Boolean>("disable_walk_to_berry_bush")
@JvmField
val TIME_TRYING_TO_REACH_BERRY_BUSH = register<Int>("time_trying_to_reach_berry_bush")
@JvmField
val IS_CONSUMING_ITEM = register<Boolean>("is_consuming_item")
@JvmField
val RECENTLY_ATE_GRASS = register<Boolean>("recently_ate_grass")
@JvmField
val HIVE_LOCATION = register<BlockPos>("hive_location", BlockPos.CODEC)
@JvmField
val HIVE_BLACKLIST = register<List<BlockPos>>("hive_blacklist")
@@ -24,6 +24,8 @@ import com.cobblemon.mod.common.client.net.data.DataRegistrySyncPacketHandler
import com.cobblemon.mod.common.client.net.data.PokemonInteractionsSyncHandler
import com.cobblemon.mod.common.client.net.data.RideSettingsSyncHandler
import com.cobblemon.mod.common.client.net.debug.OpenRidingStatsDebugGUIHandler
import com.cobblemon.mod.common.client.net.debug.S2CUpdateObsAvoidHandler
import com.cobblemon.mod.common.client.net.debug.UpdateTrackedBrainDataHandler
import com.cobblemon.mod.common.client.net.dialogue.DialogueClosedHandler
import com.cobblemon.mod.common.client.net.dialogue.DialogueOpenedHandler
import com.cobblemon.mod.common.client.net.effect.*
@@ -66,7 +68,9 @@ import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyMoveCallba
import com.cobblemon.mod.common.net.messages.client.cooking.SeasoningRegistrySyncPacket
import com.cobblemon.mod.common.net.messages.client.cooking.ToggleCookingPotLidPacket
import com.cobblemon.mod.common.net.messages.client.data.*
import com.cobblemon.mod.common.net.messages.client.debug.ClientboundUpdateObsAvoidPacket
import com.cobblemon.mod.common.net.messages.client.debug.RequestOpenRidingStatsDebugGUIPacket
import com.cobblemon.mod.common.net.messages.client.debug.UpdateTrackedBrainDataPacket
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueClosedPacket
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueOpenedPacket
import com.cobblemon.mod.common.net.messages.client.effect.*
@@ -188,7 +192,11 @@ import com.cobblemon.mod.common.net.serverhandling.storage.party.SwapPartyPokemo
import com.cobblemon.mod.common.net.serverhandling.storage.pc.*
import com.cobblemon.mod.common.net.serverhandling.trade.*
import com.cobblemon.mod.common.util.server
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.Entity
import com.cobblemon.mod.common.mixin.accessor.ChunkMapAccessor
import com.cobblemon.mod.common.mixin.accessor.TrackedEntityAccessor
/**
* Registers Cobblemon network packets.
@@ -211,6 +219,19 @@ object CobblemonNetwork {
fun sendToAllPlayers(packet: NetworkPacket<*>) = sendPacketToPlayers(server()!!.playerList.players, packet)
@JvmStatic
fun sendPacketToPlayers(players: Iterable<ServerPlayer>, packet: NetworkPacket<*>) = players.forEach { sendPacketToPlayer(it, packet) }
fun sendPacketToTrackingPlayers(entity: Entity, packet: NetworkPacket<*>) {
val level = entity.level() as? ServerLevel ?: return
val chunkMap = level.chunkSource.chunkMap
val entityTracker = (chunkMap as ChunkMapAccessor).entityMap[entity.id]
if (entityTracker is TrackedEntityAccessor) {
entityTracker.seenBy.forEach { connection ->
sendPacketToPlayer(connection.player, packet)
}
}
}
val s2cPayloads = generateS2CPacketInfoList()
val c2sPayloads = generateC2SPacketInfoList()
@@ -418,6 +439,7 @@ object CobblemonNetwork {
// Debug / cheats
list.add(PacketRegisterInfo(CalculateSeatPositionsPacket.ID, CalculateSeatPositionsPacket::decode, CalculateSeatPositionsHandler))
list.add(PacketRegisterInfo(ClientboundUpdateObsAvoidPacket.ID, ClientboundUpdateObsAvoidPacket::decode, S2CUpdateObsAvoidHandler))
// Riding
list.add(PacketRegisterInfo(ClientboundUpdateRidingStatePacket.ID, ClientboundUpdateRidingStatePacket::decode, ClientboundUpdateRidingStateHandler))
@@ -425,6 +447,7 @@ object CobblemonNetwork {
// Debug
list.add(PacketRegisterInfo(OpenRidingStatsDebugGUIPacket.ID, OpenRidingStatsDebugGUIPacket::decode, OpenRidingStatsDebugGUIHandler))
list.add(PacketRegisterInfo(UpdateTrackedBrainDataPacket.ID, UpdateTrackedBrainDataPacket::decode, UpdateTrackedBrainDataHandler))
return list
}
@@ -18,6 +18,7 @@ import net.minecraft.resources.ResourceKey
import net.minecraft.world.entity.ai.village.poi.PoiType
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.Blocks
object CobblemonPoiTypes: PlatformRegistry<Registry<PoiType>, ResourceKey<Registry<PoiType>>, PoiType>() {
override val registry: Registry<PoiType> = BuiltInRegistries.POINT_OF_INTEREST_TYPE
@@ -30,6 +31,8 @@ object CobblemonPoiTypes: PlatformRegistry<Registry<PoiType>, ResourceKey<Regist
// TODO after 1.7
// @JvmField
// val INCENSE_SWEET_KEY = createKey("incense_sweet", CobblemonBlocks.INCENSE_SWEET, 0, 1)
@JvmField
val JUKEBOX_KEY = createKey("vanilla_jukebox", Blocks.JUKEBOX, 0, 1)
private fun createKey(string: String, block: Block, maxTickets: Int, validRange: Int ): ResourceKey<PoiType> =
ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, cobblemonResource(string)).also { resourceKey ->
@@ -46,9 +46,6 @@ object CobblemonSensors {
@JvmField
val NEARBY_FLOWER = register("nearby_flower", ::FlowerSensor)
@JvmField
val NEARBY_SWEET_BERRY_BUSH = register("nearby_sweet_berry_bush", ::SweetBerryBushSensor)
@JvmField
val POKEMON_NEARBY_WANTED_ITEM = register("pokemon_nearby_wanted_item", ::PokemonItemSensor)
@@ -12,13 +12,15 @@ import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Objective
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.Sense
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
import com.cobblemon.mod.common.api.molang.ExpressionLike
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addStandardFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.molang.ObjectValue
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
import com.cobblemon.mod.common.entity.MoLangScriptingEntity
import com.cobblemon.mod.common.util.activityRegistry
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
@@ -46,6 +48,9 @@ class BehaviourConfigurationContext {
val memories = mutableSetOf<MemoryModuleType<*>>()
val sensors = mutableSetOf<SensorType<*>>()
val objectives = mutableMapOf<Int, MutableList<Objective>>()
val senses = mutableSetOf<Sense>()
val onAdd = mutableListOf<ExpressionLike>()
fun getOrCreateActivity(activity: Activity): ActivityConfigurationContext {
@@ -68,6 +73,22 @@ class BehaviourConfigurationContext {
this.sensors.addAll(sensors)
}
fun addSenses(vararg senses: Sense) {
addSenses(senses.toList())
}
fun addSenses(senses: Collection<Sense>) {
outer@for (sense in senses) {
for (existingSense in this.senses) {
if (existingSense.merge(sense)) {
continue@outer
}
}
this.senses.add(sense)
this.addMemories(sense.memories)
}
}
fun addOnAddScript(script: ExpressionLike) {
onAdd.add(script)
}
@@ -88,8 +109,23 @@ class BehaviourConfigurationContext {
var brain = entity.brain
// Apply the brain config
if (entity is MoLangScriptingEntity) {
brain = entity.assignNewBrainWithMemoriesAndSensors(dynamic, memories, sensors)
val useBiggerBrain = objectives.isNotEmpty() || senses.isNotEmpty()
brain = entity.assignNewBrainWithMemoriesAndSensors(dynamic, memories, if (useBiggerBrain) emptySet() else sensors)
onAdd.forEach { runtime.resolve(it) }
if (useBiggerBrain) {
val wereDebugging = entity.biggerBrain.debuggingPlayers ?: emptySet()
val biggerBrain = BiggerBrain(entity)
entity.biggerBrain = biggerBrain
addSenses(biggerBrain.senses)
val orderedObjectives = objectives.entries.sortedBy { it.key }.flatMap { it.value }
orderedObjectives.forEach(biggerBrain::registerObjective)
biggerBrain.senses.addAll(senses)
biggerBrain.debuggingPlayers.addAll(wereDebugging)
return
} else {
val biggerBrain = BiggerBrain(entity)
entity.biggerBrain = biggerBrain
}
}
activities.forEach { it.apply(entity) }
brain.setCoreActivities(coreActivities)
@@ -9,44 +9,40 @@
package com.cobblemon.mod.common.api.ai
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.util.getBooleanOrNull
import com.cobblemon.mod.common.util.getDoubleOrNull
import kotlin.math.sqrt
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.PathfinderMob
/**
* Used to maintain some settings around how the entity should wander this tick. The idea is you
* reset this with some script task at priority 0 then some number of steps before it gets to the wander
* tasks you can have other conditional tasks jump in to configure parts of this.
* Used to maintain some settings around how the entity should wander this tick. Anything left null
* will fall back to defaults specified by the logic of the WanderAround objective.
*
* @author Hiroku
* @since July 18, 2025
*/
class CobblemonWanderControl(
var center: WanderCenter? = null,
var maxAttempts: Int = 4, // How many times to try to find a suitable point before giving up on that tick.
var allowLand: Boolean = true,
var allowWater: Boolean = false,
var allowAir: Boolean = false,
var pathCooldownTicks: Int = 20 * 5, // Used to mitigate the cost of pathfinding.
var wanderSpeed: Float = 0.35F,
var maxAttempts: Int? = null, // How many times to try to find a suitable point before giving up on that tick.
var allowLand: Boolean? = null,
var allowWater: Boolean? = null,
var allowAir: Boolean? = null,
var wanderSpeed: Float? = null,
var wanderChanceMultiplier: Float? = null
) {
class WanderCenter(val x: Number, val y: Number, val z: Number, val minRange: Float, val maxRange: Float)
@Transient
val struct: QueryStruct = QueryStruct(hashMapOf())
.addFunction("center_x") { center?.x ?: 0.0 }
.addFunction("center_y") { center?.y ?: 0.0 }
.addFunction("center_z") { center?.z ?: 0.0 }
.addFunction("max_attempts") { maxAttempts.toDouble() }
.addFunction("min_range") { center?.minRange ?: 0.0 }
.addFunction("max_range") { center?.maxRange ?: 0.0 }
.addFunction("allow_land") { if (allowLand) 1.0 else 0.0 }
.addFunction("allow_water") { if (allowWater) 1.0 else 0.0 }
.addFunction("allow_air") { if (allowAir) 1.0 else 0.0 }
.addFunction("path_cooldown_ticks") { pathCooldownTicks.toDouble() }
.addFunction("wander_speed") { wanderSpeed }
.addFunction("center_x") { DoubleValue(center?.x ?: 0.0) }
.addFunction("center_y") { DoubleValue(center?.y ?: 0.0) }
.addFunction("center_z") { DoubleValue(center?.z ?: 0.0) }
.addFunction("max_attempts") { DoubleValue(maxAttempts?.toDouble() ?: 0.0) }
.addFunction("min_range") { DoubleValue(center?.minRange ?: 0.0) }
.addFunction("max_range") { DoubleValue(center?.maxRange ?: 0.0) }
.addFunction("allow_land") { DoubleValue(if (allowLand == true) 1.0 else 0.0) }
.addFunction("allow_water") { DoubleValue(if (allowWater == true) 1.0 else 0.0) }
.addFunction("allow_air") { DoubleValue(if (allowAir == true) 1.0 else 0.0) }
.addFunction("wander_speed") { DoubleValue(wanderSpeed ?: 0.0) }
.addFunction("set_center") { params ->
if (params.params.size < 3) {
throw IllegalArgumentException("set_center requires at least 3 parameters: x, y, z")
@@ -68,26 +64,6 @@ class CobblemonWanderControl(
.addFunction("set_allow_land") { params -> allowLand = params.getBooleanOrNull(0) ?: true }
.addFunction("set_allow_water") { params -> allowWater = params.getBooleanOrNull(0) ?: false }
.addFunction("set_allow_air") { params -> allowAir = params.getBooleanOrNull(0) ?: false }
.addFunction("set_path_cooldown_ticks") { params -> pathCooldownTicks = params.getDoubleOrNull(0)?.toInt() ?: (20 * 5) }
.addFunction("set_wander_speed") { params -> wanderSpeed = params.getDoubleOrNull(0)?.toFloat() ?: 0.35F }
.addFunction("reset") { reset() }
fun isSuitable(position: BlockPos): Boolean {
val center = center ?: return true
val centerPos = BlockPos(center.x.toInt(), center.y.toInt(), center.z.toInt())
val distance = sqrt(centerPos.distSqr(position))
val suitable = distance >= center.minRange && distance <= center.maxRange
return suitable
}
fun reset() {
center = null
allowLand = false
allowWater = false
allowAir = false
pathCooldownTicks = 20 * 5
wanderSpeed = 0.35F
maxAttempts = 4
}
}
@@ -9,9 +9,23 @@
package com.cobblemon.mod.common.api.ai
import com.bedrockk.molang.Expression
import com.bedrockk.molang.ast.NumberExpression
import com.bedrockk.molang.ast.StringExpression
import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.value.DoubleValue
import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.MoLangScriptingEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveDouble
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.resolveString
import com.mojang.datafixers.util.Either
import kotlin.jvm.optionals.getOrNull
import net.minecraft.world.entity.LivingEntity
/**
* The issue in a lot of the behaviour datapacking is that there are times when a property should be exposed to
@@ -31,6 +45,50 @@ import kotlin.jvm.optionals.getOrNull
*/
typealias ExpressionOrEntityVariable = Either<Expression, MoLangConfigVariable>
fun ExpressionOrEntityVariable.asExpression() = map({ it }, { "q.entity.config.${it.variableName}".asExpression() })
fun ExpressionOrEntityVariable.resolveString(runtime: MoLangRuntime) = runtime.resolveString(asExpression())
fun ExpressionOrEntityVariable.resolveBoolean(runtime: MoLangRuntime) = runtime.resolveBoolean(asExpression())
fun ExpressionOrEntityVariable.resolveInt(runtime: MoLangRuntime) = runtime.resolveInt(asExpression())
fun ExpressionOrEntityVariable.resolveDouble(runtime: MoLangRuntime) = runtime.resolveDouble(asExpression())
fun ExpressionOrEntityVariable.resolveFloat(runtime: MoLangRuntime) = runtime.resolveFloat(asExpression())
private fun variable(category: String, name: String, type: MoLangConfigVariable.MoLangVariableType, default: String) = MoLangConfigVariable(
variableName = name,
category = lang("entity.variable.category.$category"),
displayName = lang("entity.variable.$name.name"),
description = lang("entity.variable.$name.desc"),
type = type,
defaultValue = default
)
fun stringVariable(category: String, name: String, default: String) = variable(category = category, name = name, type = MoLangConfigVariable.MoLangVariableType.TEXT, default = default)
fun numberVariable(category: String, name: String, default: Number) = variable(category = category, name = name, type = MoLangConfigVariable.MoLangVariableType.NUMBER, default = default.toString())
fun booleanVariable(category: String, name: String, default: Boolean) = variable(category = category, name = name, type = MoLangConfigVariable.MoLangVariableType.BOOLEAN, default = default.toString())
fun getVariableExpression(name: String) = "q.entity.config.$name".asExpression()
fun resolveBooleanVariable(name: String, runtime: MoLangRuntime) = runtime.resolveBoolean(getVariableExpression(name))
fun checkCondition(runtime: MoLangRuntime, expressionOrEntityVariable: ExpressionOrEntityVariable): Boolean {
return expressionOrEntityVariable.resolveBoolean(runtime)
}
fun ExpressionOrEntityVariable.asSimplifiedExpression(entity: LivingEntity): Expression {
return map(
{ it },
{
if (entity is MoLangScriptingEntity) {
val variable = entity.config.map[it.variableName]
if (variable is DoubleValue) {
return@map NumberExpression(variable.value)
} else if (variable is StringValue) {
return@map StringExpression(variable)
}
}
return@map "q.entity.config.${it.variableName}".asExpression()
}
)
}
/**
* In the case of [ExpressionOrEntityVariable] the right side is the only one that requires visibility for a user,
* this function is a shorthand for finding all of the values in the list that have something to show the user to
@@ -0,0 +1,182 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Objective
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.ObjectiveStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.Sense
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.net.messages.client.debug.UpdateTrackedBrainDataPacket
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.getPlayer
import com.cobblemon.mod.common.util.withQueryValue
import java.util.UUID
import kotlin.collections.mutableListOf
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.MemoryStatus
/**
* A better* version of Minecraft's [net.minecraft.world.entity.ai.Brain] system that makes development more
* straightforward and allows easier debugging.
*
* We could name this thing better.
*
* There are three main principles inside this system:
*
* 1: Senses
*
* Senses are simple ticking objects that are instantiated per entity and are expected to just update memories based
* on properties about the entity or its surroundings. This is an analogue of SensorType from Brains.
*
* 2: Objectives
*
* Objectives are also ticking objects that are instantiated per entity. They represent a goal for the entity and
* run in a fixed order.
*
* 3: Fixations
*
* Fixations are a task that can be set on the brain that represents a more total commitment to a certain task. Only
* a single fixation can be active at a time, and they can be 'distracted' by other objectives or potentially external
* factors.
*
* These can also be debugged using the /debugcobblemonai command while looking at a Pokémon or NPC entity.
*
* *that remains to be seen
*
* @author Hiroku
* @since December 29th, 2025
*/
class BiggerBrain(val entity: LivingEntity) {
val runtime = MoLangRuntime().setup().withQueryValue("entity", entity.asMostSpecificMoLangValue())
val senses = mutableListOf<Sense>()
val objectives = mutableListOf<Objective>()
val observedMemories = mutableMapOf<MemoryModuleType<*>, MutableList<Objective>>()
var fixation: EntityFixation? = null
var debuggingPlayers = mutableSetOf<UUID>()
fun registerObjective(objective: Objective) {
objectives.add(objective)
for (memory in objective.observedMemories) {
val list = this.observedMemories.getOrPut(memory, ::ArrayList)
list.add(objective)
}
}
fun isFixation(fixation: EntityFixation?): Boolean {
return fixation != null && this.fixation == fixation
}
fun sendDebugMessage(message: String) {
debuggingPlayers.forEach {
it.getPlayer()?.sendSystemMessage(message.text())
}
}
fun tick() {
senses.forEach {
it.ticksUntilNextExecution--
if (it.ticksUntilNextExecution <= 0) {
it.tick(entity, this)
}
}
if (fixation?.tick(entity, this) == false) {
fixation = null
}
val objectiveStatuses = mutableMapOf<Objective, ObjectiveStatus>()
val activeObjectiveTags = mutableSetOf<String>()
for (objective in objectives) {
val status = objective.perform(entity, this, activeObjectiveTags)
objectiveStatuses[objective] = status
}
if (debuggingPlayers.isNotEmpty()) {
val state = BiggerBrainState(entity = entity, brain = this, objectiveStatuses = objectiveStatuses)
val packet = UpdateTrackedBrainDataPacket(entity.id, state)
debuggingPlayers.removeIf { uuid ->
val player = uuid.getPlayer()
if (player != null && Cobblemon.serverPlayerDebuggingPokemonBrainEntities[player.uuid] != entity.uuid) {
return@removeIf true
} else {
player?.sendPacket(packet)
}
return@removeIf player == null
}
}
}
fun fixate(fixation: EntityFixation): EntityFixation {
this.fixation = fixation
return fixation
}
fun distract(distraction: Distraction): Boolean {
if (fixation?.canDistract(distraction, entity) != false) {
fixation?.onDistract(distraction, entity)
this.fixation = null
return true
}
return false
}
fun canDistract(distraction: Distraction): Boolean {
return fixation?.canDistract(distraction, entity) != false
}
fun <T> setMemory(memory: MemoryModuleType<T>, value: T, expiry: Long? = null) {
if (expiry != null) {
entity.brain.setMemoryWithExpiry(memory, value, expiry)
} else {
entity.brain.setMemory(memory, value)
}
observedMemories[memory]?.forEach { objective ->
objective.onMemoryChanged(entity, this, memory, value)
}
}
fun <T> setMemoryIfChanged(memory: MemoryModuleType<T>, value: T, expiry: Long? = null) {
if (entity.brain.getMemorySafely(memory).orElse(null) != value) {
setMemory(memory, value, expiry)
}
}
fun <T> eraseMemory(memory: MemoryModuleType<T>) {
entity.brain.eraseMemory(memory)
observedMemories[memory]?.forEach { objective ->
objective.onMemoryChanged(entity, this, memory, null)
}
}
fun <T> eraseMemoryIfPresent(memory: MemoryModuleType<T>) {
if (entity.brain.hasMemoryValue(memory)) {
eraseMemory(memory)
}
}
fun hasMemoryValue(memory: MemoryModuleType<*>): Boolean {
return entity.brain.checkMemory(memory, MemoryStatus.VALUE_PRESENT)
}
fun <T> getMemory(memory: MemoryModuleType<T>): T? {
return entity.brain.getMemorySafely(memory).orElse(null)
}
}
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Objective
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.ObjectiveStatus
import kotlin.reflect.jvm.jvmName
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.world.entity.LivingEntity
/**
* A DTO of sorts that is sent to debugging players to keep them informed about the state of an entity's Cobblemon AI.
*
* @author Hiroku
* @since December 29th, 2025
*/
class BiggerBrainState(
val senses: List<SenseState>,
val objectives: List<ObjectiveState>,
val fixation: String? = null
) {
class SenseState(val className: String, val ticksUntilNextExecution: Int) {
fun encode(buffer: FriendlyByteBuf) {
buffer.writeUtf(className)
buffer.writeInt(ticksUntilNextExecution)
}
companion object {
fun decode(buffer: FriendlyByteBuf): SenseState {
return SenseState(buffer.readUtf(), buffer.readInt())
}
}
}
class ObjectiveState(val description: String, val status: ObjectiveStatus) {
fun encode(buffer: FriendlyByteBuf) {
buffer.writeUtf(description)
buffer.writeEnum(status)
}
companion object {
fun decode(buffer: FriendlyByteBuf): ObjectiveState {
return ObjectiveState(buffer.readUtf(), buffer.readEnum(ObjectiveStatus::class.java))
}
}
}
constructor(entity: LivingEntity, brain: BiggerBrain, objectiveStatuses: Map<Objective, ObjectiveStatus>): this(
senses = brain.senses.map { SenseState(className = it::class.simpleName ?: it::class.jvmName, it.ticksUntilNextExecution) },
objectives = objectiveStatuses.entries.map { ObjectiveState(it.key.getDescription(entity), it.value) },
fixation = brain.fixation?.getDescription(entity)
)
fun encode(buffer: FriendlyByteBuf) {
buffer.writeCollection(senses) { _, sense -> sense.encode(buffer) }
buffer.writeCollection(objectives) { _, objective -> objective.encode(buffer) }
buffer.writeNullable(fixation) { _, fixation -> buffer.writeUtf(fixation) }
}
companion object {
fun decode(buffer: FriendlyByteBuf): BiggerBrainState {
val senses = buffer.readList { SenseState.decode(it) }
val objectives = buffer.readList { ObjectiveState.decode(it) }
val fixation = buffer.readNullable { buffer.readUtf() }
return BiggerBrainState(senses, objectives, fixation)
}
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.BlockPosTracker
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.behavior.PositionTracker
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.phys.Vec3
/**
* A trivial wrapper around an entity and a position tracker to make the entity look at the position each tick.
*
* @author Hiroku
* @since December 29th, 2025
*/
class LookingTracker(val entity: PathfinderMob, val lookTarget: PositionTracker) {
companion object {
fun forTargetEntity(entity: PathfinderMob, target: LivingEntity, trackEyeHeight: Boolean = true): LookingTracker {
return LookingTracker(entity, EntityTracker(target, trackEyeHeight))
}
fun fromNavigationPathOrWalkTarget(entity: PathfinderMob, walkTarget: WalkTarget): LookingTracker {
val destinationPoint = entity.navigation.path?.endNode?.asVec3() ?: walkTarget.target.currentPosition()
return LookingTracker(entity, BlockPosTracker(destinationPoint.add(0.0, entity.eyeHeight.toDouble(), 0.0)))
}
}
fun tick() {
entity.lookControl.setLookAt(lookTarget.currentPosition())
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
/**
* A simple enum representing the status of a movement action.
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class MovementStatus {
/** Represents when the entity is still en route to the destination. */
PENDING,
/** Represents when the entity has successfully reached the destination. */
COMPLETED,
/**
* Represents when the entity has failed to reach the destination. This can be due to
* a change in surroundings or taking too long or all sorts of things.
*/
FAILED
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* A wrapping around logic that maintains an entity's journey towards a specific destination. Mainly used by fixations
* to keep track of when pathing is done, and whether it failed or succeeded. Can also be told to stop to do any
* necessary clean up. Implemented only by [RegularMovementTracker] which has me questioning if it should be an interface
* or just a simple class like the [LookingTracker].
*
* @author Hiroku
* @since December 29th, 2025
*/
interface MovementTracker {
val walkTarget: WalkTarget
/** The last known status of this movement tracker. */
var lastStatus: MovementStatus
/** Performs a tick of movement tracking logic. Returns the current [MovementStatus]. */
fun tick(): MovementStatus
/** Stops the movement and does any necessary clean up. */
fun stop()
}
@@ -0,0 +1,209 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.pokemon.ai.OmniPathNodeMaker
import com.cobblemon.mod.common.util.deleteNode
import java.util.function.Predicate
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.ai.util.DefaultRandomPos
import net.minecraft.world.level.pathfinder.Path
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.phys.Vec3
/**
* The default movement tracker used for tracking movement towards a [WalkTarget]. This is pretty much entirely
* just the code for FollowWalkTargetTask from Minecraft brain stuff.
*
* @author Hiroku
* @since December 29th, 2025
*/
class RegularMovementTracker(
val entity: PathfinderMob,
override val walkTarget: WalkTarget
) : MovementTracker {
companion object {
/**
* Attempts to create a tracker for the given entity and target. Returns null if the path
* couldn't be created.
*/
fun attempt(entity: PathfinderMob, walkTarget: WalkTarget): RegularMovementTracker? {
return RegularMovementTracker(entity, walkTarget).takeIf { it.isValid }
}
}
var isValid = false
private set
var started = false
override var lastStatus: MovementStatus = MovementStatus.PENDING
private var path: Path? = null
private var lastKnownTargetPos: BlockPos? = null
init {
val hasReached = hasReached(entity, walkTarget)
if (!hasReached && hasFinishedPath(entity, walkTarget)) {
this.lastKnownTargetPos = walkTarget.target.currentBlockPosition()
isValid = true
} else {
lastStatus = MovementStatus.FAILED
}
}
override fun tick(): MovementStatus {
val path = path
val status = if (path == null || isTargetSpectator(walkTarget)) {
stop(entity)
MovementStatus.FAILED
} else if (hasReached(entity, walkTarget)) {
stop(entity)
MovementStatus.COMPLETED
} else if (started && entity.navigation.isDone) {
stop(entity)
MovementStatus.FAILED
} else {
if (!started) {
startOnPath(entity)
started = true
}
tick(entity)
MovementStatus.PENDING
}
this.lastStatus = status
return status
}
fun startOnPath(entity: PathfinderMob) {
entity.brain.setMemory(MemoryModuleType.PATH, this.path)
entity.navigation.moveTo(this.path, walkTarget.speedModifier.toDouble())
}
override fun stop() {
stop(entity)
}
fun stop(entity: PathfinderMob) {
entity.navigation.stop()
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.brain.eraseMemory(MemoryModuleType.PATH)
}
private fun tick(entity: PathfinderMob) {
val path = entity.navigation.path
if (this.path !== path) {
this.path = path
this.startOnPath(entity)
}
if (path != null && lastKnownTargetPos != null) {
if (walkTarget.target.currentBlockPosition().distSqr(lastKnownTargetPos!!) > 4.0) {
// The target has moved away from where we are pathing, try pathing to its new location
if (hasFinishedPath(entity, walkTarget)) {
lastKnownTargetPos = walkTarget.target.currentBlockPosition()
startOnPath(entity)
} else {
// Uh oh, we can't get closer? Maybe next tick will be better?
}
}
}
}
private fun withNodeFilter(
entity: PathfinderMob,
nodeFilter: Predicate<PathType>,
block: () -> Unit) {
val nodeEvaluator = entity.navigation.nodeEvaluator
if (nodeEvaluator is OmniPathNodeMaker) {
nodeEvaluator.nodeFilter = nodeFilter
block()
nodeEvaluator.nodeFilter = Predicate { true }
} else {
block()
}
}
private fun hasFinishedPath(entity: PathfinderMob, walkTarget: WalkTarget): Boolean {
val blockPos = walkTarget.target.currentBlockPosition()
this.path = generatePath(entity, walkTarget, blockPos)
val hasReached = hasReached(entity, walkTarget)
if (!hasReached && path == null) {
// Desperate attempt to still path to the destination by going somewhere in the vicinity
val vec3d = DefaultRandomPos.getPosTowards(
entity,
10,
7,
Vec3.atBottomCenterOf(blockPos),
Math.PI / 2F
)
if (vec3d != null) {
this.path = generatePath(entity, walkTarget, BlockPos.containing(vec3d))
return this.path != null
}
} else if (!hasReached) {
return true
}
return false
}
private fun generatePath(
entity: PathfinderMob,
walkTarget: WalkTarget,
target: BlockPos
): Path? {
var path: Path? = null
if (walkTarget is CobblemonWalkTarget) {
withNodeFilter(
entity = entity,
nodeFilter = walkTarget.nodeTypeFilter,
) {
var resolvedPath = entity.navigation.createPath(
walkTarget.target.currentBlockPosition(),
0
)
if (resolvedPath != null) {
// A CobblemonWalkTarget may have a destinationNodeTypeFilter, which is used to filter the end node of the path.
// Mainly useful for when the thing setting the target did it a bit crudely or didn't know how far the navigator
// was going to get, and might land on something that is technically traversable by the entity but it doesn't
// fit the intention of the task. Example, a little bird wandering might end up finishing on a flight node,
// but it doesn't really want to fly in place so it'd prefer not ending there.
while (resolvedPath.endNode?.type?.let { walkTarget.destinationNodeTypeFilter(it) } == false) {
resolvedPath.deleteNode(resolvedPath.nodeCount - 1)
}
if (resolvedPath.nodeCount == 0) {
resolvedPath = null
}
}
path = resolvedPath
}
} else {
path = entity.navigation.createPath(target, 0)
}
return path
}
private fun hasReached(entity: PathfinderMob, walkTarget: WalkTarget): Boolean {
return walkTarget.target.currentBlockPosition().distManhattan(entity.blockPosition()) <= walkTarget.closeEnoughDist
}
fun isTargetSpectator(target: WalkTarget): Boolean {
val lookTarget = target.target
return if (lookTarget is EntityTracker) {
lookTarget.entity.isSpectator
} else {
false
}
}
}
@@ -0,0 +1,223 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.cobblemon.mod.common.api.ai.CobblemonWanderControl.WanderCenter
import com.cobblemon.mod.common.api.ai.config.task.WanderTaskConfig.Companion.MAX_LOOK_DOWN_DISTANCE
import com.cobblemon.mod.common.entity.OmniPathingEntity
import com.cobblemon.mod.common.entity.ai.CobblemonRandomSurfacePos
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import kotlin.math.ceil
import kotlin.math.sqrt
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.BehaviorUtils
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.ai.util.HoverRandomPos
import net.minecraft.world.entity.ai.util.LandRandomPos
import net.minecraft.world.level.material.Fluids
import net.minecraft.world.level.pathfinder.PathType
/**
* A type of wandering behaviour for an entity. I'm not sure if we keep this.
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class WanderType(
val isValid: (PathfinderMob) -> Boolean,
val choosePosition: (PathfinderMob, minimumHeight: Int, maximumHeight: Int, horizontalRange: Int, verticalRange: Int) -> BlockPos?,
val createWalkTarget: (PathfinderMob, position: BlockPos, avoidsTargetingAir: Boolean, speedMultiplier: Float) -> WalkTarget?,
) {
WATER(
isValid = { it.isInWater },
choosePosition = choosePosition@{ entity, _, _, horizontalRange, verticalRange ->
var pos = BehaviorUtils.getRandomSwimmablePos(entity, horizontalRange, verticalRange)?.let(BlockPos::containing)
?: return@choosePosition null
// Move target pos down so that we don't move out of water too much
val requiredDepth = ceil(0.5 + entity.eyeHeight)
// Get the current depth of the block
var depth = 1
var testPos = pos.above()
var blockState = entity.level().getBlockState(testPos)
while (blockState.fluidState.type == Fluids.WATER) {
depth++
testPos = testPos!!.above()
blockState = entity.level().getBlockState(testPos)
}
if (depth < requiredDepth) {
// Iterate down until we reach the desired min depth or we reach a non water block
pos = pos.below()
blockState = entity.level().getBlockState(pos)
while (blockState.fluidState.type == Fluids.WATER && depth < requiredDepth && pos.y > entity.level().minBuildHeight) {
depth++
pos = pos.below()
blockState = entity.level().getBlockState(pos)
}
}
return@choosePosition if (depth < requiredDepth) null else pos
},
createWalkTarget = { _, pos, _, speedMultiplier ->
CobblemonWalkTarget(
pos = pos,
nodeTypeFilter = { it == PathType.WATER || it == PathType.WATER_BORDER },
speedModifier = speedMultiplier,
completionRange = 0
)
}
),
LAND(
isValid = { entity -> !entity.isInWater && !entity.isInLava },
choosePosition = choosePosition@{ entity, minimumHeight, maximumHeight, horizontalRange, verticalRange ->
val targetVec = when {
maximumHeight != -1 -> {
HoverRandomPos.getPos(
entity,
horizontalRange,
verticalRange,
entity.random.nextFloat() - 0.5,
entity.random.nextFloat() - 0.5,
Math.PI.toFloat(),
maximumHeight,
minimumHeight
)
}
entity.isUnderWater && entity.canBreatheUnderwater() && !((entity as OmniPathingEntity).canSwimInWater()) -> {
BehaviorUtils.getRandomSwimmablePos(
entity,
horizontalRange,
verticalRange
)
}
entity is OmniPathingEntity && (entity.canWalkOnWater() || entity.canWalkOnLava()) -> {
CobblemonRandomSurfacePos.getPos(
entity,
horizontalRange,
verticalRange
)
}
else -> {
LandRandomPos.getPos(
entity,
horizontalRange,
verticalRange
)
}
}
val pos = targetVec?.let(BlockPos::containing) ?: return@choosePosition null
LAND.applyHeightConstraints(pos, minimumHeight, maximumHeight, entity.level() as ServerLevel)
},
createWalkTarget = { entity, pos, avoidsTargetingAir, speedMultiplier ->
CobblemonWalkTarget(
pos = pos,
speedModifier = speedMultiplier,
completionRange = 0,
nodeTypeFilter = { nodeType ->
entity.canBreatheUnderwater() || nodeType !in listOf(
PathType.WATER,
PathType.WATER_BORDER
)
},
destinationNodeTypeFilter = { nodeType ->
!avoidsTargetingAir || nodeType !in listOf(
PathType.OPEN
)
}
)
}
)
;
fun generateWalkTarget(
entity: PathfinderMob,
maxAttempts: Int,
center: WanderCenter?,
minimumHeight: Int,
maximumHeight: Int,
horizontalRange: Int,
verticalRange: Int,
avoidTargetingAir: Boolean,
speedMultiplier: Float
): WalkTarget? {
var attempts = 0
var pos: BlockPos? = null
while (attempts++ < maxAttempts && pos == null) {
pos = choosePosition(entity, minimumHeight, maximumHeight, horizontalRange, verticalRange)
?: return null
if (!isSuitable(center, pos)) {
pos = null
}
}
if (pos == null) {
return null
}
return createWalkTarget(entity, pos, avoidTargetingAir, speedMultiplier)
}
private fun isSuitable(center: WanderCenter?, position: BlockPos): Boolean {
val center = center ?: return true
val centerPos = BlockPos(center.x.toInt(), center.y.toInt(), center.z.toInt())
val distance = sqrt(centerPos.distSqr(position))
val suitable = distance >= center.minRange && distance <= center.maxRange
return suitable
}
private fun applyHeightConstraints(
pos: BlockPos,
minimumHeight: Int,
maximumHeight: Int,
world: ServerLevel
): BlockPos {
if (minimumHeight <= 0 && maximumHeight == -1) {
return pos // It ain't a hoverer
}
val block = world.getBlockState(pos)
val altitude = if (!block.isAir) {
0
} else {
(1..MAX_LOOK_DOWN_DISTANCE).firstOrNull {
val newPos = pos.below(it)
if (!world.getBlockState(newPos).isAir) {
return@firstOrNull true
} else if (newPos.y <= world.minBuildHeight) {
// Don't adjust downward into the void (Mostly if we're in the end)
// This doesn't stop fliers from wandering off end islands,
// but it does stop them from diving directly into the void.
return pos
}
return@firstOrNull false
} ?: MAX_LOOK_DOWN_DISTANCE
}
if (altitude > maximumHeight && maximumHeight >= 0) {
val excess = altitude - maximumHeight
val excessFromMinimum = altitude - minimumHeight
val correction = world.random.nextIntBetweenInclusive(excess, excessFromMinimum)
return pos.atY(pos.y - correction)
} else if (altitude < minimumHeight && minimumHeight >= 0) {
val deficit = minimumHeight - altitude
val deficitFromMaximum = maximumHeight - altitude
val correction = world.random.nextIntBetweenInclusive(deficit, deficitFromMaximum)
return pos.atY(pos.y + correction)
} else {
return pos
}
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.distraction
import net.minecraft.world.damagesource.DamageSource
/**
* Something that may distract an entity from its current fixation. The majority of fixations
* will rely on the types of distraction to determine if they should be distracted.
*
* @author Hiroku
* @since December 29th, 2025
*/
open class Distraction(val types: Set<DistractionType>) {
constructor(vararg types: DistractionType) : this(types.toSet())
val isIdleBoredom = DistractionType.IDLE_BOREDOM in types
val isForce = DistractionType.FORCE in types
val isComfort = DistractionType.COMFORT in types
val isDamage = DistractionType.DAMAGE in types
fun hasAnyOf(vararg distractionTypes: DistractionType): Boolean {
return distractionTypes.any { it in types }
}
companion object {
val FORCE = Distraction(DistractionType.FORCE)
}
}
/** Reusable basic distraction for a COMFORT type of distraction. */
val comfortDistraction = Distraction(DistractionType.COMFORT)
/** Reusable basic distraction for an IDLE_BOREDOM type of distraction. */
val idleBoredomDistraction = Distraction(DistractionType.IDLE_BOREDOM)
open class HurtDistraction(val damageSource: DamageSource) : Distraction(DistractionType.DAMAGE)
@@ -0,0 +1,28 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
/**
* A categorisation of distractions that can be attempted on an [EntityFixation].
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class DistractionType {
/** Represents a distraction that the entity is not particularly motivated by but would consider doing out of boredom. */
IDLE_BOREDOM,
/** Represents a distraction that is for the sake of the entity's comfort because it isn't comfortable where it is. */
COMFORT,
/** Represents a distraction motivated by being hurt. */
DAMAGE,
/** A forceful distraction. Just about everything should respect this but it's conceivable that something not. */
FORCE,
}
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import net.minecraft.world.entity.LivingEntity
/**
* A fixation that rejects all non-force distractions and does nothing, lasting until
* the provided [condition] is no longer true.
*
* @author Hiroku
* @since January 16th, 2026
*/
open class ConditionalLockFixation(
val description: String,
val condition: () -> Boolean
): EntityFixation, LockFixation {
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
override fun getDescription(entity: LivingEntity) = description
override fun tick(entity: LivingEntity, brain: BiggerBrain) = condition()
}
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import net.minecraft.world.entity.LivingEntity
/**
* A fixation that rejects all non-force distractions and does nothing for some
* number of ticks.
*
* @author Hiroku
* @since January 16th, 2026
*/
open class DurationLockFixation(
val description: String,
var durationTicks: Int
) : EntityFixation, LockFixation {
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
override fun getDescription(entity: LivingEntity) = description.replace("{ticks}", durationTicks.toString())
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
return --durationTicks > 0
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import net.minecraft.world.entity.LivingEntity
/**
* An entity's fixation, representing a task that takes a central role in the entity's behaviour
* and excludes all other possible fixations.
*
* The role of the fixation is to do an action which is the primary focus of the entity at that time,
* and which may be distracted from under some circumstances. An entity may be fixated on moving from
* A to B, and then be distracted upon being hurt. Or maybe it's an attack fixation, in which case
* damage doesn't distract it at all.
*
* The difference between a fixation and an objective is that objectives are capable of running in parallel,
* and a fixation may even be in the pursuit of an objective, but the fixation is central.
*
* @author Hiroku
* @since December 28th, 2025
*/
interface EntityFixation {
/** Returns true if the given distraction can stop this fixation. */
fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean
/** Notifies the fixation that it has been distracted by the given distraction so it can do clean up. */
fun onDistract(distraction: Distraction, entity: LivingEntity) {}
/** Continues doing whatever the fixation does. Returns true if the fixation should continue. */
fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean
/** Gets a current description of the fixation for the debug screen. */
fun getDescription(entity: LivingEntity): String
}
@@ -0,0 +1,18 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
/**
* Represents a fixation that blocks battling, capture, etc. for Pokémon. This is
* used to control the isBusy property on Pokémon.
*
* @author Hiroku
* @since January 16th, 2026
*/
interface LockFixation
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import net.minecraft.world.entity.LivingEntity
/**
* A simple fixation that uses both a looking tracker and a movement tracker.
*
* @author Hiroku
* @since December 29th, 2025
*/
open class LookAndMoveFixation(
/** Distraction types that will be respected. */
val distractionTypes: Set<DistractionType>,
/** How to describe the fixation in the debug overlay. */
val description: String,
override val lookingTracker: LookingTracker,
override val movementTracker: MovementTracker,
val onMovementComplete: ((entity: LivingEntity, brain: BiggerBrain) -> Unit)? = null
): EntityFixation, LookingTrackerFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = description
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.types.any(distractionTypes::contains)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
val continueFixation = tickMovementFixation() == MovementStatus.PENDING
if (!continueFixation && onMovementComplete != null) {
onMovementComplete.invoke(entity, brain)
}
return continueFixation
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
/**
* Applied to fixations which may have looking associated with them. This is useful
* in the case that an objective needs to know if the current fixation intends on (or is)
* controlling their looking direction.
*
* Example: An objective that makes Pokémon bob their heads up and down while music is playing.
* Said objective would not warrant a full fixation, but would still like to ensure that the
* current fixation does not intend on using a looking tracker.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface LookingTrackerFixation {
val lookingTracker: LookingTracker?
}
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
/**
* Applied to fixations which may have movement associated with them. This is useful
* in the case that an objective needs to know if the current fixation intends on (or is)
* controlling their movement.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface MovementTrackerFixation {
/** The movement tracker at the moment. */
val movementTracker: MovementTracker?
/** Ticks the movement tracker in a way that skips finalized movement trackers. */
fun tickMovementFixation(): MovementStatus? {
val movementTracker = this.movementTracker ?: return null
return if (movementTracker.lastStatus != MovementStatus.PENDING) {
movementTracker.lastStatus
} else {
movementTracker.tick()
}
}
}
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.WanderAround
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.entity.pokemon.extensions.orientEntityToTravel
import com.cobblemon.mod.common.entity.pokemon.extensions.steerToTarget
import com.cobblemon.mod.common.util.math.geometry.toRadians
import net.minecraft.util.Mth
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.phys.Vec3
import kotlin.math.abs
/**
* Fixation for random wander (Essentially Reynolds wander for steered entities
*
* @author Jackson
* @since April 13th, 2026
*/
class RandomWanderFixation(
val objective: WanderAround,
val pokemonEntity: PokemonEntity,
val moveControl: PokemonMoveControl,
val center: Vec3 = pokemonEntity.position(),
val boundarySize: Double = 25.0,
val durationTicks: Int = 400
) : EntityFixation, MovementTrackerFixation {
override val movementTracker: MovementTracker? = null
var ticksRemaining = durationTicks
// Wander state — pulled from BoidsMoveControl.wander()
var currHorzWander = 0.0
var currVertWander = 0.0
val wanderDisp = 5.0
override fun getDescription(entity: LivingEntity) = "Reynolds wandering ($ticksRemaining ticks left)"
override fun canDistract(distraction: Distraction, entity: LivingEntity) =
distraction.isForce || distraction.isComfort || distraction.isDamage
override fun onDistract(distraction: Distraction, entity: LivingEntity) {}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) return false
if (ticksRemaining-- <= 0) return false
val maxSpeed = moveControl.getTopSpeed(pokemonEntity) * 2.0
entity.setFlying(true)
// TODO: deadlock detection — track position delta over last ~40 ticks, if average movement < threshold mark objective.deadlock = true and return false
applyWanderForce(maxSpeed)
applyBoundaryForce(maxSpeed)
// moveControl.mob.speed = 0f // This is done in PokemonMoveControl however it needs to be done
// moveControl.mob.setZza(0f)
// moveControl.mob.setXxa(0f)
// pokemonEntity.setDiscardFriction(true)
// pokemonEntity.orientEntityToTravel(1.0f)
return true
}
private fun applyWanderForce(maxSpeed: Double) {
val maxForce = 0.2
val normVec = if (pokemonEntity.deltaMovement.lengthSqr() > 0.0001) {
pokemonEntity.lookAngle.normalize()
} else {
Vec3(
kotlin.random.Random.nextDouble(-1.0, 1.0),
kotlin.random.Random.nextDouble(-1.0, 1.0),
kotlin.random.Random.nextDouble(-1.0, 1.0)
).normalize()
// pokemonEntity.lookAngle.normalize()
}
var wanderOff = normVec
val currPitchS = Mth.atan2(wanderOff.y, wanderOff.horizontalDistance())
if (currPitchS >= 0.85f || currPitchS <= -0.85f) {
currVertWander = 0.0
}
wanderOff = wanderOff.xRot(currVertWander.toFloat().toRadians())
wanderOff = wanderOff.yRot(currHorzWander.toFloat().toRadians())
val centerDistance = 4.0
val wanderCenter = pokemonEntity.position().add(normVec.scale(centerDistance))
val wanderRadius = 0.2
val wanderPoint = wanderCenter.add(wanderOff.scale(wanderRadius))
currVertWander = Mth.wrapDegrees(kotlin.random.Random.nextDouble(-wanderDisp, wanderDisp) + currVertWander)
currHorzWander = Mth.wrapDegrees(kotlin.random.Random.nextDouble(-wanderDisp, wanderDisp) + currHorzWander)
val wanderForce = pokemonEntity.steerToTarget(wanderPoint, maxSpeed, maxForce)
pokemonEntity.deltaMovement = pokemonEntity.deltaMovement.add(wanderForce)
}
private fun applyBoundaryForce(maxSpeed: Double) {
val maxBoundaryForce = 0.01
val halfSize = 12 //boundarySize / 2.0
val entityPos = pokemonEntity.position()
val posFromCenter = entityPos.subtract(center)
val xExceed = maxOf(0.0, abs(posFromCenter.x) - halfSize)
val yExceed = maxOf(0.0, abs(posFromCenter.y) - halfSize)
val zExceed = maxOf(0.0, abs(posFromCenter.z) - halfSize)
if (xExceed == 0.0 && yExceed == 0.0 && zExceed == 0.0) return
var desiredPos = entityPos.add(pokemonEntity.deltaMovement)
if (xExceed != 0.0) desiredPos = Vec3(center.x, desiredPos.y, desiredPos.z)
if (yExceed != 0.0) desiredPos = Vec3(desiredPos.x, center.y, desiredPos.z)
if (zExceed != 0.0) desiredPos = Vec3(desiredPos.x, desiredPos.y, center.z)
val correctiveForce = desiredPos.subtract(entityPos).normalize().scale(maxSpeed)
var steer = correctiveForce.subtract(pokemonEntity.deltaMovement)
if (steer.length() > maxBoundaryForce) steer = steer.normalize().scale(maxBoundaryForce)
pokemonEntity.deltaMovement = pokemonEntity.deltaMovement.add(steer)
}
}
@@ -0,0 +1,168 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Swim or fly in a circle objective
* TODO: this may just need to be included in [WanderAround]?
*/
class CircleAround(
val poseTypes: Set<PoseType>,
val minTurnAngleDegrees: Float,
val maxTurnAngleDegrees: Float,
val verticalSpeed: Float,
val speed: Float,
val minDurationTicks: Int = 60,
val maxDurationTicks: Int = 180
) : Objective {
var chosenTurnAngle = 0F
var chosenDuration = 0
var fixation: EntityFixation? = null
var moveControl: PokemonMoveControl? = null
override fun getDescription(entity: LivingEntity) = "Circling"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (entity.getCurrentPoseType() !in poseTypes) {
return ObjectiveStatus.BLOCKED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED // Since this doesn't distract anything then if the brain is fixated at all we are blocked
}
// TODO: should this not be able to distract anything? relates to the above fixation comment
// if (!brain.distract(idleBoredomDistraction)) {
// return ObjectiveStatus.BLOCKED
// }
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.navigation.stop()
// Gather a random turn angle and random duration
this.chosenTurnAngle = entity.random.nextFloat() * (maxTurnAngleDegrees - minTurnAngleDegrees) + minTurnAngleDegrees
if (entity.random.nextBoolean()) {
chosenTurnAngle = -chosenTurnAngle
}
chosenDuration = entity.random.nextIntBetweenInclusive(minDurationTicks, maxDurationTicks)
// Grab moveControl off the entity to use during fixation
this.moveControl = entity.moveControl as PokemonMoveControl?
// Become fixated
fixation = brain.fixate(
CircleAroundFixation(
this,
null,
chosenDuration
)
)
return ObjectiveStatus.ACTIVE //TODO: should this have a cooldown? Currently just having it as the pure fallback and able to be distracted by anything. I guess fishes should always swim... probably not but I'll sort that later
}
class CircleAroundFixation(
val objective: CircleAround,
override val movementTracker: MovementTracker?,
var timer: Int
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Circling around at ${this.objective.chosenTurnAngle} degrees for ${this.timer} more ticks"
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
super.onDistract(distraction, entity)
objective.moveControl?.stopBanking()
}
// can be distracted by anything
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
objective.moveControl?.startBanking(
forwardBlocksPerTick = objective.speed,
upwardsBlocksPerTick = objective.verticalSpeed,
rightDegreesPerTick = objective.chosenTurnAngle,
durationTicks = 2 //TODO: is it odd we have the check in multiple spots?
)
this.timer--
if (this.timer < 0 || (entity as PokemonEntity).getCurrentPoseType() !in objective.poseTypes) {
objective.moveControl?.stopBanking()
return false
}
return true
}
}
class Config : ObjectiveConfig {
val poseTypes: Set<PoseType> = setOf(PoseType.FLY, PoseType.HOVER)
val minAngularVelocityDegrees: ExpressionOrEntityVariable = Either.left("0.0".asExpression())
val maxAngularVelocityDegrees: ExpressionOrEntityVariable = Either.left("1.0".asExpression())
val speed: ExpressionOrEntityVariable = Either.left("0.6".asExpression())
val verticalSpeed: ExpressionOrEntityVariable = Either.left("0.0".asExpression())
val minDurationTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDurationTicks: ExpressionOrEntityVariable = Either.left("180".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minAngularVelocityDegrees,
maxAngularVelocityDegrees,
speed,
verticalSpeed,
minDurationTicks,
maxDurationTicks
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
if (entity !is PokemonEntity) return null
return CircleAround(
poseTypes = poseTypes,
minTurnAngleDegrees = minAngularVelocityDegrees.resolveFloat(behaviourConfigurationContext.runtime),
maxTurnAngleDegrees = maxAngularVelocityDegrees.resolveFloat(behaviourConfigurationContext.runtime),
speed = speed.resolveFloat(behaviourConfigurationContext.runtime),
verticalSpeed = verticalSpeed.resolveFloat(behaviourConfigurationContext.runtime),
minDurationTicks = minDurationTicks.resolveInt(behaviourConfigurationContext.runtime),
maxDurationTicks = maxDurationTicks.resolveInt(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,158 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.net.messages.client.effect.RunPosableMoLangPacket
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Stops movement and plays a Pokemon's dance animation, if available.
*
*/
class Dance(
val minDuration: Int,
val danceChance: Float
) : Objective {
var fixation: EntityFixation? = null
var remainingCooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Dancing"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
}
// Only dance if we feel like it
val danceMemory = brain.getMemory(MemoryModuleType.DANCING) ?: false
if (!danceMemory || entity.random.nextFloat() > danceChance || entity.ticksLived < 4 * 20) {
return ObjectiveStatus.INACTIVE
}
if (!brain.distract(idleBoredomDistraction)) {
return ObjectiveStatus.BLOCKED
}
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.navigation.stop()
// Become fixated
fixation = brain.fixate(
DanceFixation(
this,
null,
minDuration
)
)
return ObjectiveStatus.ACTIVE
}
class DanceFixation(
val objective: Dance,
override val movementTracker: MovementTracker?,
val minDuration: Int
) : EntityFixation, MovementTrackerFixation {
var ticksSinceStarted = 0
override fun getDescription(entity: LivingEntity) = "Dancing"
override fun tickMovementFixation() = MovementStatus.PENDING
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
super.onDistract(distraction, entity)
stopDancing(entity)
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
if (distraction.isIdleBoredom) {
return false
}
return true
}
fun stopDancing(entity: LivingEntity) {
val pokemon = entity as? PokemonEntity ?: return
pokemon.setBehaviourFlag(PokemonBehaviourFlag.DANCING, false)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (ticksSinceStarted == 0) { // Makes make me want a Start() for fixations
val pokemon = entity as? PokemonEntity ?: return false
RunPosableMoLangPacket(entity.id, setOf("v.bpm = 100;")).sendToPlayersAround(entity, 64.0)
pokemon.setBehaviourFlag(PokemonBehaviourFlag.DANCING, true)
}
ticksSinceStarted++
if (ticksSinceStarted > minDuration && !entity.brain.getMemorySafely(MemoryModuleType.DANCING).orElse(false)) {
stopDancing(entity)
return false
}
return true
}
}
class Config : ObjectiveConfig {
var danceChance: ExpressionOrEntityVariable = Either.left("1/2".asExpression())
var minDuration: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minDuration,
danceChance
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val minDuration = minDuration.resolveInt(behaviourConfigurationContext.runtime)
val danceChance = danceChance.resolveFloat(behaviourConfigurationContext.runtime)
return Dance(
minDuration,
danceChance)
}
}
companion object {
private const val ticksBetweenAttempts = 20
}
}
@@ -0,0 +1,76 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* Defend owner objective
* Handles transition of nearest visible attacker to a valid attack target when wanting to defend owner.
* Could possibly be more configurable in the future
*/
class DefendOwner() : Objective {
var cooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Following parent species"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) return ObjectiveStatus.INVALID
if (brain.hasMemoryValue(MemoryModuleType.ATTACK_TARGET)) return ObjectiveStatus.INACTIVE
val attacker = brain.getMemory(CobblemonMemories.NEAREST_VISIBLE_ATTACKER)
?: return ObjectiveStatus.INACTIVE
brain.setMemory(MemoryModuleType.ATTACK_TARGET, attacker)
return ObjectiveStatus.ACTIVE
}
class Config : ObjectiveConfig {
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
emptyList<MoLangConfigVariable>()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective? {
if (entity !is PokemonEntity) return null
return DefendOwner()
}
}
}
@@ -0,0 +1,147 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.pokemon.feature.FlagSpeciesFeature
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.level.GameRules
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.state.predicate.BlockStatePredicate
/**
* The baa's eat the graa's
*
* @author Hiroku
* @since January 9th, 2025
*/
class EatGrass(
val cooldownTicks: Int,
val eatGrassChance: Float
) : Objective {
var fixation: EntityFixation? = null
val grassPredicate = BlockStatePredicate.forBlock(Blocks.GRASS_BLOCK)
var remainingCooldownTicks = cooldownTicks
override fun getDescription(entity: LivingEntity) = "Eat grass"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (!brain.canDistract(comfortDistraction)) {
return ObjectiveStatus.BLOCKED
} else if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
val world = entity.level() as ServerLevel
entity.pokemon.getFeature<FlagSpeciesFeature>(DataKeys.HAS_BEEN_SHEARED)?.enabled?.takeIf { it } ?: run {
return ObjectiveStatus.INACTIVE
}
if (world.random.nextFloat() > eatGrassChance) {
return ObjectiveStatus.ACTIVE
} else {
val blockPos = entity.blockPosition()
// Are we not even on a grass block? Alright don't bother
if (!grassPredicate.test(world.getBlockState(blockPos)) && !world.getBlockState(blockPos.below()).`is`(Blocks.GRASS_BLOCK)) {
return ObjectiveStatus.ACTIVE
}
fixation = brain.fixate(EatGrassFixation(this))
entity.playAnimation("eat")
world.broadcastEntityEvent(entity, 10.toByte())
return ObjectiveStatus.FIXATED
}
}
class EatGrassFixation(val objective: EatGrass) : EntityFixation {
var timer = 40
override fun getDescription(entity: LivingEntity) = "Eating grass"
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isComfort || distraction.isDamage || distraction.isForce
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
timer--
if (timer <= 0) {
entity as PokemonEntity
val world = entity.level() as ServerLevel
val blockPos = entity.blockPosition()
if (objective.grassPredicate.test(world.getBlockState(blockPos)) ) {
if (world.gameRules.getBoolean(GameRules.RULE_MOBGRIEFING)) {
world.destroyBlock(blockPos, false)
}
entity.ate()
objective.remainingCooldownTicks = objective.cooldownTicks
} else if (world.getBlockState(blockPos.below()).`is`(Blocks.GRASS_BLOCK)) {
val below = blockPos.below()
if (world.gameRules.getBoolean(GameRules.RULE_MOBGRIEFING)) {
world.levelEvent(2001, below, Block.getId(Blocks.GRASS_BLOCK.defaultBlockState()))
world.setBlock(below, Blocks.DIRT.defaultBlockState(), 2)
}
entity.ate()
objective.remainingCooldownTicks = objective.cooldownTicks
}
}
return timer > 0
}
}
class Config : ObjectiveConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("400".asExpression())
var eatGrassChance: ExpressionOrEntityVariable = Either.left("1/400".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
cooldownTicks,
eatGrassChance
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
val eatGrassChance = eatGrassChance.resolveFloat(behaviourConfigurationContext.runtime)
return if (eatGrassChance == 0F) {
null
} else {
EatGrass(
cooldownTicks = cooldownTicks,
eatGrassChance = eatGrassChance
)
}
}
}
}
@@ -0,0 +1,170 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.PickupItem.Companion.dropItem
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.PokemonItemSense.Companion.PICKUP_ITEMS
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.ai.ObtainableItem
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.findMatchingEntry
import com.cobblemon.mod.common.util.getObjectList
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolve
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.core.component.DataComponents
import net.minecraft.core.particles.ItemParticleOption
import net.minecraft.core.particles.ParticleTypes
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.server.level.ServerLevel
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.item.ItemStack
/**
* Eat the currently held item, apply the effect, and drop if it's an undesired item
*
* @author JazzMcNade
* @since February 16th, 2026
*/
class EatHeldItem(
val cooldownTicks: Int,
val pickupItems: List<ObtainableItem>
) : Objective {
var fixation: EntityFixation? = null
var remainingCooldownTicks = cooldownTicks
override fun getDescription(entity: LivingEntity) = "Eat Held Item"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
}
val itemStack: ItemStack = entity.pokemon.heldItem()
if (canEat(itemStack, entity)) {
fixation = brain.fixate(EatHeldItemFixation(this))
remainingCooldownTicks = 120
return ObjectiveStatus.FIXATED
}
return ObjectiveStatus.INACTIVE
}
fun canEat(item: ItemStack, entity: PokemonEntity): Boolean {
return item.has(DataComponents.FOOD) || pickupItems.findMatchingEntry(entity.registryAccess(), item)?.onUseEffect != null
}
class EatHeldItemFixation(val objective: EatHeldItem) : EntityFixation {
var ticksRemaining = 40
override fun getDescription(entity: LivingEntity) = "Eating held item"
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isComfort || distraction.isDamage || distraction.isForce
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val world = entity.level()
if (entity is PokemonEntity && entity.isAlive) {
val itemStack: ItemStack = entity.pokemon.heldItem()
val itemConfig = objective.pickupItems.findMatchingEntry(entity.registryAccess(), itemStack)
if (objective.canEat(itemStack, entity)) {
if (ticksRemaining < 0) {
var resultItemStack = itemStack.finishUsingItem(world, entity)
val configuredReturnItem = itemConfig?.returnItem
resultItemStack = if (configuredReturnItem != ItemStack.EMPTY) ItemStack(BuiltInRegistries.ITEM.get(configuredReturnItem))
else if (resultItemStack.item == itemStack.item)
ItemStack.EMPTY // Items that aren't normally edible return themselves
else
resultItemStack
entity.pokemon.swapHeldItem(resultItemStack)
val onUseEffect = itemConfig?.onUseEffect
if (onUseEffect != null) {
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
mainThreadRuntime.resolve(onUseEffect)
}
if (itemConfig != null && itemConfig.fullnessValue > 0) {
entity.pokemon.feedPokemon(itemConfig.fullnessValue, false)
}
// Check if the result item is something that should be dropped
resultItemStack = entity.pokemon.heldItem()
if ((objective.pickupItems.findMatchingEntry(entity.registryAccess(), resultItemStack)?.pickupPriority ?: 0) < 0) {
// Drop item
resultItemStack = entity.pokemon.swapHeldItem(resultItemStack)
if (!resultItemStack.isEmpty && !entity.level().isClientSide) {
dropItem(entity, resultItemStack)
}
}
return false
} else if ((itemConfig?.fullnessValue ?: 0) > 0 && entity.random.nextFloat() < 0.4f) {
ticksRemaining--
entity.playSound(entity.getEatingSound(itemStack), 1.0f, 1.0f)
world.broadcastEntityEvent(entity, 45.toByte())
spawnFoodParticles(entity, itemStack)
}
}
return true
}
return false
}
private fun spawnFoodParticles(entity: LivingEntity, itemStack: ItemStack) {
val serverLevel = entity.level() as ServerLevel
//TODO: Figure out how to this with snowstorm so we can use mouth/face/head locators
// The issue as of this writing is we don't have a clean way to utilize the item texture for the particle in snowstorm
serverLevel.sendParticles(
ItemParticleOption(ParticleTypes.ITEM, itemStack),
entity.x, entity.y + 0.5, entity.z, // particle position (centered on entity)
5, // count
0.1, 0.1, 0.1, // x, y, z offset spread
0.05 // speed
)
}
}
class Config : ObjectiveConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("120".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
cooldownTicks
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
var pickupItems = emptyList<ObtainableItem>()
if (entity is PokemonEntity) {
pickupItems = entity.config.getObjectList<ObtainableItem>(PICKUP_ITEMS)
}
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return EatHeldItem(
cooldownTicks = cooldownTicks,
pickupItems = pickupItems
)
}
}
}
@@ -0,0 +1,302 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.entity.pokemon.extensions.steerToTarget
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.math.geometry.toRadians
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.phys.Vec3
import java.util.UUID
import kotlin.math.cos
/**
* Flock or School to stay cool
* This objective and fixation is currently not working as intended and needs modification or scrapped.
*/
class Flock(
val poseTypes: Set<PoseType> = setOf(PoseType.FLY, PoseType.HOVER, PoseType.SWIM, PoseType.FLOAT),
val separationWeight: Float = 0.8f,
val alignmentWeight: Float = 0.6f,
val cohesionWeight: Float = 0.6f,
val neighborRadius: Float = 8f,
val maxForce: Double = 0.02
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Flocking"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) return ObjectiveStatus.INVALID
val moveControl = entity.moveControl as? PokemonMoveControl ?: return ObjectiveStatus.INVALID
if (brain.isFixation(fixation)) {
activeObjectiveTags.add(Objective.OBJECTIVE_TAG_WANDERING)
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
}
if (entity.getCurrentPoseType() !in poseTypes) return ObjectiveStatus.INACTIVE
val leaderUUID = brain.getMemory(CobblemonMemories.HERD_LEADER)
?: if (brain.hasMemoryValue(CobblemonMemories.HERD_SIZE)) entity.uuid.toString() else return ObjectiveStatus.INACTIVE
if (!brain.distract(idleBoredomDistraction)) return ObjectiveStatus.BLOCKED
fixation = brain.fixate(FlockFixation(this, entity, leaderUUID, moveControl))
return ObjectiveStatus.FIXATED
}
inner class FlockFixation(
val objective: Flock,
val pokemonEntity: PokemonEntity,
val leaderUUID: String,
val moveControl: PokemonMoveControl,
) : EntityFixation, MovementTrackerFixation {
override val movementTracker: MovementTracker? = null
var maxSpeed = moveControl.getTopSpeed(pokemonEntity).toFloat()
var maxForce = 0.02 // TODO: possibly move these to configs
var flockNumber = 0
override fun getDescription(entity: LivingEntity) = "Flocking with ${this.flockNumber} friends"
override fun canDistract(distraction: Distraction, entity: LivingEntity) =
distraction.isForce || distraction.isComfort || distraction.isDamage
override fun onDistract(distraction: Distraction, entity: LivingEntity) {}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) return false
if (entity.getCurrentPoseType() !in objective.poseTypes) return false
val isLeader = leaderUUID == pokemonEntity.uuid.toString()
if (!isLeader && brain.getMemory(CobblemonMemories.HERD_LEADER) != leaderUUID) return false
this.maxSpeed = moveControl.getTopSpeed(pokemonEntity).toFloat() * 1.0f // TODO: can this be made to be static per species? and then friction calcs are done elsewhere?
this.maxForce = 0.02
val flockMates = getFlockMates(brain)
this.flockNumber = flockMates.size
val force = computeBoidForce(flockMates)
applyBoidForce(force)
return true
}
private fun getFlockMates(brain: BiggerBrain): List<PokemonEntity> {
val isLeader = leaderUUID == pokemonEntity.uuid.toString()
val followers = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
?.findAll {
it is PokemonEntity && it != pokemonEntity &&
it.brain.getMemorySafely(CobblemonMemories.HERD_LEADER).orElse(null) == leaderUUID
}
?.filterIsInstance<PokemonEntity>()
?: emptyList()
if (isLeader) return followers
val level = pokemonEntity.level() as? ServerLevel
val leader = level?.getEntity(UUID.fromString(leaderUUID)) as? PokemonEntity
return if (leader != null) followers + leader else followers
}
/**
* Compute all forces involved in classic boid behaviour.
* Each returns a Vec3 force, scale by respective weight, sum them
*/
private fun computeBoidForce(flockMates: List<PokemonEntity>): Vec3 {
// TODO: implement separation, alignment, cohesion
var totalForce = Vec3.ZERO
val separationForce = this.separation(flockMates)?.scale(objective.separationWeight.toDouble())
separationForce?.let { totalForce = totalForce.add(it) }
val alignmentForce = this.alignment(flockMates)?.scale(objective.alignmentWeight.toDouble())
alignmentForce?.let { totalForce = totalForce.add(it) }
val cohesionForce = this.cohesion(flockMates)?.scale(objective.cohesionWeight.toDouble())
cohesionForce?.let { totalForce = totalForce.add(it) }
val vel = pokemonEntity.deltaMovement
val dir = if (vel.lengthSqr() > 0.0001) vel.normalize() else Vec3(
-kotlin.math.sin(Math.toRadians(pokemonEntity.yRot.toDouble())),
0.0,
kotlin.math.cos(Math.toRadians(pokemonEntity.yRot.toDouble()))
)
val pointAhead = pokemonEntity.position().add(dir.scale(4.0))
val forwardForce = pokemonEntity.steerToTarget(pointAhead, maxSpeed.toDouble(), maxForce)
//totalForce = totalForce.add(dir.scale(maxForce * 1.5))
return totalForce
}
private fun separation(flockMates: List<PokemonEntity>): Vec3? {
var seperationVec: Vec3? = null
// Gather the total separation vec of all close entities
flockMates.forEach { boid ->
val toTargetVec = pokemonEntity.position().subtract(boid.position())
val desiredSeperation = boid.bbWidth * 2.0 // Base the seperation distance on the model width
val currDist = toTargetVec.length()
if (currDist < desiredSeperation) {
if (seperationVec == null) seperationVec = Vec3.ZERO
// Make the seperation force inversely proprotional to the serperation distance
// Also, scale the force by the bbwidth of the model so
seperationVec = seperationVec.add(toTargetVec.normalize().scale((1.0 - (currDist / desiredSeperation)) ))
}
}
if (seperationVec != null) {
//if (seperationVec.length() > this.maxSpeed) seperationVec = seperationVec.normalize().scale(this.maxSpeed)
seperationVec = seperationVec.normalize().scale(this.maxSpeed.toDouble())
seperationVec = seperationVec.subtract(pokemonEntity.deltaMovement)
if (seperationVec.length() > this.maxForce) {
seperationVec = seperationVec.normalize().scale(this.maxForce)
}
}
return seperationVec
}
private fun alignment(flockMates: List<PokemonEntity>): Vec3? {
val neighborDist = objective.neighborRadius
var summedVel: Vec3? = null
var alignmentVec: Vec3? = null
var boidCount = 0
// Gather the average position of the boid
flockMates.forEach { boid ->
val vecToOther = boid.position().subtract(this.pokemonEntity.position())
val distToOther = vecToOther.length()
val widthOfViewInDeg = 360
val isInSightLine = pokemonEntity.deltaMovement.normalize().dot(vecToOther) > cos((widthOfViewInDeg / 2.0).toRadians())
if (isInSightLine && distToOther < neighborDist) {
if (summedVel == null) summedVel = Vec3.ZERO
summedVel = summedVel.add(boid.deltaMovement.normalize())
boidCount++
}
}
if (summedVel != null) {
// Get the average vel/alignment by dividing by the number of boids sampled
val averageVel = summedVel.scale(1.0 / boidCount)
//alignmentVec = if (averageVel.length() > this.maxSpeed) averageVel.normalize().scale(this.maxSpeed) else averageVel
alignmentVec = averageVel.normalize().scale(this.maxSpeed.toDouble())
alignmentVec = alignmentVec.subtract(pokemonEntity.deltaMovement)
if (alignmentVec.length() > this.maxForce) {
alignmentVec = alignmentVec.normalize().scale(this.maxForce)
}
}
return alignmentVec
}
private fun cohesion(flockMates: List<PokemonEntity>): Vec3? {
var summedPos: Vec3? = null
var cohesionVec: Vec3? = null
var boidCount = 0
val cohesionRadius = objective.neighborRadius
// Gather the average position of the boid
flockMates.forEach { boid ->
val vecToOther = boid.position().subtract(this.pokemonEntity.position())
val distToOther = vecToOther.length()
val widthOfViewInDeg = 360
val isInSightLine = pokemonEntity.deltaMovement.normalize().dot(vecToOther) > cos((widthOfViewInDeg / 2.0).toRadians())
if (isInSightLine && distToOther < cohesionRadius) { // Only use members that are within a certain radius and eyeline
if (summedPos == null) summedPos = Vec3.ZERO
summedPos = summedPos.add(boid.position())
boidCount++
}
}
if (summedPos != null) {
// Get the average position by dividing by the number of boids sampled
var averagePos = summedPos.scale(1.0 / boidCount)
// Further weight the entire boid towards the leaders position 50/50 all and leader
val isLeader = leaderUUID == pokemonEntity.uuid.toString()
if (!isLeader) {
val level = pokemonEntity.level() as? ServerLevel
val leader = level?.getEntity(UUID.fromString(leaderUUID)) as? PokemonEntity
leader?.let { averagePos = averagePos.add(it.position()).scale(0.5) }
}
// Get the vector towards that average position and scale
cohesionVec = averagePos.subtract(pokemonEntity.position())
//if (cohesionVec.length() > this.maxSpeed) cohesionVec = cohesionVec.normalize().scale(this.maxSpeed)
cohesionVec = cohesionVec.normalize().scale(this.maxSpeed.toDouble())
cohesionVec = cohesionVec.subtract(pokemonEntity.deltaMovement)
if (cohesionVec.length() > this.maxForce) {
cohesionVec = cohesionVec.normalize().scale(this.maxForce)
}
}
return cohesionVec
}
private fun applyBoidForce(force: Vec3) {
var finalForce = force
if (finalForce.length() < maxForce) {
finalForce = finalForce.normalize().scale(maxForce)
}
pokemonEntity.deltaMovement = pokemonEntity.deltaMovement.add(finalForce)
}
}
class Config : ObjectiveConfig {
val poseTypes: Set<PoseType> = setOf(PoseType.FLY, PoseType.HOVER, PoseType.SWIM, PoseType.FLOAT)
val separationWeight: ExpressionOrEntityVariable = Either.left("0.8".asExpression())
val alignmentWeight: ExpressionOrEntityVariable = Either.left("0.6".asExpression())
val cohesionWeight: ExpressionOrEntityVariable = Either.left("0.6".asExpression())
val neighborRadius: ExpressionOrEntityVariable = Either.left("8.0".asExpression())
val maxForce: ExpressionOrEntityVariable = Either.left("0.02".asExpression())
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
listOf(separationWeight, alignmentWeight, cohesionWeight, neighborRadius, maxForce).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective? {
if (entity !is PokemonEntity) return null
return Flock(
poseTypes = poseTypes,
separationWeight = separationWeight.resolveFloat(behaviourConfigurationContext.runtime),
alignmentWeight = alignmentWeight.resolveFloat(behaviourConfigurationContext.runtime),
cohesionWeight = cohesionWeight.resolveFloat(behaviourConfigurationContext.runtime),
neighborRadius = neighborRadius.resolveFloat(behaviourConfigurationContext.runtime),
maxForce = maxForce.resolveFloat(behaviourConfigurationContext.runtime).toDouble()
)
}
}
}
@@ -0,0 +1,244 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.HurtDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LockFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveBoolean
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.scheduling.afterOnServer
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* An objective that ensures the entity, whether it's a PokemonEntity or an NPCEntity, will pay attention to its
* opponents in battle. They will not move, and will look at its opponents. For Pokémon, they will focus on the
* targeted opponent if one exists; otherwise, they will randomly look at one of their opponent Pokémon. For NPCs,
* they will randomly look at one of their opponent Pokémon.
*
* If the entity gets hurt and [stopBattleIfHurt] is true, this objective stops the battle.
*
* @author Hiroku
* @since December 29th, 2025
*/
class FocusDuringBattle(
var stopBattleIfHurt: Boolean = true,
var minDurationTicks: Int = 40,
var maxDurationTicks: Int = 80
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Look at battle opponents"
override fun perform(entity: LivingEntity, brain: BiggerBrain, activeObjectiveTags: MutableSet<String>): ObjectiveStatus {
if (entity !is NPCEntity && entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
}
if (stopBattleIfHurt && brain.hasMemoryValue(MemoryModuleType.HURT_BY)) {
if (brain.isFixation(fixation)) {
if (entity is PokemonEntity) {
entity.battle?.stop()
} else if (entity is NPCEntity) {
entity.battleIds.mapNotNull { BattleRegistry.getBattle(it) }.forEach { it.stop() }
}
brain.distract(Distraction.FORCE)
}
return ObjectiveStatus.INACTIVE
}
val isInBattle = isInBattle(entity)
if (brain.isFixation(fixation)) {
if (isInBattle) {
// Ok this is fine
return ObjectiveStatus.FIXATED
} else {
// Alright my work here is done, going back to inactive.
fixation = null
brain.fixation = null
return ObjectiveStatus.INACTIVE
}
} else if (!isInBattle) {
// Ok we don't need to do anything
fixation = null
return ObjectiveStatus.INACTIVE
} else {
// We need to start focusing
if (brain.distract(Distraction.FORCE)) {
fixation = if (entity is NPCEntity) NPCFocusFixation(this) else PokemonFocusFixation(this)
// Handle kick starting flight for flying pokemon over water
if (entity is PokemonEntity && entity.exposedForm.behaviour.moving.fly.canFly) {
if (entity.ticksLived >= 0 && entity.navigation.isAirborne(entity.level(), entity.blockPosition())) {
// Let flyers fly in battle if they're in the air
entity.setBehaviourFlag(PokemonBehaviourFlag.FLYING, true)
afterOnServer(0.1F) {
entity.navigation.moveTo(entity.x, entity.y + 0.2, entity.z, 1.0)
}
}
}
brain.fixation = fixation
return ObjectiveStatus.FIXATED
} else {
return ObjectiveStatus.BLOCKED
}
}
}
override fun <T> onMemoryChanged(entity: LivingEntity, brain: BiggerBrain, memory: MemoryModuleType<T>, value: T?) {
if (brain.isFixation(fixation) && memory == MemoryModuleType.HURT_BY && value != null && stopBattleIfHurt) {
brain.distract(HurtDistraction(value as DamageSource))
}
}
fun isInBattle(entity: LivingEntity): Boolean {
return when (entity) {
is PokemonEntity -> entity.isBattling
is NPCEntity -> entity.isInBattle()
else -> false
}
}
class NPCFocusFixation(val objective: FocusDuringBattle) : EntityFixation, LookingTrackerFixation {
override var lookingTracker: LookingTracker? = null
var ticksUntilReacquireTarget: Int = 0
override fun getDescription(entity: LivingEntity): String {
return if (lookingTracker == null) {
"Looking for an opponent Pokémon to look at"
} else {
"Looking at targeted or opponent Pokémon"
}
}
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
fun acquireLookTarget(entity: NPCEntity, brain: BiggerBrain) {
val battlingPokemon = brain.getMemory(CobblemonMemories.BATTLING_POKEMON) ?: return
val randomBattlingPokemon = battlingPokemon.randomOrNull()?.let { (entity.level() as ServerLevel).getEntity(it) }
if (randomBattlingPokemon != null) {
lookingTracker = LookingTracker(entity, EntityTracker(randomBattlingPokemon, true))
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is NPCEntity) {
return false
}
val battlingPokemon = brain.getMemory(CobblemonMemories.BATTLING_POKEMON) ?: return false
val lookingTracker = lookingTracker
if (lookingTracker != null && lookingTracker.entity.uuid !in battlingPokemon) {
this.lookingTracker = null
ticksUntilReacquireTarget = 0
}
if (ticksUntilReacquireTarget <= 0) {
acquireLookTarget(entity, brain)
ticksUntilReacquireTarget = (objective.minDurationTicks..objective.maxDurationTicks).random()
} else {
ticksUntilReacquireTarget--
}
lookingTracker?.tick()
return true
}
}
class PokemonFocusFixation(val objective: FocusDuringBattle) : EntityFixation, LookingTrackerFixation, LockFixation {
var ticksUntilReacquireTarget: Int = 0
override var lookingTracker: LookingTracker? = null
override fun getDescription(entity: LivingEntity): String {
return if (lookingTracker == null) {
"Looking for an opponent Pokémon to look at"
} else {
"Looking at targeted or opponent Pokémon"
}
}
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) {
return false
}
val battlingPokemon = brain.getMemory(CobblemonMemories.BATTLING_POKEMON) ?: return false
val targetedBattlePokemon = brain.getMemory(CobblemonMemories.TARGETED_BATTLE_POKEMON)
val lookingTracker = lookingTracker
// If there is a targetedBattlePokemon then that is the highest priority, and we should not look away
// Otherwise, look at one of the entities for a while and occasionally reacquire the target.
if (targetedBattlePokemon != null && (lookingTracker == null || lookingTracker.entity.uuid != targetedBattlePokemon)) {
// We should be targeting the targetedBattlePokemon
val targetedPokemon = (entity.level() as ServerLevel).getEntity(targetedBattlePokemon) ?: return false
this.lookingTracker = LookingTracker(entity, EntityTracker(targetedPokemon, true))
ticksUntilReacquireTarget = (objective.minDurationTicks..objective.maxDurationTicks).random()
} else if (targetedBattlePokemon == null && ticksUntilReacquireTarget <= 0) {
// Choose someone to look at
val randomBattlingPokemon = battlingPokemon.randomOrNull()?.let { (entity.level() as ServerLevel).getEntity(it) }
if (randomBattlingPokemon != null) {
this.lookingTracker = LookingTracker(entity, EntityTracker(randomBattlingPokemon, true))
ticksUntilReacquireTarget = (objective.minDurationTicks..objective.maxDurationTicks).random()
}
}
ticksUntilReacquireTarget--
this.lookingTracker?.tick()
return true
}
}
class Config : ObjectiveConfig {
var stopBattleIfHurt: ExpressionOrEntityVariable = Either.left("true".asExpression())
var minDurationTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
var maxDurationTicks: ExpressionOrEntityVariable = Either.left("80".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
stopBattleIfHurt,
minDurationTicks,
maxDurationTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val stopBattleIfHurt = stopBattleIfHurt.resolveBoolean(behaviourConfigurationContext.runtime)
val minDurationTicks = minDurationTicks.resolveInt(behaviourConfigurationContext.runtime)
val maxDurationTicks = maxDurationTicks.resolveInt(behaviourConfigurationContext.runtime)
return FocusDuringBattle(
stopBattleIfHurt = stopBattleIfHurt,
minDurationTicks = minDurationTicks,
maxDurationTicks = maxDurationTicks
)
}
}
}
@@ -0,0 +1,508 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonBlocks
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.task.PollinateFlowerTaskConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.block.SaccharineLeafBlock
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.distanceTo
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.MemoryStatus
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.level.block.BeehiveBlock
import net.minecraft.world.level.block.entity.BeehiveBlockEntity
import net.minecraft.world.phys.Vec3
/**
* Mimics the vanilla bee behavior, with added interactions with Saccharine leaves.
* Only wild bees are allowed to enter hives because of dupe risks with pasture blocks.
*
* @author JazzMcNade
* @since February 23th, 2026
*/
class GatherNectar(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.2".asExpression()
) : Objective {
var workerFixation: EntityFixation? = null
var shelterFixation: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Worker Bee"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(shelterFixation)) {
// Never preempt the shelter fixation
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
} else if (!entity.biggerBrain.hasMemoryValue(CobblemonMemories.HIVE_LOCATION) && !entity.biggerBrain.hasMemoryValue(CobblemonMemories.NEARBY_SACC_LEAVES)) {
return ObjectiveStatus.INACTIVE
}
val world = entity.level()
if ((world.isRaining || world.isNight) ) {
if (!brain.distract(comfortDistraction)) {
return ObjectiveStatus.BLOCKED
}
// Return to hive or do nothing
if (entity.pokemon.isWild()) {
// Only wilds can path to hives
val hivePos = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION)
if (hivePos != null && wantsToEnterHive(entity)) {
// Deliver to hive
if (!tryEnterHive(entity)) { // Attempt to enter the hive, if we fail, probably too far away
val hiveEntrance = getHiveEntrance(hivePos, entity)
if (hiveEntrance != null) {
// Move to hive
shelterFixation = tryMovementFixation(entity, hiveEntrance, "Sheltering in Hive", ::onHiveMovementComplete)
} else {
// Blacklist the hive
dropAndBlackListHive(entity)
}
} // no else the entity is gone and is stored in the hive
}
} else {
return ObjectiveStatus.INACTIVE
}
} else if (brain.isFixation(workerFixation)) {
// Already fixated on the work
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
} else {
// Perform nectar gathering/delivery
if (!brain.distract(idleBoredomDistraction)) {
return ObjectiveStatus.BLOCKED
}
if (entity.biggerBrain.hasMemoryValue(CobblemonMemories.HAS_NECTAR) ) {
// Deliver nectar to hive or Sacc leaves
val hivePos = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION)
if (hivePos != null && wantsToEnterHive(entity) && entity.pokemon.isWild()) {
// Deliver to hive
if (!tryEnterHive(entity)) { // Attempt to enter the hive, if we fail, probably too far away
val hiveEntrance = getHiveEntrance(hivePos, entity)
if (hiveEntrance != null) {
// Move to hive
workerFixation = tryMovementFixation(entity, hiveEntrance, "Delivering nectar to hive", ::onHiveMovementComplete)
} else {
// Blacklist the hive
dropAndBlackListHive(entity)
}
} // no else the entity is gone and is stored in the hive
} else {
// Deliver to Saccharine Leaves
val sacLeafPos : BlockPos = entity.biggerBrain.getMemory(CobblemonMemories.NEARBY_SACC_LEAVES)
?: return ObjectiveStatus.INACTIVE
if (entity.blockPosition() != sacLeafPos) {
workerFixation = tryMovementFixation(entity, sacLeafPos, "Delivering nectar to Saccharine Leaves")
return ObjectiveStatus.ACTIVE
} else {
// Do nectar deposit fixation
workerFixation = brain.fixate(DepositNectarInSaccharineLeavesFixation())
return ObjectiveStatus.ACTIVE
}
}
} else {
// Gather Nectar
val flowerPos =
entity.biggerBrain.getMemory(CobblemonMemories.NEARBY_FLOWER) ?: return ObjectiveStatus.INACTIVE
val distance = entity.distanceTo(flowerPos)
val maxDistance = mainThreadRuntime.resolveFloat(maxDistance)
if (distance < 1.0) {
// Pollinate/Gather nectar from the flower
if (workerFixation !is PollinateFlowerFixation && brain.distract(idleBoredomDistraction)) {
workerFixation = brain.fixate(PollinateFlowerFixation())
return ObjectiveStatus.FIXATED
}
} else if (distance < maxDistance) {
// Move to the flower
if (remainingCooldownTicks <= 0 && brain.distract(idleBoredomDistraction) && !brain.hasMemoryValue(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN
)
) {
remainingCooldownTicks = ticksBetweenAttempts
workerFixation = tryMovementFixation(entity, flowerPos, "Moving to flower")
}
}
}
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
return ObjectiveStatus.ACTIVE
}
/*
* This Fixation has movement, but it doesn't utilize pathfinding, and it's more about flavor than accomplishing a goal
*
*
*/
class PollinateFlowerFixation(
) : EntityFixation {
var successfulPollinationTicks = 0
var lastSoundPlayedTick = 0
var hoverPos: Vec3? = null
override fun getDescription(entity: LivingEntity) = "Pollinating Flower"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || distraction.isComfort || entity.brain.hasMemoryValue(
CobblemonMemories.HAS_NECTAR
)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
hoverPos = null
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
entity.brain.setMemory(CobblemonMemories.HAS_NECTAR, true)
}
successfulPollinationTicks = 0
entity.brain.setMemoryWithExpiry(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN, true,
PollinateFlowerTaskConfig.Companion.PATH_TO_FLOWER_COOLDOWN_TICKS
)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) return false
val flowerPos = entity.brain.getMemorySafely(CobblemonMemories.NEARBY_FLOWER).orElse(null)
if (!(flowerPos != null && Vec3.atCenterOf(flowerPos).distanceTo(entity.position()) <= 1.0)) {
onStop(entity)
return false
}
++successfulPollinationTicks
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
onStop(entity)
return false
}
if (entity.random.nextFloat() < 0.05f && successfulPollinationTicks > this.lastSoundPlayedTick + 60) {
this.lastSoundPlayedTick = successfulPollinationTicks
entity.playSound(SoundEvents.BEE_POLLINATE, 1.0f, 1.0f)
}
val bl = hoverPos == null || entity.position().distanceTo(hoverPos!!) <= 0.1
val bl3 = entity.random.nextInt(40) == 0
if (bl && bl3) {
// mimics the wriggling over a flower the vanilla bees do
if (hoverPos == null) {
hoverPos = flowerPos.bottomCenter.add(0.0, 0.4, 0.0)
}
hoverPos = flowerPos.bottomCenter.add(
Vec3(
(entity.random.nextDouble() * 2.0 - 1.0) * (1.0 / 5.0),
0.3 + (entity.random.nextDouble() * 2.0 - 1.0) * (1.0 / 7.0),
(entity.random.nextDouble() * 2.0 - 1.0) * (1.0 / 5.0)
)
)
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
entity.lookControl.setLookAt(flowerPos.bottomCenter.add(0.0, 0.5, 0.0))
} else if (!bl) {
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
}
entity.lookControl.setLookAt(flowerPos.bottomCenter.add(0.0, 0.5, 0.0))
return true
}
fun onStop(entity: LivingEntity) {
hoverPos = null
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
entity.brain.setMemory(CobblemonMemories.HAS_NECTAR, true)
}
successfulPollinationTicks = 0
entity.brain.setMemoryWithExpiry(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN, true,
PATH_TO_FLOWER_COOLDOWN_TICKS
)
}
}
class DepositNectarInSaccharineLeavesFixation() : EntityFixation {
var successfulPollinationTicks = 0
var lastSoundPlayedTick = 0
var hoverPos: Vec3? = null
override fun getDescription(entity: LivingEntity) = "Depositing nectar in Saccharine Leaves"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || distraction.isComfort || entity.brain.hasMemoryValue(
CobblemonMemories.HAS_NECTAR
)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
hoverPos = null
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
entity.brain.setMemory(CobblemonMemories.HAS_NECTAR, true)
}
successfulPollinationTicks = 0
entity.brain.setMemoryWithExpiry(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN, true,
PollinateFlowerTaskConfig.Companion.PATH_TO_FLOWER_COOLDOWN_TICKS
)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) return false
++successfulPollinationTicks
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
val blockPos = brain.getMemory(CobblemonMemories.NEARBY_SACC_LEAVES)
blockPos?.let {
val world = entity.level()
val blockState = world.getBlockState(blockPos)
if (blockState.block == CobblemonBlocks.SACCHARINE_LEAVES) {
val saccAge = blockState.getValue( SaccharineLeafBlock.AGE)
if (saccAge < SaccharineLeafBlock.MAX_AGE) {
brain.eraseMemory(CobblemonMemories.HAS_NECTAR)
val newBlockState = blockState.setValue(SaccharineLeafBlock.AGE, saccAge + 1)
world.setBlock(blockPos, newBlockState, 3)
}
}
}
return false
}
if (entity.random.nextFloat() < 0.05f && successfulPollinationTicks > this.lastSoundPlayedTick + 60) {
this.lastSoundPlayedTick = successfulPollinationTicks
entity.playSound(SoundEvents.BEEHIVE_DRIP, 1.0f, 1.0f)
}
val leavesPos = brain.getMemory(CobblemonMemories.NEARBY_SACC_LEAVES) ?: return false
val bl = hoverPos == null || entity.position().distanceTo(hoverPos!!) <= 0.1
val bl3 = entity.random.nextInt(40) == 0
if (bl && bl3) {
// mimics the wriggling over a flower the vanilla bees do
if (hoverPos == null) {
hoverPos = leavesPos.bottomCenter.add(0.0, 0.4, 0.0)
}
hoverPos = leavesPos.bottomCenter.add(Vec3((entity.random.nextDouble() * 2.0 - 1.0) * (1.0/5.0), 0.3 + (entity.random.nextDouble() * 2.0 - 1.0) * (1.0/7.0), (entity.random.nextDouble() * 2.0 - 1.0) * (1.0/5.0)))
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
entity.lookControl.setLookAt(leavesPos.bottomCenter.add(0.0,0.5,0.0))
} else if (!bl) {
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
}
return true
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return GatherNectar(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
fun onHiveMovementComplete(entity: LivingEntity, brain: BiggerBrain) {
if (entity !is PokemonEntity) return
if(!tryEnterHive(entity)) {
dropAndBlackListHive(entity)
}
}
fun tryMovementFixation(
entity: PokemonEntity,
blockPos: BlockPos,
description : String,
onMovementComplete : ((entity: LivingEntity, brain: BiggerBrain) -> Unit)? = null,
) : EntityFixation? {
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
blockPos,
speedMultiplier,
0
)
)
if (movementTracker != null) {
val fixation = entity.biggerBrain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(
DistractionType.DAMAGE,
DistractionType.COMFORT,
DistractionType.FORCE
),
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(
entity,
movementTracker.walkTarget
),
movementTracker = movementTracker,
description = description,
onMovementComplete = onMovementComplete
)
)
return fixation
}
return null
}
fun getHiveEntrance(hiveLocation: BlockPos, entity: LivingEntity) : BlockPos? {
val sidesByClosest = listOf(
hiveLocation.north(),
hiveLocation.south(),
hiveLocation.east(),
hiveLocation.west()
).sortedBy { it.distSqr(entity.blockPosition()) }
val world = entity.level()
var openSide = BlockPos.ZERO
for (side in sidesByClosest) {
if (world.getBlockState(side).isAir) {
openSide = side
break
}
}
if (openSide == BlockPos.ZERO) {
if (world.getBlockState(hiveLocation.above()).isAir) {
// If the above position is also air, we can use it
openSide = hiveLocation.above() // Fallback to above if no open sides found
} else if (world.getBlockState(hiveLocation.below()).isAir) {
// If the below position is also air, we can use it
openSide = hiveLocation.below() // Fallback to below if no open sides found
} else {
// If no open sides or above/below positions are found, we cannot proceed
return null
}
}
return openSide
}
fun tryEnterHive(entity: LivingEntity): Boolean {
if (entity !is PokemonEntity || !wantsToEnterHive(entity)) {
return false
}
val hiveLocation = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION) ?: return false
val targetVec = Vec3.atCenterOf(hiveLocation)
// if we are not close to it then end early
if (entity.distanceToSqr(targetVec) > 1.6 * 1.6) {
return false
}
val state = entity.level().getBlockState(hiveLocation)
val block = state.block
if (block is BeehiveBlock) {
val blockEntity = entity.level().getBlockEntity(hiveLocation)
if (blockEntity !is BeehiveBlockEntity) return false
if (blockEntity.isFull) {
// Erase Hive memory and give the bee a moment to locate a new hive
dropAndBlackListHive(entity)
} else {
blockEntity.addOccupant(entity)
return true
}
}
return false
}
fun wantsToEnterHive(entity: LivingEntity): Boolean {
val result = !entity.brain.checkMemory(CobblemonMemories.HIVE_COOLDOWN, MemoryStatus.VALUE_PRESENT)
&& (entity.level().isRaining || entity.level().isNight || entity.brain.getMemory(CobblemonMemories.HAS_NECTAR)
.orElse(false))
if (result) {
val blockPos = entity.brain.getMemorySafely(CobblemonMemories.HIVE_LOCATION).orElse(null)
val blockEntity = entity.level().getBlockEntity(blockPos)
return blockEntity is BeehiveBlockEntity && !blockEntity.isFireNearby
}
return false
}
fun dropAndBlackListHive(entity: PokemonEntity) {
val hivePos = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION)
if (hivePos == null) return
val blackList : MutableList<BlockPos> = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_BLACKLIST)?.toMutableList() ?: emptyList<BlockPos>().toMutableList()
blackList.add(hivePos)
if (blackList.count() > 3) {
blackList.removeFirst()
}
entity.brain.eraseMemory(CobblemonMemories.HIVE_LOCATION)
entity.brain.setMemory(CobblemonMemories.HIVE_BLACKLIST, blackList)
}
companion object {
const val PATH_TO_FLOWER_COOLDOWN_TICKS: Long = 200
const val HAS_NECTAR_ASPECT = "has_nectar"
const val MIN_DURATION: Int = 300
const val MAX_DURATION: Int = 400
const val REQUIRED_SUCCESSFUL_POLLINATION_TICKS = 250
}
}
@@ -0,0 +1,155 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonActivities
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.status.PersistentStatusContainer
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Sleeps the entity.
*
* @author Hiroku
* @since December 29th, 2025
*/
class GoToSleep(
val onlyFromStatus: Expression = "false".asExpression(),
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Sleeping"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED
}
// Don't sleep if we're not tired
brain.getMemory(CobblemonMemories.POKEMON_DROWSY)
?: return ObjectiveStatus.INACTIVE
val hasSleepStatus = entity.pokemon.status?.status === Statuses.SLEEP
if (entity.behaviour.resting.canSleep && entity.canSleepAt(entity.blockPosition().below()) || hasSleepStatus) {
if (!hasSleepStatus) {
if (mainThreadRuntime.resolveBoolean(onlyFromStatus)) {
return ObjectiveStatus.BLOCKED
}
entity.pokemon.status = PersistentStatusContainer(Statuses.SLEEP)
}
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.navigation.stop()
entity.brain.setActiveActivityToFirstValid(listOf(CobblemonActivities.POKEMON_SLEEPING_ACTIVITY))
entity.brain.setMemory(CobblemonMemories.POKEMON_SLEEPING, true)
// Become fixated
fixation = brain.fixate(
SleepFixation(
this,
null
)
)
return ObjectiveStatus.FIXATED
}
return ObjectiveStatus.BLOCKED
}
class SleepFixation(
val objective: GoToSleep,
override val movementTracker: MovementTracker?,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity): String {
return "Sleeping"
}
override fun tickMovementFixation(): MovementStatus? {
return MovementStatus.PENDING
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
if (distraction.isIdleBoredom) {
return false
}
wakeUp(entity)
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (!entity.brain.getMemorySafely(CobblemonMemories.POKEMON_DROWSY).orElse(false)) {
wakeUp(entity)
return false
}
return true
}
fun wakeUp(entity: LivingEntity) {
if (entity !is PokemonEntity) return
val hasSleepStatus = entity.pokemon.status?.status == Statuses.SLEEP
if (hasSleepStatus && entity.pokemon.storeCoordinates.get()?.store is PartyStore) {
return // You can't wake up if you're in the party with the sleep status.
}
if (hasSleepStatus) {
entity.pokemon.status = null
}
entity.brain.eraseMemory(CobblemonMemories.POKEMON_SLEEPING)
entity.brain.useDefaultActivity()
}
}
class Config : ObjectiveConfig {
val onlyFromStatus: ExpressionOrEntityVariable = Either.left("false".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
onlyFromStatus
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return GoToSleep(
onlyFromStatus = onlyFromStatus.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,204 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.distanceTo
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Items
import net.minecraft.world.level.GameRules
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.CaveVines
import net.minecraft.world.level.block.SweetBerryBushBlock
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.gameevent.GameEvent
/**
* Paths to ripened sweet berry bushes AND glowberry vines with berries.
* Upon reaching the target harvests the berries and stashes one in its
* held item slot if possible.
* Requires NEARBY_SWEET_BERRY_BUSH memory
*
* @author JazzMcNade
* @since February 8th, 2026
*/
class HarvestSweetBerryBush(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var harvestTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Harvesting sweet/glow berry"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(harvestTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
val berryPosition = entity.biggerBrain.getMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH) ?: return ObjectiveStatus.INACTIVE
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val maxDistance = mainThreadRuntime.resolveFloat(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val distance = entity.distanceTo(berryPosition)
if (distance < maxDistance) {
if (remainingCooldownTicks <= 0 && brain.distract(idleBoredomDistraction)) {
remainingCooldownTicks = ticksBetweenAttempts
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
berryPosition,
speedMultiplier,
1
)
)
if (movementTracker != null) {
harvestTask = brain.fixate(
fixation = HarvestSweetBerryBushFixation(
entity = entity,
movementTracker = movementTracker
)
)
}
}
}
return ObjectiveStatus.ACTIVE
}
class HarvestSweetBerryBushFixation(
entity: PathfinderMob,
override val movementTracker: MovementTracker,
): EntityFixation, LookingTrackerFixation, MovementTrackerFixation {
override val lookingTracker: LookingTracker = LookingTracker(entity = entity, lookTarget = movementTracker.walkTarget.target)
override fun getDescription(entity: LivingEntity) = "Harvesting sweet/glow berry"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || (movementTracker.lastStatus == MovementStatus.COMPLETED && entity.brain.getMemorySafely(
CobblemonMemories.NEARBY_SWEET_BERRY_BUSH).orElse(null) != null)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
movementTracker.tick()
if (movementTracker.lastStatus == MovementStatus.COMPLETED) {
val world = entity.level()
if (entity !is PokemonEntity) return false
if (!world.gameRules.getRule(GameRules.RULE_MOBGRIEFING).get()) {
// Not allowed to alter the world
return false
}
val blockPos = entity.brain.getMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH).orElse(null) ?: return false
val blockState = world.getBlockState(blockPos)
if (CaveVines.hasGlowBerries(blockState)) { // Glow Berries Case
CaveVines.use(entity, blockState, world, blockPos)
} else if (blockState.`is`(Blocks.SWEET_BERRY_BUSH)) { // Sweet Berries Case
blockState.setValue(SweetBerryBushBlock.AGE, 1)
var j: Int = 1 + entity.level().random.nextInt(2) + if (blockState.getValue<Int>(SweetBerryBushBlock.AGE) == 3) 1 else 0
val itemStack: ItemStack = entity.pokemon.heldItem
if (itemStack.isEmpty) {
entity.pokemon.swapHeldItem(ItemStack(Items.SWEET_BERRIES))
--j
}
if (j > 0) {
Block.popResource(entity.level(), blockPos, ItemStack(Items.SWEET_BERRIES, j))
}
entity.playSound(SoundEvents.SWEET_BERRY_BUSH_PICK_BERRIES, 1.0f, 1.0f)
entity.level().setBlock(blockPos, blockState.setValue(SweetBerryBushBlock.AGE, 1) as BlockState, 2)
entity.level().gameEvent(GameEvent.BLOCK_CHANGE, blockPos, GameEvent.Context.of(entity))
}
entity.brain.eraseMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH)
return false
} else if (movementTracker.lastStatus == MovementStatus.FAILED) {
// Cannot reach, give up for a awhile
entity.brain.setMemoryWithExpiry(CobblemonMemories.DISABLE_WALK_TO_BERRY_BUSH, true, 200)
entity.brain.eraseMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH)
return false
}
return true
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return HarvestSweetBerryBush(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,409 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.CobblemonWanderControl
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.pokemon.ai.ToleratedHerdLeader
import com.cobblemon.mod.common.pokemon.status.PersistentStatusContainer
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.toBlockPos
import com.mojang.datafixers.util.Either
import java.util.UUID
import kotlin.math.cos
import kotlin.math.sin
import net.minecraft.server.level.ServerLevel
import net.minecraft.util.Mth
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.phys.Vec3
class Herd(
var checkTicks: Int = 60,
var tooFar: Float = 8F,
var closeEnough: Float = 4F,
/** Chance per tick of following the herd leader. */
val chance: Float = 1 / 60F,
val pathingCooldownTicks: Int = 80
) : Objective {
var wanderCenter: CobblemonWanderControl.WanderCenter? = null
var fixation: EntityFixation? = null
var leader: PokemonEntity? = null
var ticksUntilMaintainLeader: Int = checkTicks
var remainingPathingCooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Herd"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
entity as PokemonEntity
val moveControl = entity.moveControl as? PokemonMoveControl ?: return ObjectiveStatus.INVALID
if (remainingPathingCooldownTicks > 0) {
remainingPathingCooldownTicks--
}
val level = entity.level() as ServerLevel
if (leader == null && brain.hasMemoryValue(CobblemonMemories.HERD_LEADER)) {
leader = level.getEntity(brain.getMemory(CobblemonMemories.HERD_LEADER).let(UUID::fromString)) as? PokemonEntity
if (leader == null) {
brain.eraseMemory(CobblemonMemories.HERD_LEADER)
}
}
if (ticksUntilMaintainLeader > 0) {
ticksUntilMaintainLeader--
} else if (ticksUntilMaintainLeader == 0) {
if (brain.fixation == null || brain.isFixation(fixation)) {
// Don't maintain the herd leader if we're busy with something else
maintainHerdLeader(entity, brain)
}
ticksUntilMaintainLeader = checkTicks
}
if (leader?.level() != level) {
this.leader = null
}
val leader = leader
if (leader == null && brain.isFixation(fixation)) {
brain.distract(Distraction.FORCE)
}
val wanderControl = brain.getMemory(CobblemonMemories.WANDER_CONTROL)
?: CobblemonWanderControl()
if (this.wanderCenter != null && leader == null) {
if (wanderControl.center == this.wanderCenter) {
wanderControl.center = null
wanderControl.wanderChanceMultiplier = null
brain.setMemory(CobblemonMemories.WANDER_CONTROL, wanderControl)
}
this.wanderCenter = null
} else if (leader != null) {
wanderControl.center = CobblemonWanderControl.WanderCenter(
x = leader.x,
y = leader.y,
z = leader.z,
minRange = 1F,
maxRange = tooFar
)
this.wanderCenter = wanderControl.center
wanderControl.wanderChanceMultiplier = 0.25F
brain.setMemory(CobblemonMemories.WANDER_CONTROL, wanderControl)
}
leader ?: return ObjectiveStatus.INACTIVE
if (brain.isFixation(fixation) && fixation is MovementTrackerFixation) {
return ObjectiveStatus.FIXATED
}
val leaderFixation = leader.biggerBrain.fixation
val canMove = brain.canDistract(comfortDistraction) || brain.isFixation(fixation)
val isMovingCloser = brain.isFixation(fixation) && fixation is LookAndMoveFixation
val leaderMoveControl = leader.moveControl as? PokemonMoveControl ?: return ObjectiveStatus.INVALID
if (leader.distanceTo(entity) > tooFar) {
return when {
isMovingCloser -> ObjectiveStatus.FIXATED // Already have the fixation to move closer
remainingPathingCooldownTicks > 0 -> manageFixation(brain) // Still cooling down from last pathing attempt
!canMove -> ObjectiveStatus.BLOCKED // I'm not able to distract the brain and move closer
else -> tryMovingCloser(entity, brain, level, leader) // let's give it a fair shake then
}
} else if (leader.isFlying() && !entity.isFlying() && !isMovingCloser) {
if (!entity.canFly()) {
entity.brain.eraseMemory(CobblemonMemories.HERD_LEADER) // We can't go where this guy's going
this.leader = null
return ObjectiveStatus.INACTIVE
} else if (!canMove) {
return ObjectiveStatus.BLOCKED
}
return tryMovingCloser(entity, brain, level, leader)
} else if (leaderMoveControl.banking && !isMovingCloser) {
if (!canMove) {
return ObjectiveStatus.BLOCKED
}
if (leader.isInLiquid && !entity.isInLiquid) {
if (remainingPathingCooldownTicks > 0) {
return manageFixation(brain) // Still cooling down from last pathing attempt
}
// We should get into water asap so we can mimic the banking
return tryMovingCloser(entity, brain, level, leader, completionRange = 1)
} else {
removeSleep(entity, brain)
entity.yRot = leader.yRot
moveControl.startBanking(
forwardBlocksPerTick = leaderMoveControl.bankForwardBlocksPerTick,
upwardsBlocksPerTick = leaderMoveControl.bankUpwardsBlocksPerTick,
durationTicks = 2,
rightDegreesPerTick = 0F // Relying on the above yRot = leader.yRot because we dunno when we first started mimicking the banking
)
return ObjectiveStatus.FIXATED
}
} else if (leaderFixation is MovementTrackerFixation && leaderFixation.movementTracker?.lastStatus == MovementStatus.PENDING) {
if (entity.random.nextFloat() > chance) {
return manageFixation(brain) // Not this tick
} else if (!canMove) {
return ObjectiveStatus.BLOCKED
} else if (isMovingCloser) {
return ObjectiveStatus.FIXATED // Already moving
}
val leaderWalkTarget = leaderFixation.movementTracker?.walkTarget ?: return manageFixation(brain)
// We're already closer to the walk target than the leader is, so no need to move. If anything we should get out of the way
if (entity.distanceToSqr(leaderWalkTarget.target.currentPosition()) + closeEnough < leader.distanceToSqr(leaderWalkTarget.target.currentPosition())) {
return manageFixation(brain)
}
// Go to the leader's walk target, roughly.
val walkTarget = CobblemonWalkTarget(
pos = leaderWalkTarget.target.currentPosition().add(getRandomOffset(entity, level)).toBlockPos(),
speedModifier = leaderWalkTarget.speedModifier,
nodeTypeFilter = (leaderWalkTarget as? CobblemonWalkTarget)?.nodeTypeFilter ?: { true },
completionRange = closeEnough.toInt()
)
return tryMovingCloser(entity, brain, level, leader, walkTarget = walkTarget)
} else if (leader.getCurrentPoseType() == PoseType.SLEEP) {
// Leader is sleeping, if I'm drowsy and can sleep here then I will sleep too.
if (entity.canSleepAt(entity.blockPosition().offset(0, -1, 0)) && brain.getMemory(CobblemonMemories.POKEMON_DROWSY) == true) {
if (entity.random.nextFloat() < 1 / 40F) {
applySleep(entity, brain)
}
}
} else if (brain.getMemory(CobblemonMemories.POKEMON_SLEEPING) == true) {
// Leader is awake, so we should be awake too. Maybe.
if (entity.random.nextFloat() < 1 / 15F) {
removeSleep(entity, brain)
}
}
return manageFixation(brain)
}
fun manageFixation(brain: BiggerBrain): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (leader != null) {
return ObjectiveStatus.ACTIVE
} else {
return ObjectiveStatus.INACTIVE
}
}
fun tryMovingCloser(
entity: PokemonEntity,
brain: BiggerBrain,
level: ServerLevel,
leader: PokemonEntity,
walkTarget: WalkTarget? = null,
completionRange: Int = closeEnough.toInt()
): ObjectiveStatus {
val walkTarget = walkTarget ?: CobblemonWalkTarget(
pos = leader.position().add(getRandomOffset(entity, level)).toBlockPos(),
speedModifier = 0.4F,
completionRange = completionRange
)
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
remainingPathingCooldownTicks = pathingCooldownTicks
if (movementTracker == null) {
// Couldn't find a path, wait a bit before trying again
return manageFixation(brain)
} else if (!(brain.isFixation(fixation) && brain.distract(Distraction.FORCE)) && !brain.distract(comfortDistraction)) {
return manageFixation(brain) // Not likely based on checks run on callers to this function.
}
brain.sendDebugMessage("Moving closer, to ${movementTracker.walkTarget.target.currentBlockPosition()}")
removeSleep(entity, brain)
fixation = brain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.COMFORT, DistractionType.FORCE),
lookingTracker = LookingTracker.forTargetEntity(entity, leader, trackEyeHeight = true),
movementTracker = movementTracker,
description = "Moving towards herd leader"
)
)
return ObjectiveStatus.FIXATED
}
fun maintainHerdLeader(entity: PokemonEntity, brain: BiggerBrain) {
val world = entity.level() as ServerLevel
val leader = brain.getMemory(CobblemonMemories.HERD_LEADER)?.let(UUID::fromString).let(world::getEntity) as? PokemonEntity
val currentLeaderDefinition = leader?.let { leader ->
entity.behaviour.herd.toleratedLeaders.find { it.pokemon.matches(leader) }
}
if (leader == null || currentLeaderDefinition == null) {
entity.brain.eraseMemory(CobblemonMemories.HERD_LEADER)
this.leader = null
}
val bestLeader = getBestHerdLeader(
currentLeader = if (leader == null || currentLeaderDefinition == null) null else (leader to currentLeaderDefinition),
nearbyEntities = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES) ?: return,
entity = entity
)
if (bestLeader != null && bestLeader != leader) {
bestLeader.brain.eraseMemory(CobblemonMemories.HERD_LEADER)
entity.brain.setMemory(CobblemonMemories.HERD_LEADER, bestLeader.uuid.toString())
bestLeader.adjustHerdSize(1)
leader?.adjustHerdSize(-1)
this.leader = bestLeader
}
}
fun getRandomOffset(entity: PokemonEntity, level: ServerLevel): Vec3 {
val leader = leader ?: return Vec3.ZERO
val minRange = closeEnough.toDouble()
val maxRange = (tooFar - closeEnough / 2).toDouble()
val randomDistance = Mth.nextDouble(level.random, minRange, maxRange)
val randomAngle = Mth.nextDouble(level.random, 0.0, 2 * Math.PI)
var offset = Vec3(cos(randomAngle) * randomDistance, 0.0, sin(randomAngle) * randomDistance)
if ((entity.isInLiquid && leader.isInLiquid) || (entity.isFlying() && leader.isFlying())) {
val verticalRange = randomDistance * 0.5
val randomY = Mth.nextDouble(level.random, -verticalRange, verticalRange)
offset = offset.add(0.0, randomY, 0.0)
}
return offset
}
fun applySleep(entity: PokemonEntity, brain: BiggerBrain) {
brain.setMemory(CobblemonMemories.POKEMON_SLEEPING, true)
entity.pokemon.status = PersistentStatusContainer(Statuses.SLEEP)
}
fun removeSleep(entity: PokemonEntity, brain: BiggerBrain) {
if (brain.hasMemoryValue(CobblemonMemories.POKEMON_SLEEPING)) {
brain.eraseMemory(CobblemonMemories.POKEMON_SLEEPING)
val status = entity.pokemon.status
if (status != null && status.status == Statuses.SLEEP) {
entity.pokemon.status = null
}
}
}
/**
* Logic used to choose the best herd leader from nearby visible entities.
*
* - Higher tier leaders are always preferred.
* - Same-tier leaders that are closer are preferred except for when they're the same tier as the current leader.
* - We don't want to exceed the target's herd size limit.
* - We don't want to choose a leader that is themselves following a leader.
* - Some leader definitions allow lower-level Pokémon to lead them.
* - Leaders just have to not be in a party - pastured and wild Pokémon can mingle.
*/
fun getBestHerdLeader(
currentLeader: Pair<PokemonEntity, ToleratedHerdLeader>?,
nearbyEntities: NearestVisibleLivingEntities,
entity: PokemonEntity,
): PokemonEntity? {
var bestLeader: PokemonEntity? = null
val (currentLeaderEntity, currentLeaderDefinition) = currentLeader ?: Pair(null, null)
var bestTier = currentLeaderDefinition?.tier?.let { it + 1 } ?: 0 // Only upgrade to a higher tier leader
var bestDistance = Float.MAX_VALUE
nearbyEntities.findAll {
it is PokemonEntity &&
it != currentLeader &&
it.pokemon.storeCoordinates.get()?.store !is PartyStore &&
it.getHerdSize() < it.behaviour.herd.maxSize &&
!it.brain.hasMemoryValue(CobblemonMemories.POKEMON_DROWSY)
}.forEach { possibleLeader ->
possibleLeader as PokemonEntity
val bestMatchingHerdLeader = entity.behaviour.herd.bestMatchLeader(entity, possibleLeader) ?: return@forEach
val possibleLeaderIsAlreadyALeader = possibleLeader.brain.hasMemoryValue(CobblemonMemories.HERD_SIZE)
val currentLeaderHerdTier = currentLeaderEntity?.getHerdTier() ?: entity.getHerdTier()
if (currentLeaderHerdTier >= bestMatchingHerdLeader.tier) {
return@forEach // This leader is following a leader of a higher tier, we can't replace them
}
val distance = entity.distanceTo(possibleLeader)
if (bestMatchingHerdLeader.tier < bestTier) {
return@forEach // No need to check further if this leader is worse than the best found so far
} else if ((distance > bestDistance && !possibleLeaderIsAlreadyALeader) && bestMatchingHerdLeader.tier == bestTier) {
return@forEach // No need to check further if this leader is farther than the best found so far, unless they are already a leader - I'd prefer to join a pack
} else {
bestLeader = possibleLeader
bestDistance = distance
bestTier = bestMatchingHerdLeader.tier
}
}
return bestLeader ?: currentLeaderEntity
}
class Config : ObjectiveConfig {
// How frequently to check for whether it should herd. Probably isn't that expensive but might use this for chance.
val checkTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
val tooFar: ExpressionOrEntityVariable = Either.left("8".asExpression())
val closeEnough: ExpressionOrEntityVariable = Either.left("4".asExpression())
val chance: ExpressionOrEntityVariable = Either.left("1 / 60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(checkTicks, tooFar, closeEnough, chance).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
behaviourConfigurationContext.addMemories(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
behaviourConfigurationContext.addMemories(CobblemonMemories.HERD_LEADER)
behaviourConfigurationContext.addMemories(CobblemonMemories.HERD_SIZE)
return Herd(
checkTicks = checkTicks.resolveInt(behaviourConfigurationContext.runtime),
tooFar = tooFar.resolveFloat(behaviourConfigurationContext.runtime),
closeEnough = closeEnough.resolveFloat(behaviourConfigurationContext.runtime),
chance = chance.resolveFloat(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,166 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.sounds.SoundEvents
import net.minecraft.tags.FluidTags
import net.minecraft.util.Mth
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.level.material.FluidState
import kotlin.math.atan2
/**
* Swimming Pokemon perform a cool little jump out of the water if they're near the surface
*
*/
class JumpOutOfWater(
val ticksBetweenAttempts: Int = 60,
) : Objective {
var inWater = false
var remainingCooldownTicks = ticksBetweenAttempts
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Jump out of water"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
if (entity.random.nextInt(CHANCE) != 0) {
return ObjectiveStatus.INACTIVE
} else {
if (!brain.distract(idleBoredomDistraction)) return ObjectiveStatus.BLOCKED
val direction = entity.motionDirection
val x = direction.stepX
val z = direction.stepZ
val blockPos = entity.blockPosition()
val offsets = OFFSET_MULTIPLIERS
for (offset in offsets) {
if (!this.isWater(entity, blockPos, x, z, offset) || !this.isAirAbove(entity, blockPos, x, z, offset)) {
return ObjectiveStatus.ACTIVE
}
}
val newVelocity = entity.deltaMovement.add(direction.stepX.toDouble() * 0.6, 0.7, direction.stepZ.toDouble() * 0.6)
entity.deltaMovement = newVelocity
entity.getNavigation().stop()
fixation = brain.fixate(
fixation = JumpOutOfWaterFixation(
this,
movementTracker = null
)
)
}
return ObjectiveStatus.ACTIVE
}
class JumpOutOfWaterFixation(
val objective: JumpOutOfWater,
override val movementTracker: MovementTracker?,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Jumping out of water"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val bl: Boolean = objective.inWater
if (!bl) {
val fluidState: FluidState = entity.level().getFluidState(entity.blockPosition())
objective.inWater = fluidState.`is`(FluidTags.WATER)
}
if (objective.inWater && !bl) {
// Transition tick from in water to out of water
entity.playSound(SoundEvents.DOLPHIN_JUMP, 1.0f, 1.0f)
}
val vec3d = entity.deltaMovement
if (vec3d.y * vec3d.y < 0.029999999329447746 && entity.xRot != 0.0f) {
entity.xRot = Mth.rotLerp(0.2f, entity.xRot, 0.0f)
} else if (vec3d.length() > 9.999999747378752E-6) {
val d = vec3d.horizontalDistance()
val e = atan2(-vec3d.y, d) * 57.2957763671875
entity.xRot = e.toFloat()
}
val d: Double = vec3d.y
return (!(d * d < 0.029999999329447746) || entity.xRot == 0.0f || !(Math.abs(entity.xRot) < 10.0f) || !entity.isInWater) && !entity.onGround()
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return JumpOutOfWater(
ticksBetweenAttempts = ticksBetweenAttempts,
)
}
}
private fun isWater(entity: PokemonEntity, pos: BlockPos, offsetX: Int, offsetZ: Int, multiplier: Int): Boolean {
val blockPos = pos.offset(offsetX * multiplier, 0, offsetZ * multiplier)
return entity.level().getFluidState(blockPos).`is`(FluidTags.WATER) && !entity.level().getBlockState(blockPos)
.blocksMotion()
}
private fun isAirAbove(entity: PokemonEntity, pos: BlockPos, offsetX: Int, offsetZ: Int, multiplier: Int): Boolean {
return entity.level().getBlockState(pos.offset(offsetX * multiplier, 1, offsetZ * multiplier))
.isAir && entity.level().getBlockState(pos.offset(offsetX * multiplier, 2, offsetZ * multiplier))
.isAir
}
companion object {
private const val CHANCE = 10
private val OFFSET_MULTIPLIERS = intArrayOf(0, 1, 4, 5, 6, 7)
}
}
@@ -0,0 +1,136 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import kotlin.math.pow
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Randomly looks at nearby entities out of curiosity. Very easily distracted once doing so.
*
* @author Hiroku
* @since December 29th, 2025
*/
class LookAtNearbyEntities(
val maxDistance: Double = 10.0,
val minDuration: Int = 20,
val maxDuration: Int = 80
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Look at nearby entities"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED
}
val nearestVisibleLivingEntities = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
?: return ObjectiveStatus.INVALID
val closest = nearestVisibleLivingEntities.findClosest(
{ otherEntity -> otherEntity.distanceToSqr(entity) <= maxDistance.pow(2) && !entity.hasPassenger(otherEntity) }
).orElse(null)
if (closest == null) {
return ObjectiveStatus.INACTIVE
} else {
// Become fixated
fixation = brain.fixate(
IdleLookFixation(
this,
closest,
(minDuration..maxDuration).random()
)
)
return ObjectiveStatus.FIXATED
}
}
class IdleLookFixation(
val objective: LookAtNearbyEntities,
val targetEntity: LivingEntity,
var remainingTicks: Int
) : EntityFixation, LookingTrackerFixation {
override var lookingTracker: LookingTracker? = null
override fun getDescription(entity: LivingEntity): String {
return "Looking at a nearby entity ($remainingTicks ticks left)"
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
// Bro literally anything will distract me
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (targetEntity.isRemoved || entity !is PathfinderMob) {
return false
}
if (lookingTracker == null) {
lookingTracker = LookingTracker(entity, EntityTracker(targetEntity, true))
}
val lookingTracker = lookingTracker!!
remainingTicks--
lookingTracker.tick()
return remainingTicks > 0
}
}
class Config : ObjectiveConfig {
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val minDuration: ExpressionOrEntityVariable = Either.left("20".asExpression())
val maxDuration: ExpressionOrEntityVariable = Either.left("80".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
maxDistance,
minDuration,
maxDuration
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val maxDistance = maxDistance.resolveDouble(behaviourConfigurationContext.runtime)
val minDuration = minDuration.resolveInt(behaviourConfigurationContext.runtime)
val maxDuration = maxDuration.resolveInt(behaviourConfigurationContext.runtime)
return LookAtNearbyEntities(
maxDistance = maxDistance,
minDuration = minDuration,
maxDuration = maxDuration
)
}
}
}
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.OmniPathingEntity
import net.minecraft.world.entity.LivingEntity
class MaintainFluidY : Objective {
override fun getDescription(entity: LivingEntity) = "Maintain Y in fluids"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is OmniPathingEntity) {
return ObjectiveStatus.INVALID
}
val fixation = brain.fixation
if (fixation is MovementTrackerFixation) {
return ObjectiveStatus.BLOCKED
}
if (entity.isFlying()) {
return ObjectiveStatus.INACTIVE
}
if (entity.canSwimInWater() && entity.isUnderWater) {
entity.isNoGravity = true
} else if (entity.canSwimInLava() && entity.isInLava) {
entity.isNoGravity = true
} else {
entity.isNoGravity = false
}
return if (entity.isNoGravity) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
class Config : ObjectiveConfig {
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return emptyList()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return MaintainFluidY()
}
}
}
@@ -0,0 +1,251 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.*
import com.cobblemon.mod.common.api.ai.biggerbrain.*
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.TamableAnimal
import net.minecraft.world.entity.ai.behavior.BehaviorUtils
import net.minecraft.world.entity.ai.util.RandomPos
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.phys.Vec3
/**
* Tries to path into water if the entity usually avoids land.
* Will pathfind through land even if the entity usually filters out land nodes.
* If water cannot be found in the entity's wander range it'll wander randomly in a spiral-ish pattern
*
* @author JazzMcNade
* @since January 25th, 2026
*/
class MoveIntoWater(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var movementTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
var wanderDirection: Vec3? = null
var isWanderTurnDirectionClockwise = true
var wanderTurnChance = BASE_TURN_CHANCE
var failCount = 0
override fun getDescription(entity: LivingEntity) = "Move into water if currently out of water"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is TamableAnimal) {
return ObjectiveStatus.INVALID
}
if (entity.isInWater) {
// All good, nothing to do here
return ObjectiveStatus.INACTIVE
}
if (brain.isFixation(movementTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
} else {
remainingCooldownTicks = ticksBetweenAttempts
}
if (brain.distract(comfortDistraction)) {
val maxDistance = mainThreadRuntime.resolveInt(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val runtime = mainThreadRuntime
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
val allowLand = wanderControl?.allowLand
?: runtime.resolveBoolean("(q.entity.behaviour.moving.walk.can_walk && q.entity.behaviour.moving.walk.avoids_land) || q.entity.behaviour.moving.fly.can_fly".asExpression())
val allowAir = wanderControl?.allowAir
?: runtime.resolveBoolean("q.entity.behaviour.moving.fly.can_fly && !q.entity.behaviour.moving.walk.can_walk".asExpression())
val types = mutableSetOf<WanderType>()
if ((allowLand || allowAir)) {
types.add(WanderType.WATER)
}
if (types.isEmpty()) {
return ObjectiveStatus.INACTIVE
}
var walkTarget: CobblemonWalkTarget? = null
val targetVec3 = BehaviorUtils.getRandomSwimmablePos(entity, 10, 7)
if (targetVec3 != null) {
walkTarget = CobblemonWalkTarget(
BlockPos.containing(targetVec3.x, targetVec3.y, targetVec3.z),
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
}
if (walkTarget == null) {
if (failCount >= 5) {
// No out of water target could be found.
// Need to choose a direction and move as far as possible, hoping we randomly find water
// Totally possible that a shoreline is *just* outside the entity's wander range and
// we choose a direction that's opposite of the shoreline
// To counteract this, the pokemon moves in a (very roughly) spiral pattern outward from the origin
var wanderPosition: BlockPos? = null
if (wanderDirection == null) {
val wanderOffset = RandomPos.generateRandomDirection(entity.level().random, maxDistance / 2, 0)
wanderDirection = wanderOffset.toVec3d().normalize()
isWanderTurnDirectionClockwise = entity.random.nextInt(2) > 0
wanderTurnChance = BASE_TURN_CHANCE
wanderPosition = entity.blockPosition().offset(wanderOffset.x, wanderOffset.y, wanderOffset.z)
} else {
if (entity.level().random.nextFloat() < wanderTurnChance) {
// Turn 30 degrees
wanderDirection =
wanderDirection!!.yRot(Math.PI.toFloat() / 3.0f * if (isWanderTurnDirectionClockwise) -1f else 1f)
wanderTurnChance *= 0.7
}
val wanderVec = entity.position().add(wanderDirection!!.scale(maxDistance.toDouble()))
wanderPosition = BlockPos.containing(wanderVec)
}
val wanderTarget = generateWaterSafePosToward(entity, maxDistance, wanderPosition)
if (wanderTarget != null) {
walkTarget = CobblemonWalkTarget(
wanderPosition,
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
} else {
return ObjectiveStatus.ACTIVE
}
} else {
failCount++
}
}
if (walkTarget != null) {
failCount = 0
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
?: return ObjectiveStatus.ACTIVE
brain.distract(comfortDistraction)
movementTask = brain.fixate(
fixation = MoveIntoWaterFixation(
movementTracker = movementTracker
)
)
}
}
return ObjectiveStatus.ACTIVE
}
fun generateWaterSafePosToward(
mob: PathfinderMob,
range: Int,
targetPos: BlockPos
): BlockPos? {
for (i in 0..4) {
val candidate: BlockPos? = RandomPos.generateRandomPosTowardDirection(
mob,
range,
mob.level().random,
targetPos
)
if (candidate == null) continue
val pathType = mob.navigation.nodeEvaluator.getPathType(mob, candidate)
// Don't actually care if it can be reached, only if it's not hazardous
if (pathType == PathType.WALKABLE || mob.getPathfindingMalus(pathType) <= 0)
return candidate
}
return null
}
companion object {
val BASE_TURN_CHANCE = 0.8
}
class MoveIntoWaterFixation(
override val movementTracker: MovementTracker,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Moving into water"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val movementStatus = tickMovementFixation()
if (movementStatus == MovementStatus.COMPLETED) return false
if (!entity.isInWater) {
return false
}
return movementStatus != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return MoveIntoWater(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,258 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.*
import com.cobblemon.mod.common.api.ai.biggerbrain.*
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.TamableAnimal
import net.minecraft.world.entity.ai.util.LandRandomPos
import net.minecraft.world.entity.ai.util.RandomPos
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.phys.Vec3
/**
* Tries to path out of water if the entity usually water to avoid water.
* Will pathfind through water even if the entity usually filters out water path nodes.
* If land cannot be found in the entity's wander range it'll wander randomly in a spiral-ish pattern
*
* @author JazzMcNade
* @since January 17th, 2026
*/
class MoveOutOfWater(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var movementTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
var wanderDirection: Vec3? = null
var isWanderTurnDirectionClockwise = true
var wanderTurnChance = BASE_TURN_CHANCE
var failCount = 0
override fun getDescription(entity: LivingEntity) = "Move out of water"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is TamableAnimal) {
return ObjectiveStatus.INVALID
}
if (brain.isFixation(movementTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (!entity.isInWater || entity.isUnderWater) {
// Focus on not drowning first
// TODO: 100% boned if in an underwater cave
return ObjectiveStatus.INACTIVE
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
} else {
remainingCooldownTicks = ticksBetweenAttempts
}
val maxDistance = mainThreadRuntime.resolveInt(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val runtime = mainThreadRuntime
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
val allowLand = wanderControl?.allowLand
?: runtime.resolveBoolean("(q.entity.behaviour.moving.walk.can_walk && !q.entity.behaviour.moving.walk.avoids_land) || q.entity.behaviour.moving.fly.can_fly".asExpression())
val allowAir = wanderControl?.allowAir
?: runtime.resolveBoolean("q.entity.behaviour.moving.fly.can_fly && !q.entity.behaviour.moving.walk.can_walk".asExpression())
val types = mutableSetOf<WanderType>()
if ((allowLand || allowAir)) {
types.add(WanderType.LAND)
}
if (types.isEmpty()) {
return ObjectiveStatus.INACTIVE
}
if (brain.distract(comfortDistraction)) {
var walkTarget: CobblemonWalkTarget? = null
val targetVec3 = LandRandomPos.getPos(entity, maxDistance, maxDistance)
if (targetVec3 != null) {
walkTarget = CobblemonWalkTarget(
BlockPos.containing(targetVec3.x, targetVec3.y, targetVec3.z),
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
}
if (walkTarget == null) {
if (failCount >= 5) {
// No out of water target black with a malus of 0 could be found.
// Need to choose a direction and move as far as possible, hoping we randomly find land
// Totally possible that a shoreline is *just* outside of the entity's wander range and
// we choose a direction that's opposite of the shoreline
// To counteract this, the pokemon moves in a (very roughly) spiral pattern outward from the origin
var wanderPosition: BlockPos? = null
if (wanderDirection == null) {
val wanderOffset = RandomPos.generateRandomDirection(entity.level().random, maxDistance / 2, 0)
wanderDirection = wanderOffset.toVec3d().normalize()
isWanderTurnDirectionClockwise = entity.random.nextInt(2) > 0
wanderTurnChance = BASE_TURN_CHANCE
wanderPosition = entity.blockPosition().offset(wanderOffset.x, wanderOffset.y, wanderOffset.z)
} else {
if (entity.level().random.nextFloat() < wanderTurnChance) {
// Turn 30 degrees
wanderDirection =
wanderDirection!!.yRot(Math.PI.toFloat() / 3.0f * if (isWanderTurnDirectionClockwise) -1f else 1f)
wanderTurnChance *= 0.7
}
val wanderVec = entity.position().add(wanderDirection!!.scale(maxDistance.toDouble()))
wanderPosition = BlockPos.containing(wanderVec)
}
val wanderTarget = generateWaterSafePosToward(entity, maxDistance, wanderPosition)
if (wanderTarget != null) {
walkTarget = CobblemonWalkTarget(
wanderPosition,
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
} else {
return ObjectiveStatus.ACTIVE
}
} else {
failCount++
}
}
if (walkTarget != null) {
failCount = 0
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
?: return ObjectiveStatus.ACTIVE
movementTask = brain.fixate(
fixation = StayOutOfWaterFixation(
movementTracker = movementTracker
)
)
}
}
return ObjectiveStatus.ACTIVE
}
fun generateWaterSafePosToward(
mob: PathfinderMob,
range: Int,
targetPos: BlockPos
): BlockPos? {
for (i in 0..4) {
val candidate: BlockPos? = RandomPos.generateRandomPosTowardDirection(
mob,
range,
mob.level().random,
targetPos
)
if (candidate == null) continue
val pathType = mob.navigation.nodeEvaluator.getPathType(mob, candidate)
// Don't actually care if it can be reached, only if it's not hazardous
if (pathType == PathType.WATER || mob.getPathfindingMalus(pathType) <= 0)
return candidate
}
return null
}
companion object {
const val BASE_TURN_CHANCE = 0.8
}
class StayOutOfWaterFixation(
override val movementTracker: MovementTracker,
) : EntityFixation, MovementTrackerFixation {
var ticksOutOfWater = 0
override fun getDescription(entity: LivingEntity) = "Moving out of water"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
// Easily distracted once we are no longer touching water.
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val movementStatus = tickMovementFixation()
if (movementStatus == MovementStatus.COMPLETED) return false
if (entity.isInWater) {
ticksOutOfWater = 0
} else {
ticksOutOfWater++
if (ticksOutOfWater > 20) {
// Made it out of water, job done
return false
}
}
return movementStatus != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return MoveOutOfWater(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,166 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.*
import com.cobblemon.mod.common.api.ai.biggerbrain.*
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.phys.AABB
/**
* Looks for a resting place if the Pokemon is drowsy, and if available paths to it.
*
* @author JazzMcNade
* @since February 3rd, 2026
*/
class MoveToRestingPlace(
val ticksBetweenAttempts: Int = 80,
val horizontalSearchDistance: Expression = "14.0".asExpression(),
val verticalSearchDistance: Expression = "6.0".asExpression(),
val onlyFromStatus: Expression = "false".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var movementTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Moving to a resting place"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
}
brain.getMemory(CobblemonMemories.POKEMON_DROWSY)
?: return ObjectiveStatus.INACTIVE
if (brain.isFixation(movementTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
val hasSleepStatus = entity.pokemon.status?.status === Statuses.SLEEP
if (hasSleepStatus) return ObjectiveStatus.INACTIVE // Already sleeping
if (entity.behaviour.resting.canSleep) {
if (mainThreadRuntime.resolveBoolean(onlyFromStatus)) {
return ObjectiveStatus.BLOCKED
}
if (remainingCooldownTicks > 0 || entity.canSleepAt(entity.blockPosition().below())) {
// Can sleep where we're at, no need to go anywhere
return ObjectiveStatus.INACTIVE
}
val hSearchDistance = mainThreadRuntime.resolveDouble(horizontalSearchDistance)
val vSearchDistance = mainThreadRuntime.resolveDouble(verticalSearchDistance)
val positionList = entity.level()
.getBlockPositions(AABB.ofSize(entity.position(), hSearchDistance, vSearchDistance, hSearchDistance))
.filter(entity::canSleepAt)
val position = if (positionList.isEmpty()) null else positionList.random(1).firstOrNull()
if (position != null && brain.distract(comfortDistraction)) {
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
position,
speedMultiplier,
0
)
)
if (movementTracker != null) {
// Become fixated
movementTask = brain.fixate(
fixation = MoveToRestingPlaceFixation(
movementTracker = movementTracker,
)
)
}
} else {
return ObjectiveStatus.INACTIVE
}
return ObjectiveStatus.ACTIVE
}
return ObjectiveStatus.INACTIVE
}
class MoveToRestingPlaceFixation(
override val movementTracker: MovementTracker,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Moving to a resting place"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val movementStatus = tickMovementFixation()
if (movementStatus == MovementStatus.COMPLETED) return false
return movementStatus != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val horizontalSearchDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val verticalSearchDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
val onlyFromStatus: ExpressionOrEntityVariable = Either.left("false".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
horizontalSearchDistance,
verticalSearchDistance,
speedMultiplier,
onlyFromStatus
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return MoveToRestingPlace(
ticksBetweenAttempts = ticksBetweenAttempts,
horizontalSearchDistance = horizontalSearchDistance.asSimplifiedExpression(entity),
verticalSearchDistance = verticalSearchDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
onlyFromStatus = onlyFromStatus.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* An ongoing priority for an entity. Objectives are managed by the [BiggerBrain] system. Objectives can act out
* entirely within their own logic, or they can alter memories or create fixations for the entity to take up its
* entire attention.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface Objective {
companion object {
/**
* The idea behind this is that later objectives may like to know or respect that something impacting wandering
* has taken place.
*/
val OBJECTIVE_TAG_WANDERING = "WANDERING"
}
/** The memory types that, upon being changed, should trigger [onMemoryChanged]. */
val observedMemories: List<MemoryModuleType<*>>
get() = emptyList()
/** Gets a current description for this objective. This is purely used for the debug overlay. */
fun getDescription(entity: LivingEntity): String
/** Performs this objective's logic for a tick. */
fun perform(entity: LivingEntity, brain: BiggerBrain, activeObjectiveTags: MutableSet<String>): ObjectiveStatus
/**
* A subscription handler called for when a memory is set or removed (not expired). For a memory to trigger this
* function, it must be in [observedMemories].
*/
fun <T> onMemoryChanged(entity: LivingEntity, brain: BiggerBrain, memory: MemoryModuleType<T>, value: T?) {
// Default implementation does nothing
}
}
@@ -0,0 +1,28 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
/**
* The current status of an [Objective]. Used for the debug overlay.
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class ObjectiveStatus {
/** States that this objective owns the current fixation. */
FIXATED,
/** States that the objective's logic is ongoing and not impeded. */
ACTIVE,
/** States that the objective is not performing any meaningful logic right now but isn't actively blocked. */
INACTIVE,
/** States that there are other objectives, fixations, etc. in play which prevents the objective from being performed. */
BLOCKED,
/** States that the objective is not valid and shouldn't have been registered on the entity in the first place, such as when placed on the wrong entity type. */
INVALID
}
@@ -0,0 +1,234 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveDouble
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.GameRules
import kotlin.math.ceil
import kotlin.math.min
/**
* Paths to whatever item entity is marked by NEAREST_VISIBLE_WANTED_ITEM
* Upon reaching the target attempts to place it in held item slot
* held item slot if possible.
* Requires NEARBY_SWEET_BERRY_BUSH memory
*
* @author JazzMcNade
* @since February 8th, 2026
*/
class PickupItem(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression(),
val maxReach: Expression = "1.0".asExpression(),
) : Objective {
var collectItemTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Pickup item"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(collectItemTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
val itemEntity = entity.biggerBrain.getMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM) ?: return ObjectiveStatus.INACTIVE
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
// See if the item can be picked up without needing to path to it
val success = tryPickupItem(entity, itemEntity)
if (!success) {
// Item is too far away, need to path to it
if (remainingCooldownTicks <= 0 && brain.distract(idleBoredomDistraction)) {
remainingCooldownTicks = ticksBetweenAttempts
val horizontalHitboxRadius = maxOf(entity.boundingBox.xsize, entity.boundingBox.zsize) / 2
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
itemEntity,
speedMultiplier,
min(ceil(horizontalHitboxRadius).toInt() - 1, 1),
)
)
if (movementTracker != null) {
val lookingTracker = LookingTracker(entity = entity, lookTarget = movementTracker.walkTarget.target)
collectItemTask = brain.fixate(
fixation = PickupItemFixation(
objective = this,
itemEntity = itemEntity,
movementTracker = movementTracker,
lookingTracker = lookingTracker,
)
)
}
}
} else {
remainingCooldownTicks = ticksBetweenAttempts
}
return ObjectiveStatus.ACTIVE
}
fun tryPickupItem(entity: PokemonEntity, itemEntity: ItemEntity) : Boolean {
val maxReach = mainThreadRuntime.resolveDouble(maxReach) + maxOf(entity.boundingBox.xsize, entity.boundingBox.zsize) / 2
if (itemEntity.distanceTo(entity) > maxReach || !entity.hasLineOfSight(itemEntity)) {
return false
}
entity.brain.eraseMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM)
entity.take(itemEntity, 1) // This creates the effect of the item going into the entity along with the item pickup sound
val stack = entity.pokemon.swapHeldItem(itemEntity.item)
if (!stack.isEmpty && !entity.level().isClientSide) {
dropItem(entity, stack)
}
return true
}
class PickupItemFixation(
val objective: PickupItem,
val itemEntity: ItemEntity,
override val movementTracker: MovementTracker,
override val lookingTracker : LookingTracker,
): EntityFixation, MovementTrackerFixation, LookingTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Moving to desired item"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || (movementTracker.lastStatus == MovementStatus.COMPLETED && entity.brain.getMemorySafely(
CobblemonMemories.NEARBY_SWEET_BERRY_BUSH).orElse(null) != null)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
movementTracker.tick()
if (movementTracker.lastStatus == MovementStatus.COMPLETED || movementTracker.lastStatus == MovementStatus.FAILED) {
// May have failed but let's check if we're still close enoug to grab it
val world = entity.level()
if (entity !is PokemonEntity) return false
if (!world.gameRules.getRule(GameRules.RULE_MOBGRIEFING).get()) {
// Not allowed to alter the world
return false
}
if (!itemEntity.isAlive || !entity.pokemon.canDropHeldItem) {
return false
}
val succeeded = objective.tryPickupItem(entity, itemEntity)
if (!succeeded && movementTracker.lastStatus == MovementStatus.FAILED) {
// Cannot reach, give up for a while
entity.brain.setMemoryWithExpiry(CobblemonMemories.DISABLE_WALK_TO_WANTED_ITEM, true, 200)
entity.brain.eraseMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM)
}
return false
}
return true
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return PickupItem(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
companion object {
fun dropItem(entity: Entity, stack: ItemStack) {
val itemEntity = ItemEntity(
entity.level(),
entity.x + entity.lookAngle.x,
entity.y + 1.0,
entity.z + entity.lookAngle.z,
stack
)
itemEntity.setPickUpDelay(40)
itemEntity.setThrower(entity)
entity.playSound(SoundEvents.FOX_SPIT, 1.0f, 1.0f) // TODO: customize this sound?
entity.level().addFreshEntity(itemEntity)
}
}
}
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import kotlin.math.pow
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.BlockPosTracker
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.behavior.PositionTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.MemoryStatus
import net.minecraft.world.phys.Vec3
/**
* Randomly points toward spawn. Very easily distracted once doing so.
*
*/
class PointToSpawn(
val minDuration: Int = 20,
val maxDuration: Int = 200
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Point towards spawn"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED
} else if (!entity.brain.checkMemory(MemoryModuleType.LOOK_TARGET, MemoryStatus.REGISTERED)
|| !entity.brain.checkMemory(MemoryModuleType.WALK_TARGET, MemoryStatus.VALUE_ABSENT)
) {
return ObjectiveStatus.BLOCKED
}
val blockPos = Vec3.atCenterOf(entity.level().sharedSpawnPos).with(Direction.Axis.Y, entity.eyeY)
brain.setMemory(
MemoryModuleType.LOOK_TARGET,
BlockPosTracker(blockPos)
)
// Become fixated
fixation = brain.fixate(
IdleLookFixation(
this,
blockPos,
(minDuration..maxDuration).random()
)
)
return ObjectiveStatus.FIXATED
}
class IdleLookFixation(
val objective: PointToSpawn,
val targetPosition: Vec3,
var remainingTicks: Int
) : EntityFixation, LookingTrackerFixation {
override var lookingTracker: LookingTracker? = null
override fun getDescription(entity: LivingEntity): String {
return "Looking at spawn position ($remainingTicks ticks left)"
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PathfinderMob) {
return false
}
if (lookingTracker == null) {
lookingTracker = LookingTracker(entity, BlockPosTracker(targetPosition))
}
val lookingTracker = lookingTracker!!
remainingTicks--
lookingTracker.tick()
return remainingTicks > 0
}
}
class Config : ObjectiveConfig {
val minDuration: ExpressionOrEntityVariable = Either.left("20".asExpression())
val maxDuration: ExpressionOrEntityVariable = Either.left("80".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minDuration,
maxDuration
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val minDuration = minDuration.resolveInt(behaviourConfigurationContext.runtime)
val maxDuration = maxDuration.resolveInt(behaviourConfigurationContext.runtime)
return PointToSpawn(
minDuration = minDuration,
maxDuration = maxDuration
)
}
}
}
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.booleanVariable
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.task.SharedEntityVariables
import com.cobblemon.mod.common.api.ai.numberVariable
import com.cobblemon.mod.common.api.ai.resolveBoolean
import com.cobblemon.mod.common.api.ai.resolveFloat
import net.minecraft.tags.FluidTags
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
class StayAfloat(
val chance: Float = 0.8F
) : Objective {
override fun getDescription(entity: LivingEntity) = "Stay Afloat"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PathfinderMob) {
return ObjectiveStatus.INVALID
}
val fixation = brain.fixation
if (fixation is MovementTrackerFixation) {
// Ok if movement is in progress then we don't try staying afloat
return ObjectiveStatus.BLOCKED
}
if (entity.isInWater && (entity.getFluidHeight(FluidTags.WATER) > entity.fluidJumpThreshold) ||
(entity.isInLava && !entity.fireImmune())) {
// Cool do something
if (entity.random.nextFloat() < this.chance) {
entity.jumpControl.jump()
}
return ObjectiveStatus.ACTIVE
} else {
return ObjectiveStatus.INACTIVE
}
}
class Config : ObjectiveConfig {
val condition = booleanVariable(SharedEntityVariables.MOVEMENT_CATEGORY, "can_float", true).asExpressible()
val chance = numberVariable(SharedEntityVariables.MOVEMENT_CATEGORY, "float_chance", 0.8F).asExpressible()
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
chance
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): StayAfloat? {
return when {
condition.resolveBoolean(behaviourConfigurationContext.runtime) -> StayAfloat(chance.resolveFloat(behaviourConfigurationContext.runtime))
else -> null
}
}
}
}
@@ -0,0 +1,240 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import kotlin.math.abs
import kotlin.math.ceil
import net.minecraft.core.BlockPos
import net.minecraft.util.RandomSource
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.TamableAnimal
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.level.pathfinder.WalkNodeEvaluator
/**
* Keeps track of the owner entity, and if they are in the same world but are too far away, fixates on getting closer.
* If they are extremely far away, will attempt to teleport to them. When walking to the owner, it pauses for a short
* duration after reaching them to look at them. It's cute.
*
* @author Hiroku
* @since December 29th, 2025
*/
class StayNearOwner(
val ticksBetweenAttempts: Int = 60,
val completionRange: Expression = "4.0".asExpression(),
val maxDistance: Expression = "14.0".asExpression(),
val teleportDistance: Expression = "24.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var followTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Stay near owner"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is TamableAnimal) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(followTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
val owner = entity.owner ?: return ObjectiveStatus.INVALID
if (owner.level() != entity.level()) {
return ObjectiveStatus.INVALID
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val teleportDistance = mainThreadRuntime.resolveFloat(teleportDistance)
val maxDistance = mainThreadRuntime.resolveFloat(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val completionRange = mainThreadRuntime.resolveInt(completionRange)
val horizontalHitboxRadius = maxOf(entity.boundingBox.xsize, entity.boundingBox.zsize) / 2
val distance = entity.distanceTo(owner) - horizontalHitboxRadius
if (distance > teleportDistance) {
if (remainingCooldownTicks <= 0 && brain.distract(Distraction.FORCE)) {
remainingCooldownTicks = ticksBetweenAttempts
tryTeleport(entity, owner)
return ObjectiveStatus.ACTIVE
}
return if (remainingCooldownTicks <= 0) ObjectiveStatus.BLOCKED else ObjectiveStatus.ACTIVE
} else if (distance > maxDistance) {
if (remainingCooldownTicks <= 0 && brain.distract(comfortDistraction)) {
remainingCooldownTicks = ticksBetweenAttempts
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
owner,
speedMultiplier,
maxOf(completionRange, ceil(horizontalHitboxRadius).toInt()) - 1
)
)
if (movementTracker != null) {
followTask = brain.fixate(
fixation = FollowOwnerFixation(
entity = entity,
owner = owner,
teleportDistance = teleportDistance,
movementTracker = movementTracker
)
)
}
}
}
return ObjectiveStatus.ACTIVE
}
private fun tryTeleport(entity: TamableAnimal, owner: Entity): Boolean {
val blockPos = owner.blockPosition()
for (i in 0..9) {
val j = this.getRandomInt(entity.random, -3, 3)
val k = this.getRandomInt(entity.random, -1, 1)
val l = this.getRandomInt(entity.random, -3, 3)
val succeeded = this.tryTeleportTo(entity, owner, blockPos.x + j, blockPos.y + k, blockPos.z + l)
if (succeeded) {
return true
}
}
return false
}
private fun tryTeleportTo(entity: TamableAnimal, owner: Entity, x: Int, y: Int, z: Int): Boolean {
if (abs(x.toDouble() - owner.x) < 2.0 && abs(z - owner.z) < 2.0) {
return false
} else if (!this.canTeleportTo(entity, BlockPos(x, y, z))) {
return false
} else {
entity.moveTo(
x.toDouble() + 0.5, y.toDouble(), z.toDouble() + 0.5,
entity.yRot,
entity.xRot
)
entity.navigation.stop()
return true
}
}
private fun canTeleportTo(entity: TamableAnimal, pos: BlockPos): Boolean {
val pathNodeType = WalkNodeEvaluator.getPathTypeStatic(entity, pos.mutable())
if (pathNodeType != PathType.WALKABLE) {
return false // Could be more complex to support fliers and swimmers
} else {
val blockPos = pos.subtract(entity.blockPosition())
return entity.level().noCollision(entity, entity.boundingBox.move(blockPos))
}
}
private fun getRandomInt(random: RandomSource, min: Int, max: Int) = random.nextInt(max - min + 1) + min
class FollowOwnerFixation(
entity: PathfinderMob,
val owner: LivingEntity,
val teleportDistance: Float,
override val movementTracker: MovementTracker,
): EntityFixation, LookingTrackerFixation, MovementTrackerFixation {
// Look at the owner for some amount of time after reaching them. For cuteness!
var lingeringStareTicks = (20..40).random()
override val lookingTracker: LookingTracker = LookingTracker(entity = entity, lookTarget = EntityTracker(owner, true))
override fun getDescription(entity: LivingEntity) = "Moving to owner"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
// Easily distracted once we've reached the player.
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
if (entity.distanceTo(owner) > teleportDistance) {
// Too far away, give up, the teleport will handle it
return false
}
if (movementTracker.lastStatus == MovementStatus.COMPLETED) {
lingeringStareTicks--
return lingeringStareTicks > 0
}
return tickMovementFixation() != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val completionRange: ExpressionOrEntityVariable = Either.left("4.0".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val teleportDistance: ExpressionOrEntityVariable = Either.left("24.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
completionRange,
maxDistance,
teleportDistance,
speedMultiplier
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return StayNearOwner(
ticksBetweenAttempts = ticksBetweenAttempts,
completionRange = completionRange.asSimplifiedExpression(entity),
maxDistance = maxDistance.asSimplifiedExpression(entity),
teleportDistance = teleportDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,127 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* Walk towards parent of same species objective
*/
class WalkTowardsParent(
val minRange: Int,
val maxRange: Int,
val speed: Float
) : Objective {
var fixation: EntityFixation? = null
var cooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Following parent species"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID // its gotta be a pokemon to have a parent species
} else if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED // we are already fixated on this objectives fixation
} else if (brain.fixation != null) {
fixation = null // our brain has chosen another fixation
}
// Check to see if the cooldown has been completed
// TODO: should cooldown checks happen first? Do we only want them ticked down
if (cooldownTicks > 0) {
cooldownTicks--
return ObjectiveStatus.INACTIVE
}
// if no trusted adult is around then the objective is inactive
val adult = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT) ?: return ObjectiveStatus.INACTIVE
// If we are too close or too far then don't follow
// TODO: the too far doesn't make that much sense to me. We don't want it treating it as a herd?
val dist = entity.distanceTo(adult)
if (dist > maxRange + 1 || dist < minRange) return ObjectiveStatus.INACTIVE
// Can we comfort ourselves?
if (!brain.distract(comfortDistraction)) return ObjectiveStatus.BLOCKED
// Get our walk target and movement tracker
val walkTarget = WalkTarget(EntityTracker(adult, false), speed, minRange - 1)
val movementTracker = RegularMovementTracker.attempt(entity as PathfinderMob, walkTarget)
?: return ObjectiveStatus.INACTIVE
this.fixation = brain.fixate(
LookAndMoveFixation(
description = "Following parent",
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE), // We are very fine to ignore this movement if forced or hurt
lookingTracker = LookingTracker.forTargetEntity(entity, adult),
movementTracker = movementTracker,
onMovementComplete = { _, _ -> cooldownTicks = 60 }
)
)
return ObjectiveStatus.FIXATED // We are now fixated on
}
class Config : ObjectiveConfig {
val minRange: ExpressionOrEntityVariable = Either.left("5".asExpression())
val maxRange: ExpressionOrEntityVariable = Either.left("16".asExpression())
val speed: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minRange,
maxRange,
speed
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
if (entity !is PokemonEntity) return null
return WalkTowardsParent(
minRange = minRange.resolveInt(behaviourConfigurationContext.runtime),
maxRange = maxRange.resolveInt(behaviourConfigurationContext.runtime),
speed = speed.resolveFloat(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,210 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.WanderType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
/*
* I've scuffed the hell out of this thing. The logic for what types of wandering to do is unclear, and I haven't
* really decided whether it should be one mega function for finding a wander target and figuring out the type of
* goal in the process or if it should be cleanly separated for each type of wander target. I've done a bit of both
* and it's not pretty.
*/
class WanderAround(
val condition: Expression = "true".asExpression(),
val cooldownTicks: Int = 80,
val allowLand: Expression = "(q.entity.behaviour.moving.walk.can_walk && !q.entity.behaviour.moving.walk.avoids_land) || q.entity.behaviour.moving.fly.can_fly".asExpression(),
val allowWater: Expression = "q.entity.behaviour.moving.swim.can_swim_in_water && !q.entity.behaviour.moving.swim.avoids_water".asExpression(),
val allowAir: Expression = "q.entity.behaviour.moving.fly.can_fly && !q.entity.behaviour.moving.walk.can_walk".asExpression(),
val wanderChance: Expression = "1/(20*6)".asExpression(),
val horizontalRange: Expression = "10".asExpression(),
val verticalRange: Expression = "5".asExpression(),
val speedMultiplier: Expression = "0.35".asExpression(),
val avoidTargetingAir: Expression = "true".asExpression(),
val minimumHeight: Expression = "0".asExpression(),
val maximumHeight: Expression = "999".asExpression()
) : Objective {
var fixation: EntityFixation? = null
var remainingCooldownTicks = 10
override fun getDescription(entity: LivingEntity) = "Wander around"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
activeObjectiveTags.add(Objective.OBJECTIVE_TAG_WANDERING)
return ObjectiveStatus.FIXATED
} else if (entity !is PathfinderMob) {
return ObjectiveStatus.INVALID
} else if (Objective.OBJECTIVE_TAG_WANDERING in activeObjectiveTags) {
return ObjectiveStatus.BLOCKED
} else if (!brain.canDistract(idleBoredomDistraction)) {
return ObjectiveStatus.BLOCKED
}
fixation = null
val runtime = mainThreadRuntime
runtime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
if (!runtime.resolveBoolean(condition)) {
return ObjectiveStatus.INACTIVE
} else if (Objective.OBJECTIVE_TAG_WANDERING in activeObjectiveTags) {
return ObjectiveStatus.BLOCKED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
}
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
val wanderChance = runtime.resolveFloat(this.wanderChance) * (wanderControl?.wanderChanceMultiplier ?: 1.0F)
if (wanderChance <= 1.0F && entity.level().random.nextFloat() > wanderChance) {
return ObjectiveStatus.ACTIVE
}
val allowLand = wanderControl?.allowLand ?: runtime.resolveBoolean(allowLand)
val allowWater = wanderControl?.allowWater ?: runtime.resolveBoolean(allowWater)
val allowAir = wanderControl?.allowAir ?: runtime.resolveBoolean(allowAir)
val types = mutableSetOf<WanderType>()
if ((allowLand || allowAir) && WanderType.LAND.isValid(entity)) {
types.add(WanderType.LAND)
}
if (allowWater && WanderType.WATER.isValid(entity)) {
types.add(WanderType.WATER)
}
if (types.isEmpty()) {
return ObjectiveStatus.INVALID
}
remainingCooldownTicks = cooldownTicks
val walkTarget = types.firstNotNullOfOrNull {
it.generateWalkTarget(
entity = entity,
horizontalRange = runtime.resolveInt(horizontalRange),
verticalRange = runtime.resolveInt(verticalRange),
minimumHeight = runtime.resolveInt(minimumHeight),
maximumHeight = runtime.resolveInt(maximumHeight),
avoidTargetingAir = runtime.resolveBoolean(avoidTargetingAir),
speedMultiplier = runtime.resolveFloat(speedMultiplier),
center = wanderControl?.center,
maxAttempts = wanderControl?.maxAttempts ?: 4
)
} ?: return ObjectiveStatus.ACTIVE
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
?: return ObjectiveStatus.ACTIVE
if (brain.distract(idleBoredomDistraction)) {
movementTracker.tick()
fixation = brain.fixate(
LookAndMoveFixation(
description = "Wandering",
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE),
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(entity, walkTarget),
movementTracker = movementTracker
)
)
activeObjectiveTags.add(Objective.OBJECTIVE_TAG_WANDERING) // unsure if we need this
return ObjectiveStatus.FIXATED
}
return ObjectiveStatus.BLOCKED
}
class Config : ObjectiveConfig {
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val cooldownTicks: ExpressionOrEntityVariable = Either.left("80".asExpression())
val allowLand: ExpressionOrEntityVariable = Either.left("(q.entity.behaviour.moving.walk.can_walk && !q.entity.behaviour.moving.walk.avoids_land) || q.entity.behaviour.moving.fly.can_fly".asExpression())
val allowWater: ExpressionOrEntityVariable = Either.left("q.entity.behaviour.moving.swim.can_swim_in_water && !q.entity.behaviour.moving.swim.avoids_water".asExpression())
val allowAir: ExpressionOrEntityVariable = Either.left("q.entity.behaviour.moving.fly.can_fly && !q.entity.behaviour.moving.walk.can_walk".asExpression())
val wanderChance: ExpressionOrEntityVariable = Either.left("1/(20*6)".asExpression())
val horizontalRange: ExpressionOrEntityVariable = Either.left("10".asExpression())
val verticalRange: ExpressionOrEntityVariable = Either.left("5".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.35".asExpression())
val avoidTargetingAir: ExpressionOrEntityVariable = Either.left("true".asExpression())
val minimumHeight: ExpressionOrEntityVariable = Either.left("0".asExpression())
val maximumHeight: ExpressionOrEntityVariable = Either.left("999".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(
condition,
cooldownTicks,
allowLand,
allowWater,
allowAir,
wanderChance,
horizontalRange,
verticalRange,
speedMultiplier,
avoidTargetingAir,
minimumHeight,
maximumHeight
).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return WanderAround(
condition = condition.asSimplifiedExpression(entity),
cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime),
allowLand = allowLand.asSimplifiedExpression(entity),
allowWater = allowWater.asSimplifiedExpression(entity),
allowAir = allowAir.asSimplifiedExpression(entity),
wanderChance = wanderChance.asSimplifiedExpression(entity),
horizontalRange = horizontalRange.asSimplifiedExpression(entity),
verticalRange = verticalRange.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
avoidTargetingAir = avoidTargetingAir.asSimplifiedExpression(entity),
minimumHeight = minimumHeight.asSimplifiedExpression(entity),
maximumHeight = maximumHeight.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,90 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Senses whether the entity is battling or not. Maintains the BATTLING_POKEMON memory.
*
* @author Hiroku
* @since December 29th, 2025
*/
class BattlingPokemonSense(
var cooldownTicks: Int = 2
) : Sense {
override var ticksUntilNextExecution: Int = 10
override val memories: Set<MemoryModuleType<*>> = setOf(CobblemonMemories.BATTLING_POKEMON)
override fun merge(other: Sense): Boolean {
if (other is BattlingPokemonSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
val battles = when (entity) {
is PokemonEntity -> entity.battleId?.let { BattleRegistry.getBattle(it) }?.let { listOf(it) } ?: emptyList()
is NPCEntity -> entity.battleIds.mapNotNull(BattleRegistry::getBattle)
else -> emptyList()
}
val entityUUIDs = if (entity is PokemonEntity) { // Pokemon can look at opponents, never allies
battles.flatMap { battle ->
val actor = battle.getActor(entity)
if (actor != null) {
actor.getSide().getOppositeSide().activePokemon.mapNotNull { it.battlePokemon?.entity?.uuid }
} else {
emptyList()
}
}
} else if (entity is NPCEntity) { // NPCs can look at any of the pokemon in play
battles.flatMap { it.activePokemon }.mapNotNull { it.battlePokemon?.entity?.uuid }
} else {
emptyList()
}
brain.setMemory(CobblemonMemories.BATTLING_POKEMON, entityUUIDs)
if (entityUUIDs.isEmpty() && entity is PokemonEntity) {
brain.eraseMemoryIfPresent(CobblemonMemories.TARGETED_BATTLE_POKEMON)
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("2".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return BattlingPokemonSense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,159 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.server.level.ServerLevel
import net.minecraft.tags.PoiTypeTags
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.village.poi.PoiManager
import net.minecraft.world.entity.ai.village.poi.PoiRecord
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.entity.BeehiveBlockEntity
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
class BeeHiveSense(
private var cooldownTicks: Int = SCAN_INTERVAL
) : Sense {
override var ticksUntilNextExecution: Int = cooldownTicks
override val memories = setOf(
CobblemonMemories.HIVE_LOCATION,
CobblemonMemories.HIVE_BLACKLIST,
)
override fun merge(other: Sense): Boolean {
if (other is BeeHiveSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
val world = entity.level() as? ServerLevel ?: return
val brain = entity.brain
val currentHive = brain.getMemory(CobblemonMemories.HIVE_LOCATION).orElse(null)
if (currentHive != null) {
val state = world.getBlockState(currentHive)
if (!isValidHive(state) || !hasReachableAdjacentSide(world, currentHive)) {
brain.eraseMemory(CobblemonMemories.HIVE_LOCATION)
} else {
return // We already have a valid hive, no need to search for another
}
}
var closestHivePos: BlockPos? = null
val list = findNearbyHivesWithSpace(entity)
if (!list.isEmpty()) {
val blackList = brain.getMemory(CobblemonMemories.HIVE_BLACKLIST).orElse(emptyList())
for (blockPos in list) {
if (blackList.contains(blockPos)) continue
if (hasReachableAdjacentSide(world, blockPos)) {
closestHivePos = blockPos
break
}
}
if (closestHivePos == null) {
brain.eraseMemory(CobblemonMemories.HIVE_BLACKLIST)
closestHivePos = list.first()
}
}
if (closestHivePos != null) {
brain.setMemory(CobblemonMemories.HIVE_LOCATION, closestHivePos)
}
}
private fun isValidHive(state: BlockState): Boolean {
return isHiveBlock(state)
}
private fun isHiveBlock(state: BlockState): Boolean {
return state.`is`(Blocks.BEEHIVE) || state.`is`(Blocks.BEE_NEST)
}
private fun hasReachableAdjacentSide(world: ServerLevel, pos: BlockPos): Boolean {
for (dir in Direction.entries) {
val adjacentPos = pos.relative(dir)
if (world.isEmptyBlock(adjacentPos)) {
return true
}
}
return false
}
private fun findNearbyHivesWithSpace(entity: PokemonEntity): List<BlockPos> {
val blockPos = entity.blockPosition()
val poiManager = (entity.level() as ServerLevel).poiManager
val stream = poiManager.getInRange(
{ holder -> holder.`is`(PoiTypeTags.BEE_HOME) },
blockPos,
20,
PoiManager.Occupancy.ANY
)
return stream
.map(PoiRecord::getPos)
.filter { pos -> doesHiveHaveSpace(pos, entity.level()) }
.sorted { pos1, pos2 -> pos1.distSqr(blockPos).toInt() - pos2.distSqr(blockPos).toInt() }
.toList()
}
private fun doesHiveHaveSpace(hivePos: BlockPos, world: Level): Boolean {
val blockEntity: BlockEntity? = world.getBlockEntity(hivePos)
if (blockEntity is BeehiveBlockEntity) {
return !blockEntity.isFull
} else {
return false
}
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return BeeHiveSense(
cooldownTicks = cooldownTicks
)
}
}
companion object {
const val SCAN_INTERVAL = 40
}
}
@@ -0,0 +1,84 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.Mob
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
/**
* Senses if there is an entity this enties owner needs defending from
*
* @author Jack
* @since April 12th, 2026
*/
class DefendOwnerSense(
var cooldownTicks: Int = 10
) : Sense {
override var ticksUntilNextExecution = cooldownTicks
override val memories = setOf(CobblemonMemories.NEAREST_VISIBLE_ATTACKER, MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
override fun merge(other: Sense): Boolean {
if (other is DefendOwnerSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
val owner = entity.owner ?: return
brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)?.let { visibleMobs ->
setNearestAttacker(entity, visibleMobs, owner, brain)
}
}
private fun setNearestAttacker(entity: PokemonEntity, visibleMobs: NearestVisibleLivingEntities, owner: LivingEntity, brain: BiggerBrain) {
val nearestAttacker = visibleMobs.findClosest { livingEntity ->
if (livingEntity is ServerPlayer) return@findClosest false
if (livingEntity.lastHurtMob == owner) return@findClosest true
if (livingEntity is Mob && livingEntity.target == owner) return@findClosest true
val mobAttackTarget = livingEntity.brain.getMemorySafely(MemoryModuleType.ATTACK_TARGET)
if (mobAttackTarget.isPresent && mobAttackTarget.get() == owner) return@findClosest true
false
}.orElse(null)
if (nearestAttacker != null) {
brain.setMemory(CobblemonMemories.NEAREST_VISIBLE_ATTACKER, nearestAttacker)
} else {
brain.eraseMemoryIfPresent(CobblemonMemories.NEAREST_VISIBLE_ATTACKER)
}
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("10".asExpression())
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
DefendOwnerSense(cooldownTicks.resolveInt(behaviourConfigurationContext.runtime))
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Senses when the Pokémon is in a situation that would make it ready to sleep.
* Either by choice (nighttime) or by force (battle/spawning with sleep status)
*
* @author Hiroku
* @since March 23rd, 2024
*/
class DrowsySense(
var cooldownTicks: Int = 20
) : Sense {
override var ticksUntilNextExecution: Int = 20
override val memories = setOf(CobblemonMemories.POKEMON_DROWSY)
override fun merge(other: Sense): Boolean {
if (other is DrowsySense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
if (entity !is PokemonEntity) {
return
}
val world = entity.level()
val rest = entity.behaviour.resting
val isDrowsy = brain.getMemory(CobblemonMemories.POKEMON_DROWSY) ?: false
val hurtLately = brain.hasMemoryValue(MemoryModuleType.HURT_BY)
val shouldBeDrowsy = rest.canSleep && !hurtLately && (world.dayTime.toInt() % 24000) in rest.times && !brain.hasMemoryValue(MemoryModuleType.ANGRY_AT)
val forcedAsleep = entity.pokemon.status?.status == Statuses.SLEEP
if (entity.isBattling) {
if (!isDrowsy && forcedAsleep) {
brain.setMemory(CobblemonMemories.POKEMON_DROWSY, true)
} else if (isDrowsy && !forcedAsleep) {
brain.eraseMemory(CobblemonMemories.POKEMON_DROWSY)
}
} else {
if (!isDrowsy && shouldBeDrowsy && entity.random.nextFloat() < rest.drowsyChance) {
brain.setMemory(CobblemonMemories.POKEMON_DROWSY, true)
} else if (isDrowsy && !shouldBeDrowsy) {
brain.eraseMemory(CobblemonMemories.POKEMON_DROWSY)
} else if (isDrowsy && entity.random.nextFloat() < rest.rouseChance) {
brain.eraseMemory(CobblemonMemories.POKEMON_DROWSY)
}
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("20".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return DrowsySense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.distanceTo
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.core.Vec3i
import net.minecraft.server.level.ServerLevel
import net.minecraft.tags.BlockTags
import net.minecraft.tags.PoiTypeTags
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.village.poi.PoiManager
import net.minecraft.world.entity.ai.village.poi.PoiRecord
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.DoublePlantBlock
import net.minecraft.world.level.block.entity.BeehiveBlockEntity
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.properties.BlockStateProperties
import net.minecraft.world.level.block.state.properties.DoubleBlockHalf
class FlowerSense(
private var cooldownTicks: Int = SCAN_INTERVAL
) : Sense {
override var ticksUntilNextExecution: Int = cooldownTicks
override val memories = setOf(
CobblemonMemories.NEARBY_FLOWER,
CobblemonMemories.HAS_NECTAR,
)
override fun merge(other: Sense): Boolean {
if (other is FlowerSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
val brain = entity.brain
val world = entity.level()
// Check curr memory
val currPos = brain.getMemorySafely(CobblemonMemories.NEARBY_FLOWER).orElse(null)
if (currPos != null && isFlower(entity.level().getBlockState(currPos)) && entity.distanceTo(currPos) <= 32) {
return
}
val searchRadius = 5
val centerPos = entity.blockPosition()
var flowerPos: BlockPos? = null
var shortestDist = Double.MAX_VALUE
BlockPos.betweenClosedStream(
centerPos.offset(-searchRadius, -2, -searchRadius),
centerPos.offset(searchRadius, 2, searchRadius)
).forEach { pos ->
val state = world.getBlockState(pos)
if (isFlower(state)) {
val distance = pos.distSqr(Vec3i(centerPos.x, centerPos.y, centerPos.z))
if (distance < shortestDist) {
flowerPos = BlockPos(pos)
shortestDist = distance
}
}
}
if (flowerPos != null) {
brain.setMemory(CobblemonMemories.NEARBY_FLOWER, flowerPos)
} else {
brain.eraseMemory(CobblemonMemories.NEARBY_FLOWER)
}
}
private fun isFlower(state: BlockState): Boolean {
// Borrowed from Bee.class
if (state.hasProperty(BlockStateProperties.WATERLOGGED) && state.getValue(
BlockStateProperties.WATERLOGGED
) as Boolean
) {
return false
} else if (state.`is`(BlockTags.FLOWERS)) {
if (state.`is`(Blocks.SUNFLOWER)) {
return state.getValue(DoublePlantBlock.HALF) == DoubleBlockHalf.UPPER
} else {
return true
}
} else {
return false
}
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return FlowerSense(
cooldownTicks = cooldownTicks
)
}
}
companion object {
const val SCAN_INTERVAL = 40
}
}
@@ -0,0 +1,92 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.HurtDistraction
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Maintains memory of the last entity that hurt this entity.
*
* @author Hiroku
* @since December 29th, 2025
*/
class HurtBySense(
var cooldownTicks: Int = 2
) : Sense {
var lastDamageSource: DamageSource? = null
override var ticksUntilNextExecution: Int = 1
override val memories = setOf(MemoryModuleType.HURT_BY, MemoryModuleType.HURT_BY_ENTITY)
override fun merge(other: Sense): Boolean {
if (other is HurtBySense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
val damageSource = entity.lastDamageSource
if (damageSource === lastDamageSource) {
ticksUntilNextExecution = cooldownTicks
return
}
if (damageSource != null) {
brain.setMemory(MemoryModuleType.HURT_BY, entity.lastDamageSource)
val attacker = damageSource.entity
if (attacker is LivingEntity) {
brain.setMemory(MemoryModuleType.HURT_BY_ENTITY, attacker)
}
} else {
brain.eraseMemoryIfPresent(MemoryModuleType.HURT_BY)
}
// so apparently it remembers the entity that hurt them even if it was forever ago? fair enough I guess. that's vanilla for you.
brain.getMemory(MemoryModuleType.HURT_BY_ENTITY)?.let { livingEntity ->
if (!livingEntity.isAlive || livingEntity.level() != entity.level()) {
brain.eraseMemory(MemoryModuleType.HURT_BY_ENTITY)
}
}
if (damageSource != null && lastDamageSource !== damageSource) {
lastDamageSource = damageSource
brain.distract(HurtDistraction(damageSource))
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("2".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return HurtBySense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonPoiTypes
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.net.messages.client.animation.PlayPosableAnimationPacket
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.core.Holder
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.village.poi.PoiManager
import net.minecraft.world.entity.ai.village.poi.PoiType
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.entity.JukeboxBlockEntity
/**
* Senses nearby jukeboxes that are currently playing music.
*
*/
class JukeboxSense(
var condition: Expression,
var radiusXZ: Double = 16.0,
var radiusY: Double = 16.0,
var cooldownTicks: Int = 20 * 5
) : Sense {
override var ticksUntilNextExecution: Int = 50
override val memories = setOf(MemoryModuleType.DANCING)
override fun merge(other: Sense): Boolean {
if (other is JukeboxSense) {
this.condition = other.condition
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.radiusXZ = other.radiusXZ
this.radiusY = other.radiusY
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (!brain.runtime.resolveBoolean(condition)) {
return
}
val world = entity.level()
val poiManager = (entity.level() as ServerLevel).poiManager
val jukeboxPositions = poiManager.findAll(
{ holder: Holder<PoiType> -> holder.`is`(CobblemonPoiTypes.JUKEBOX_KEY) },
{ true },
entity.blockPosition(),
10,
PoiManager.Occupancy.ANY
).toList()
val jukeboxPos = jukeboxPositions.firstOrNull() { blockPos ->
if (world.getBlockState(blockPos).block != Blocks.JUKEBOX) return@firstOrNull false
val blockEntity = world.getBlockEntity(blockPos)
if (blockEntity !is JukeboxBlockEntity) return@firstOrNull false
!blockEntity.theItem.isEmpty
}
brain.setMemory(MemoryModuleType.DANCING, jukeboxPos != null)
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var radiusXZ: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var radiusY: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
radiusXZ,
radiusY,
cooldownTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return JukeboxSense(
condition = condition.asSimplifiedExpression(entity),
radiusXZ = radiusXZ.resolveDouble(behaviourConfigurationContext.runtime),
radiusY = radiusY.resolveDouble(behaviourConfigurationContext.runtime),
cooldownTicks = cooldownTicks.resolveDouble(behaviourConfigurationContext.runtime).toInt()
)
}
}
}
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
/**
* A sense that checks if an NPC is currently in a battle. Maintains the NPC_BATTLING memory.
*
* @author Hiroku
* @since December 29th, 2025
*/
class NPCBattlingSense(
var cooldownTicks: Int = 10
) : Sense {
override var ticksUntilNextExecution: Int = 20
override val memories = setOf(CobblemonMemories.NPC_BATTLING)
override fun merge(other: Sense): Boolean {
if (other is NPCBattlingSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
if (entity !is NPCEntity) {
return // Surely they didn't put this on a non-NPC
}
val isBattling = entity.isInBattle()
if (isBattling) {
brain.setMemoryIfChanged(CobblemonMemories.NPC_BATTLING, value = true)
} else {
brain.eraseMemoryIfPresent(CobblemonMemories.NPC_BATTLING)
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("2".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return NPCBattlingSense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import java.util.function.Predicate
import java.util.function.ToDoubleFunction
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
/**
* Senses nearby entities. Maintains the NEAREST_LIVING_ENTITIES and NEAREST_VISIBLE_LIVING_ENTITIES memories.
*
* @author Hiroku
* @since December 29th, 2025
*/
class NearbyEntitiesSense(
var condition: Expression,
var radiusXZ: Double = 16.0,
var radiusY: Double = 16.0,
var cooldownTicks: Int = 20 * 5
) : Sense {
override var ticksUntilNextExecution: Int = 50
override val memories = setOf(MemoryModuleType.NEAREST_LIVING_ENTITIES, MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
override fun merge(other: Sense): Boolean {
if (other is NearbyEntitiesSense) {
this.condition = other.condition
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.radiusXZ = other.radiusXZ
this.radiusY = other.radiusY
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (!brain.runtime.resolveBoolean(condition)) {
return
}
val level = entity.level()
val aABB = entity.boundingBox.inflate(radiusXZ, radiusY, radiusXZ)
val list = level.getEntitiesOfClass(LivingEntity::class.java, aABB, Predicate { it !== entity && it!!.isAlive })
list.sortWith(Comparator.comparingDouble(ToDoubleFunction { it.distanceToSqr(entity) }))
brain.setMemory(MemoryModuleType.NEAREST_LIVING_ENTITIES, list)
brain.setMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES, NearestVisibleLivingEntities(entity, list))
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var radiusXZ: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var radiusY: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
radiusXZ,
radiusY,
cooldownTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return NearbyEntitiesSense(
condition = condition.asSimplifiedExpression(entity),
radiusXZ = radiusXZ.resolveDouble(behaviourConfigurationContext.runtime),
radiusY = radiusY.resolveDouble(behaviourConfigurationContext.runtime),
cooldownTicks = cooldownTicks.resolveDouble(behaviourConfigurationContext.runtime).toInt()
)
}
}
}
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.AgeableMob
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
/**
* Senses when the Pokémon is near an adult of the same species. Maintains the NEAREST_VISIBLE_ADULT memory.
*
* @author broccoli
* @since May 15th, 2024
*/
class PokemonAdultSense(
var condition: Expression,
var cooldownTicks: Int = 100
) : Sense {
override var ticksUntilNextExecution: Int = 100
override val memories = setOf(MemoryModuleType.NEAREST_VISIBLE_ADULT, MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
override fun merge(other: Sense): Boolean {
if (other is PokemonAdultSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity || !brain.runtime.resolveBoolean(condition)) {
return
}
brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)?.let { visibleMobs ->
setNearestPokemonAdult(entity, visibleMobs, brain)
}
}
private fun setNearestPokemonAdult(entity: PokemonEntity, visibleMobs: NearestVisibleLivingEntities, brain: BiggerBrain) {
val nearestAdult = visibleMobs.findClosest { mob ->
targetIsValidForChild(entity, mob)
}.map { mob -> mob as AgeableMob }.orElse(null)
if (nearestAdult == null && brain.hasMemoryValue(MemoryModuleType.NEAREST_VISIBLE_ADULT)) {
brain.eraseMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT)
} else if (nearestAdult != null && brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT) != nearestAdult) {
brain.setMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT, nearestAdult)
}
}
private fun targetIsValidForChild(child: PokemonEntity, entity: LivingEntity): Boolean {
val potentialParent = entity as? PokemonEntity ?: return false
val childSpecies = child.pokemon.species.resourceIdentifier
var preEvolution = potentialParent.pokemon.preEvolution
while (preEvolution != null) {
if (childSpecies == preEvolution.species.resourceIdentifier) {
return true
}
preEvolution = preEvolution.species.preEvolution
}
return false
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return PokemonAdultSense(
condition = condition.asSimplifiedExpression(entity),
cooldownTicks = cooldownTicks
)
}
}
}
@@ -0,0 +1,130 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.ai.ObtainableItem
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.findMatchingEntry
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.getObjectList
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.level.GameRules
import java.util.Optional
/**
* Senses nearby item entities. Returns the closest item that the Pokemon would desire to pickup.
*
* @author JazzMcNade
* @since February 15th, 2026
*/
class PokemonItemSense(
var condition: Expression,
var radiusXZ: Double = 16.0,
var radiusY: Double = 16.0,
var cooldownTicks: Int = 20 * 5
) : Sense {
override var ticksUntilNextExecution: Int = 50
override val memories =
setOf(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM, CobblemonMemories.DISABLE_WALK_TO_WANTED_ITEM)
override fun merge(other: Sense): Boolean {
if (other is PokemonItemSense) {
this.condition = other.condition
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.radiusXZ = other.radiusXZ
this.radiusY = other.radiusY
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity || !brain.runtime.resolveBoolean(condition)) {
return
}
val world = entity.level()
if (!world.gameRules.getBoolean(GameRules.RULE_MOBGRIEFING) || !entity.pokemon.canDropHeldItem || entity.brain.getMemorySafely(
CobblemonMemories.DISABLE_WALK_TO_WANTED_ITEM
).orElse(false)
) {
// Mob griefing is disabled, the Pokemon cannot swap out its item, or it's exhausted from attempting to go to an unreachable item
// so don't bother to search
return
}
val pickupItems = entity.config.getObjectList<ObtainableItem>(PICKUP_ITEMS)
val heldItemValue =
pickupItems.findMatchingEntry(entity.registryAccess(), entity.pokemon.heldItem())?.pickupPriority ?: 0
if (heldItemValue >= (pickupItems.maxOfOrNull { it.pickupPriority } ?: 0)) {
// It's already holding the highest value item it can have, no need to look for better.
return
}
val list = world.getEntitiesOfClass(
ItemEntity::class.java,
entity.boundingBox.inflate(radiusXZ, radiusY, radiusXZ)
) {
(pickupItems.findMatchingEntry(entity.registryAccess(), it.item)?.pickupPriority ?: 0) > heldItemValue
&& entity.hasLineOfSight(it)
}
// Find the closest item to the entity
val nearestItemEntity = list.minByOrNull { it.distanceTo(entity) }
entity.getBrain()
.setMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM, Optional.ofNullable(nearestItemEntity))
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var radiusXZ: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var radiusY: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
radiusXZ,
radiusY,
cooldownTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return PokemonItemSense(
condition = condition.asSimplifiedExpression(entity),
radiusXZ = radiusXZ.resolveDouble(behaviourConfigurationContext.runtime),
radiusY = radiusY.resolveDouble(behaviourConfigurationContext.runtime),
cooldownTicks = cooldownTicks.resolveDouble(behaviourConfigurationContext.runtime).toInt()
)
}
}
companion object {
const val PICKUP_ITEMS = "pickup_items"
}
}
@@ -0,0 +1,131 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.block.SaccharineLeafBlock
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.distanceTo
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.core.Vec3i
import net.minecraft.server.level.ServerLevel
import net.minecraft.tags.PoiTypeTags
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.village.poi.PoiManager
import net.minecraft.world.entity.ai.village.poi.PoiRecord
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.entity.BeehiveBlockEntity
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.properties.BlockStateProperties
class SaccLeafSense(
private var cooldownTicks: Int = SCAN_INTERVAL
) : Sense {
override var ticksUntilNextExecution: Int = cooldownTicks
override val memories = setOf(
CobblemonMemories.NEARBY_SACC_LEAVES,
)
override fun merge(other: Sense): Boolean {
if (other is SaccLeafSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
val brain = entity.brain
val searchRadius = 7
val tooFarDistance = 30
val wayTooFarDistance = 64
val currPos: BlockPos? = brain.getMemorySafely(CobblemonMemories.NEARBY_SACC_LEAVES).orElse(null)
if (currPos != null && isValidLeafBlock(entity.level().getBlockState(currPos))) {
val distance = entity.distanceTo(currPos)
if (distance <= tooFarDistance) {
return
} else if (distance > wayTooFarDistance) {
brain.eraseMemory(CobblemonMemories.NEARBY_SACC_LEAVES)
}
}
val centerPos = entity.blockPosition()
var leavesPos: BlockPos? = null
var shortestDist = Double.MAX_VALUE
val world = entity.level()
BlockPos.betweenClosedStream(
centerPos.offset(-searchRadius, -2, -searchRadius),
centerPos.offset(searchRadius, searchRadius, searchRadius)
).forEach { pos ->
val state = world.getBlockState(pos)
if (isValidLeafBlock(state)) {
val distance = pos.distSqr(Vec3i(centerPos.x, centerPos.y, centerPos.z))
if (distance < shortestDist) {
leavesPos = BlockPos(pos)
shortestDist = distance
}
}
}
if (leavesPos != null) {
brain.setMemory(CobblemonMemories.NEARBY_SACC_LEAVES, leavesPos)
} else {
brain.eraseMemory(CobblemonMemories.NEARBY_SACC_LEAVES)
}
}
private fun isValidLeafBlock(state: BlockState): Boolean {
if (state.block !is SaccharineLeafBlock) return false
if (state.hasProperty(BlockStateProperties.WATERLOGGED) && state.getValue(
BlockStateProperties.WATERLOGGED
) as Boolean
) {
return false
}
return state.getValue(SaccharineLeafBlock.AGE) != SaccharineLeafBlock.MAX_AGE
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return SaccLeafSense(
cooldownTicks = cooldownTicks
)
}
}
companion object {
const val SCAN_INTERVAL = 40
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* A sense that an entity can use to gather information and store it in its brain's memory. This is an analog to a
* Minecraft SensorType. Unlike SensorTypes, Senses are instantiated per entity and can handle cooldowns in a more
* bespoke way. The remaining cooldown time is something that is set by the sense itself rather than it being forced,
* so the cooldown can differ.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface Sense {
companion object {
val types = mutableMapOf(
cobblemonResource("battling_pokemon") to BattlingPokemonSense::class.java,
cobblemonResource("drowsy") to DrowsySense::class.java,
cobblemonResource("nearby_entities") to NearbyEntitiesSense::class.java,
cobblemonResource("npc_battling") to NPCBattlingSense::class.java,
cobblemonResource("pokemon_adult") to PokemonAdultSense::class.java,
cobblemonResource("hurt_by") to HurtBySense::class.java,
cobblemonResource("jukebox_playing") to JukeboxSense::class.java,
cobblemonResource("nearby_sweet_berry_bush") to SweetBerryBushSense::class.java,
cobblemonResource("pokemon_nearby_wanted_item") to PokemonItemSense.Config::class.java,
cobblemonResource("flower_sense") to FlowerSense.Config::class.java,
cobblemonResource("beehive_sense") to BeeHiveSense.Config::class.java,
cobblemonResource("sacc_leaf_sense") to SaccLeafSense.Config::class.java,
)
}
/** The ticks until it will next be ticked. This is also displayed in the debug overlay. */
var ticksUntilNextExecution: Int
/** The set of memories that this sense may write to or read from. This ensures they are registered in the brain. */
val memories: Set<MemoryModuleType<*>>
/** Performs the sensing logic. Alter [ticksUntilNextExecution] to apply a cooldown if necessary. */
fun tick(entity: LivingEntity, brain: BiggerBrain)
/** Attempts to merge the [other] Sense into this one. Returns true if it was merged and therefore should not be added to the brain separately. */
fun merge(other: Sense): Boolean
}
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.CaveVines
import net.minecraft.world.level.block.SweetBerryBushBlock
import net.minecraft.world.level.block.state.BlockState
import java.util.Optional
class SweetBerryBushSense(
private var cooldownTicks: Int = SCAN_INTERVAL
) : Sense {
override var ticksUntilNextExecution: Int = SCAN_INTERVAL
override val memories = setOf(
CobblemonMemories.NEARBY_SWEET_BERRY_BUSH,
CobblemonMemories.DISABLE_WALK_TO_BERRY_BUSH,
)
override fun merge(other: Sense): Boolean {
if (other is SweetBerryBushSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
val world = entity.level() as? ServerLevel ?: return
entity.brain.getMemorySafely(CobblemonMemories.DISABLE_WALK_TO_BERRY_BUSH).orElse(false) ?: return
val nearestBush = findNearestBush(world, entity.blockPosition())
if (!nearestBush.isEmpty) {
entity.brain.setMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH, nearestBush)
} else {
entity.brain.eraseMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH)
}
}
private fun findNearestBush(level: ServerLevel, origin: BlockPos): Optional<BlockPos> {
var closest: BlockPos? = null
var closestDistSq = Double.MAX_VALUE
for (pos in BlockPos.betweenClosed(origin.offset(-SCAN_RADIUS_HORIZONTAL, 1 - SCAN_RADIUS_VERTICAL, -SCAN_RADIUS_HORIZONTAL),
origin.offset(SCAN_RADIUS_HORIZONTAL, SCAN_RADIUS_VERTICAL - 1, SCAN_RADIUS_HORIZONTAL))) {
val state: BlockState = level.getBlockState(pos)
if ((state.`is`(Blocks.SWEET_BERRY_BUSH) && state.getValue(SweetBerryBushBlock.AGE) >= 2)
|| (CaveVines.hasGlowBerries(state))) {
val distSq = pos.distSqr(origin)
if (distSq < closestDistSq) {
closest = pos.immutable()
closestDistSq = distSq
}
}
}
return Optional.ofNullable(closest)
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return SweetBerryBushSense(
// condition = condition.asSimplifiedExpression(entity),
cooldownTicks = cooldownTicks
)
}
}
companion object {
const val SCAN_RADIUS_HORIZONTAL = 10
const val SCAN_RADIUS_VERTICAL = 1
const val SCAN_INTERVAL = 40
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
class AddObjectivesConfig : BehaviourConfig {
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val objectivesByPriority: Map<Int, List<ObjectiveConfig>> = mapOf()
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(condition).asVariables() + objectivesByPriority
.values
.flatten()
.flatMap { it.getVariables(entity, behaviourConfigurationContext) }
}
override fun configure(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext){
if (!checkCondition(behaviourConfigurationContext, condition)) return
for ((priority, objectiveConfigs) in objectivesByPriority) {
val objectives = objectiveConfigs.mapNotNull { it.create(entity, behaviourConfigurationContext) }
val priorityObjectives = behaviourConfigurationContext.objectives.getOrPut(priority) { mutableListOf() }
priorityObjectives.addAll(objectives)
}
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
class AddSensesConfig : BehaviourConfig {
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val senses: List<SenseConfig> = listOf()
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(condition).asVariables() + senses.flatMap { it.getVariables(entity, behaviourConfigurationContext) }
}
override fun configure(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) {
if (!checkCondition(behaviourConfigurationContext, condition)) {
return
}
behaviourConfigurationContext.addSenses(senses.mapNotNull { it.create(entity, behaviourConfigurationContext) })
}
}
@@ -35,9 +35,11 @@ import net.minecraft.world.entity.LivingEntity
*/
interface BehaviourConfig {
companion object {
val types = mutableMapOf<ResourceLocation, Class<out BehaviourConfig>>(
val types = mutableMapOf(
cobblemonResource("script") to ScriptBehaviourConfig::class.java,
cobblemonResource("add_tasks_to_activity") to AddTasksToActivity::class.java,
cobblemonResource("add_objectives") to AddObjectivesConfig::class.java,
cobblemonResource("add_senses") to AddSensesConfig::class.java,
cobblemonResource("apply_behaviours") to ApplyBehaviours::class.java,
cobblemonResource("set_default_activity") to SetDefaultActivity::class.java,
cobblemonResource("set_core_activities") to SetCoreActivities::class.java,
@@ -0,0 +1,73 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.CircleAround
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Dance
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.DefendOwner
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.EatGrass
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.EatHeldItem
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.FocusDuringBattle
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.GatherNectar
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.GoToSleep
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.HarvestSweetBerryBush
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Herd
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Flock
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.LookAtNearbyEntities
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.MaintainFluidY
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.MoveIntoWater
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Objective
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.StayAfloat
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.StayNearOwner
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.MoveOutOfWater
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.MoveToRestingPlace
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.PickupItem
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.WanderAround
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.JumpOutOfWater
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.PointToSpawn
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.WalkTowardsParent
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.entity.LivingEntity
interface ObjectiveConfig {
companion object {
val types: MutableMap<ResourceLocation, Class<out ObjectiveConfig>> = mutableMapOf(
cobblemonResource("focus_during_battle") to FocusDuringBattle.Config::class.java,
cobblemonResource("look_at_nearby_entities") to LookAtNearbyEntities.Config::class.java,
cobblemonResource("stay_near_owner") to StayNearOwner.Config::class.java,
cobblemonResource("wander_around") to WanderAround.Config::class.java,
cobblemonResource("eat_grass") to EatGrass.Config::class.java,
cobblemonResource("herd") to Herd.Config::class.java,
cobblemonResource("flock") to Flock.Config::class.java,
cobblemonResource("stay_afloat") to StayAfloat.Config::class.java,
cobblemonResource("maintain_fluid_y") to MaintainFluidY.Config::class.java,
cobblemonResource("move_out_of_water") to MoveOutOfWater.Config::class.java,
cobblemonResource("move_into_water") to MoveIntoWater.Config::class.java,
cobblemonResource("jump_out_of_water") to JumpOutOfWater.Config::class.java,
cobblemonResource("move_to_resting_place") to MoveToRestingPlace.Config::class.java,
cobblemonResource("go_to_sleep") to GoToSleep.Config::class.java,
cobblemonResource("harvest_sweet_berry_bush") to HarvestSweetBerryBush.Config::class.java,
cobblemonResource("pickup_item") to PickupItem.Config::class.java,
cobblemonResource("eat_held_item") to EatHeldItem.Config::class.java,
cobblemonResource("gather_nectar") to GatherNectar.Config::class.java,
cobblemonResource("dance") to Dance.Config::class.java,
cobblemonResource("defend_owner") to DefendOwner.Config::class.java,
cobblemonResource("point_to_spawn") to PointToSpawn.Config::class.java,
cobblemonResource("circle_around") to CircleAround.Config::class.java,
cobblemonResource("walk_to_parent") to WalkTowardsParent.Config::class.java,
)
}
/** The variables that this objective config uses. These are used to declare variables on the entity cleanly. */
fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): List<MoLangConfigVariable>
fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective?
}
@@ -0,0 +1,58 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config.sense
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.BattlingPokemonSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.BeeHiveSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.DefendOwnerSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.DrowsySense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.FlowerSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.HurtBySense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.JukeboxSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.NPCBattlingSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.NearbyEntitiesSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.PokemonAdultSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.PokemonItemSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.SaccLeafSense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.Sense
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.SweetBerryBushSense
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.world.entity.LivingEntity
/**
* Creates a [Sense] for an entity.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface SenseConfig {
companion object {
val types = mutableMapOf(
cobblemonResource("nearby_entities") to NearbyEntitiesSense.Config::class.java,
cobblemonResource("defend_owner") to DefendOwnerSense.Config::class.java,
cobblemonResource("drowsy") to DrowsySense.Config::class.java,
cobblemonResource("hurt_by") to HurtBySense.Config::class.java,
cobblemonResource("jukebox_playing") to JukeboxSense.Config::class.java,
cobblemonResource("battling_pokemon") to BattlingPokemonSense.Config::class.java,
cobblemonResource("npc_battling") to NPCBattlingSense.Config::class.java,
cobblemonResource("pokemon_adult") to PokemonAdultSense.Config::class.java,
cobblemonResource("nearby_sweet_berry_bush") to SweetBerryBushSense.Config::class.java,
cobblemonResource("pokemon_nearby_wanted_item") to PokemonItemSense.Config::class.java,
cobblemonResource("flower_sense") to FlowerSense.Config::class.java,
cobblemonResource("beehive_sense") to BeeHiveSense.Config::class.java,
cobblemonResource("sacc_leaf_sense") to SaccLeafSense.Config::class.java,
)
}
/** The variables that this sense config uses. These are used to declare variables on the entity cleanly. */
fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): List<MoLangConfigVariable> = emptyList()
fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense?
}
@@ -49,7 +49,7 @@ class EatGrassTaskConfig : SingleTaskConfig {
return null
}
behaviourConfigurationContext.addMemories(MemoryModuleType.WALK_TARGET, CobblemonMemories.RECENTLY_ATE_GRASS)
// behaviourConfigurationContext.addMemories(MemoryModuleType.WALK_TARGET, CobblemonMemories.RECENTLY_ATE_GRASS)
return WrapperLivingEntityTask(
EatGrassTask(
@@ -8,7 +8,6 @@
package com.cobblemon.mod.common.api.ai.config.task
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
@@ -1,39 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config.task
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.CobblemonSensors
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.tasks.HarvestSweetBerryBushTask
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.BehaviorControl
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class HarvestSweetBerryBushTaskConfig : SingleTaskConfig {
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) = emptyList<MoLangConfigVariable>()
override fun createTask(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): BehaviorControl<in LivingEntity>? {
if (entity !is PokemonEntity) {
return null
}
behaviourConfigurationContext.addMemories(
CobblemonMemories.NEARBY_SWEET_BERRY_BUSH,
CobblemonMemories.DISABLE_WALK_TO_BERRY_BUSH,
CobblemonMemories.TIME_TRYING_TO_REACH_BERRY_BUSH,
MemoryModuleType.WALK_TARGET,
MemoryModuleType.LOOK_TARGET)
behaviourConfigurationContext.addSensors(CobblemonSensors.NEARBY_SWEET_BERRY_BUSH)
return HarvestSweetBerryBushTask()
}
}
@@ -8,7 +8,6 @@
package com.cobblemon.mod.common.api.ai.config.task
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.CobblemonSensors
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
@@ -1,36 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config.task
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.CobblemonSensors
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.tasks.MoveToSweetBerryBushTask
import net.minecraft.util.valueproviders.UniformInt
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.BehaviorControl
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class MoveToSweetBerryBushTaskConfig : SingleTaskConfig {
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) = emptyList<MoLangConfigVariable>()
override fun createTask(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): BehaviorControl<in LivingEntity>? {
if (entity !is PokemonEntity) {
return null
}
behaviourConfigurationContext.addMemories(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH, CobblemonMemories.DISABLE_WALK_TO_BERRY_BUSH,
CobblemonMemories.TIME_TRYING_TO_REACH_BERRY_BUSH, MemoryModuleType.WALK_TARGET, MemoryModuleType.LOOK_TARGET)
behaviourConfigurationContext.addSensors(CobblemonSensors.NEARBY_SWEET_BERRY_BUSH)
return MoveToSweetBerryBushTask.create(UniformInt.of(0, 10), 0.6f)
}
}
@@ -43,8 +43,6 @@ class PokemonWanderControlTaskConfig : SingleTaskConfig {
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
?: CobblemonWanderControl()
wanderControl.reset()
wanderControl.allowLand = (entity.behaviour.moving.walk.canWalk && !entity.behaviour.moving.walk.avoidsLand) || entity.behaviour.moving.fly.canFly
wanderControl.allowWater = entity.behaviour.moving.swim.canSwimInWater && !entity.behaviour.moving.swim.avoidsWater
wanderControl.allowAir = entity.behaviour.moving.fly.canFly && !entity.behaviour.moving.walk.canWalk
@@ -1,35 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config.task
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.CobblemonSensors
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.tasks.StopTryingToReachSweetBerryBushTask
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.BehaviorControl
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class StopTryingToReachSweetBerryBushTaskConfig : SingleTaskConfig {
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) = emptyList<MoLangConfigVariable>()
override fun createTask(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): BehaviorControl<in LivingEntity>? {
if (entity !is PokemonEntity) {
return null
}
behaviourConfigurationContext.addMemories(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH, CobblemonMemories.DISABLE_WALK_TO_BERRY_BUSH,
CobblemonMemories.TIME_TRYING_TO_REACH_BERRY_BUSH, MemoryModuleType.WALK_TARGET, MemoryModuleType.LOOK_TARGET)
behaviourConfigurationContext.addSensors(CobblemonSensors.NEARBY_SWEET_BERRY_BUSH)
return StopTryingToReachSweetBerryBushTask.create(100, 20*15)
}
}
@@ -1,35 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config.task
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.CobblemonSensors
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.tasks.StopTryingToReachItemTask
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.BehaviorControl
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class StopTryingToReachWantedItemTaskConfig : SingleTaskConfig {
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) = emptyList<MoLangConfigVariable>()
override fun createTask(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): BehaviorControl<in LivingEntity>? {
if (entity !is PokemonEntity) {
return null
}
behaviourConfigurationContext.addMemories(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM, CobblemonMemories.DISABLE_WALK_TO_WANTED_ITEM,
CobblemonMemories.TIME_TRYING_TO_REACH_WANTED_ITEM, MemoryModuleType.WALK_TARGET, MemoryModuleType.LOOK_TARGET)
behaviourConfigurationContext.addSensors(CobblemonSensors.POKEMON_NEARBY_WANTED_ITEM)
return StopTryingToReachItemTask.create(120, 20*15)
}
}
@@ -82,7 +82,7 @@ interface TaskConfig {
cobblemonResource("walk_away_from_avoid_target") to WalkAwayFromAvoidTargetTaskConfig::class.java,
cobblemonResource("flee_nearest_hostile") to FleeNearestHostileTaskConfig::class.java,
cobblemonResource("flee_attacker") to FleeAttackerTaskConfig::class.java,
cobblemonResource("fly_in_circles") to FlyInCirclesTaskConfig::class.java,
// cobblemonResource("fly_in_circles") to FlyInCirclesTaskConfig::class.java,
cobblemonResource("run_script") to RunScript::class.java,
cobblemonResource("look_in_direction") to LookInDirectionTaskConfig::class.java,
cobblemonResource("wake_up") to WakeUpTaskConfig::class.java,
@@ -93,7 +93,7 @@ interface TaskConfig {
cobblemonResource("switch_from_sleep_on_trainer_bed") to SwitchFromSleepOnTrainerBedTaskConfig::class.java,
cobblemonResource("sleep_if_on_trainer_bed") to SleepIfOnTrainerBedTaskConfig::class.java,
cobblemonResource("point_to_spawn") to PointToSpawnTaskConfig::class.java,
cobblemonResource("eat_grass") to EatGrassTaskConfig::class.java,
// cobblemonResource("eat_grass") to EatGrassTaskConfig::class.java,
cobblemonResource("find_air") to FindAirTaskConfig::class.java,
cobblemonResource("go_to_land") to GoToLandTaskConfig::class.java,
cobblemonResource("path_to_hive") to PathToBeeHiveTaskConfig::class.java,
@@ -106,12 +106,8 @@ interface TaskConfig {
cobblemonResource("manage_flight_in_battle") to ManageFlightInBattleTaskConfig::class.java,
cobblemonResource("attack_hostile_mobs") to AttackHostileMobsTaskConfig::class.java,
cobblemonResource("defend_owner") to DefendOwnerTaskConfig::class.java,
cobblemonResource("move_to_sweet_berry_bush") to MoveToSweetBerryBushTaskConfig::class.java,
cobblemonResource("stop_moving_to_sweet_berry_bush") to StopTryingToReachSweetBerryBushTaskConfig::class.java,
cobblemonResource("harvest_sweet_berry_bush") to HarvestSweetBerryBushTaskConfig::class.java,
cobblemonResource("eat_held_item") to EatHeldItemTaskConfig::class.java,
// cobblemonResource("eat_held_item") to EatHeldItemTaskConfig::class.java,
cobblemonResource("move_to_item") to MoveToItemTaskConfig::class.java,
cobblemonResource("stop_moving_to_item") to StopTryingToReachWantedItemTaskConfig::class.java,
cobblemonResource("pickup_item") to PickUpItemTaskConfig::class.java,
cobblemonResource("move_into_fluid") to MoveIntoFluidTaskConfig::class.java,
cobblemonResource("find_herd_leader") to FindHerdLeaderTaskConfig::class.java,
@@ -143,13 +143,13 @@ class WanderTaskConfig : SingleTaskConfig {
if (wanderChance <= 0 || world.random.nextFloat() > wanderChance) {
return@Trigger false
}
pathCooldown.setWithExpiry(true, wanderControl.pathCooldownTicks.toLong())
pathCooldown.setWithExpiry(true, 40L)
val minimumHeight = minimumHeight.resolveInt(mainThreadRuntime)
val maximumHeight = maximumHeight.resolveInt(mainThreadRuntime)
var attempts = 0
var pos: BlockPos? = null
while (attempts++ < wanderControl.maxAttempts && pos == null) {
while (attempts++ < (wanderControl.maxAttempts ?: 4) && pos == null) {
// val targetVec = getLandTarget(entity) ?: return@Trigger true
val targetVec = if (maximumHeight != -1) {
HoverRandomPos.getPos(
@@ -189,7 +189,7 @@ class WanderTaskConfig : SingleTaskConfig {
minimumHeight = minimumHeight,
maximumHeight = maximumHeight,
world = world
).takeIf(wanderControl::isSuitable)
)//.takeIf(wanderControl::isSuitable)
}
if (pos == null) {
@@ -201,17 +201,8 @@ class WanderTaskConfig : SingleTaskConfig {
pos = pos,
speedModifier = speedMultiplier.resolveFloat(mainThreadRuntime),
completionRange = 0,
nodeTypeFilter = { nodeType ->
entity.canBreatheUnderwater() || nodeType !in listOf(
PathType.WATER,
PathType.WATER_BORDER
)
},
destinationNodeTypeFilter = { nodeType ->
!avoidsTargetingAir || nodeType !in listOf(
PathType.OPEN
)
}
nodeTypeFilter = { nodeType -> entity.canBreatheUnderwater() || nodeType !in listOf(PathType.WATER, PathType.WATER_BORDER) },
destinationNodeTypeFilter = { nodeType -> !avoidsTargetingAir || nodeType !in listOf(PathType.OPEN) }
)
)
lookTarget.set(BlockPosTracker(pos.toVec3d().add(0.0, entity.eyeHeight.toDouble(), 0.0)))
@@ -75,7 +75,7 @@ class WaterWanderTaskConfig : SingleTaskConfig {
}
val wanderControl = it.tryGet(wanderControlData).orElse(null) ?: CobblemonWanderControl()
if (!wanderControl.allowWater) {
if (wanderControl.allowWater != true) {
return@Trigger false
}
@@ -85,17 +85,17 @@ class WaterWanderTaskConfig : SingleTaskConfig {
return@Trigger false
}
pathCooldown.setWithExpiry(true, wanderControl.pathCooldownTicks.toLong())
pathCooldown.setWithExpiry(true, 40L)
var pos: BlockPos? = null
var target: Vec3? = null
var attempts = 0
while (attempts < wanderControl.maxAttempts && pos == null) {
while (attempts < wanderControl.maxAttempts ?: 4 && pos == null) {
attempts++
target = BehaviorUtils.getRandomSwimmablePos(entity, horizontalRange.resolveInt(mainThreadRuntime), verticalRange.resolveInt(mainThreadRuntime))
?: continue
pos = BlockPos.containing(target).takeIf(wanderControl::isSuitable)
// pos = BlockPos.containing(target).takeIf(wanderControl::isSuitable) im migrating shit
}
if (pos == null || target == null) {
@@ -192,6 +192,11 @@ open class PokemonBattle(
*/
fun getActor(npc: NPCEntity) = actors.firstOrNull { it is NPCBattleActor && it.npc == npc }
/**
* Gets the first battle actor who has or is the given [PokemonEntity]
*/
fun getActor(pokemonEntity: PokemonEntity) = actors.firstOrNull { it.uuid == pokemonEntity.uuid || it.activePokemon.any { it.battlePokemon?.entity == pokemonEntity } }
/**
* Gets a [BattleActor] and an [ActiveBattlePokemon] from a pnx key, e.g. p2a
*
@@ -145,6 +145,7 @@ import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.entity.monster.Monster
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.enchantment.EnchantmentHelper
import net.minecraft.world.level.ClipContext
import net.minecraft.world.level.GameType
import net.minecraft.world.level.Level
@@ -311,7 +312,7 @@ object MoLangFunctions {
runtime.environment.variable = params.environment.variable
val args = params.params.subList(1, params.params.size)
runtime.environment.context = ContextStruct(
params.environment.context.map + args.mapIndexed { index, value -> "arg_${index + 1}" to value }.toMap()
(params.environment.context?.map ?: emptyMap()) + args.mapIndexed { index, value -> "arg_${index + 1}" to value }.toMap()
)
val script = params.getString(0).asIdentifierDefaultingNamespace()
// store the args in the
@@ -324,13 +325,24 @@ object MoLangFunctions {
runtime.environment.context = params.environment.context
val expression = params.getString(0).asExpressionLike()
val delayInSeconds = params.getDoubleOrNull(1)?.toFloat() ?: 0.0f
fun evaluate(): MoValue {
return try {
runtime.resolve(expression)
} catch (ex: Exception) {
Cobblemon.LOGGER.warn("Failed to evaluate MoLang expression${if (delayInSeconds > 0.0f) " (delayed)" else ""}: $expression", ex)
DoubleValue.ZERO
}
}
if (delayInSeconds > 0.0f) {
val tracker = if (Cobblemon.implementation.environment() == Environment.SERVER) ServerTaskTracker else ClientTaskTracker
tracker.after(delayInSeconds) {
runtime.resolve(expression)
evaluate()
}
DoubleValue.ONE
} else {
runtime.resolve(expression)
evaluate()
}
},
"system_time_millis" to java.util.function.Function { _ ->
@@ -340,23 +352,28 @@ object MoLangFunctions {
"date_local_time" to java.util.function.Function { _ ->
val time = System.currentTimeMillis()
val date = java.util.Date(time)
val formatted = java.text.SimpleDateFormat("DD/MM/YYYY").format(date)
val formatted = java.text.SimpleDateFormat("dd/MM/yyyy").format(date)
StringValue(formatted)
},
"date_of" to java.util.function.Function { params ->
val time = params.getDouble(0).toLong()
val date = java.util.Date(time)
val formatted = java.text.SimpleDateFormat("DD/MM/YYYY").format(date)
val formatted = java.text.SimpleDateFormat("dd/MM/yyyy").format(date)
StringValue(formatted)
},
"date_is_after" to java.util.function.Function { params ->
val dateA = params.getString(0)
val dateB = params.getString(1)
val format = java.text.SimpleDateFormat("DD/MM/YYYY")
val format = java.text.SimpleDateFormat("dd/MM/yyyy")
val a = format.parse(dateA)
val b = format.parse(dateB)
DoubleValue(a.after(b))
},
"get_move_from_id" to java.util.function.Function { params ->
val moveId = params.getString(0)
val moveTemplate = Moves.getByName(moveId)
return@Function moveTemplate?.struct ?: DoubleValue.ZERO
},
"create_simple_party_provider" to java.util.function.Function { params ->
val partyProvider = SimplePartyProvider()
return@Function partyProvider.struct
@@ -367,6 +384,13 @@ object MoLangFunctions {
val pickupItem = ObtainableItem(item = item, pickupPriority = pickupPriority)
return@Function pickupItem.struct
},
"create_itemstack" to java.util.function.Function { params ->
val itemId = params.getString(0).asIdentifierDefaultingNamespace()
val item = BuiltInRegistries.ITEM.get(itemId) ?: return@Function DoubleValue.ZERO
val count = params.getIntOrNull(1) ?: 1
val itemStack = ItemStack(item, count)
return@Function ObjectValue(itemStack)
},
"file" to java.util.function.Function { MoLangLoadedFilesCache.struct }
)
val biomeFunctions = mutableListOf<(Holder<Biome>) -> HashMap<String, java.util.function.Function<MoParams, Any>>>()
@@ -572,6 +596,62 @@ object MoLangFunctions {
}
return@put items
}
map.put("has_inventory_space") { _ ->
val inventory = player.inventory
return@put if (inventory.getFreeSlot() != -1) DoubleValue.ONE else DoubleValue.ZERO
}
map.put("set_inventory_slot") { params ->
val slot = params.getInt(0)
val inventory = player.inventory
if (slot !in 0 until inventory.containerSize) return@put DoubleValue.ZERO
val value = params.getOrNull<MoValue>(1) ?: return@put DoubleValue.ZERO
val stack: ItemStack? = when (value) {
is ObjectValue<*> -> value.obj as? ItemStack
is StringValue -> {
val id = ResourceLocation.parse(value.value)
val item = player.registryAccess().registryOrThrow(Registries.ITEM).get(id) ?: return@put DoubleValue.ZERO
ItemStack(item)
}
else -> null
}
if (stack == null) return@put DoubleValue.ZERO
inventory.setItem(slot, stack)
return@put DoubleValue.ONE
}
map.put("give_item") { params ->
val inventory = player.inventory
val freeSlot = inventory.getFreeSlot()
val value = params.getOrNull<MoValue>(0) ?: return@put DoubleValue.ZERO
val dropIfFull = params.getBooleanOrNull(1) ?: false
val stack: ItemStack? = when (value) {
is ObjectValue<*> -> value.obj as? ItemStack
is StringValue -> {
val id = ResourceLocation.parse(value.value)
val item = player.registryAccess().registryOrThrow(Registries.ITEM).get(id) ?: return@put DoubleValue.ZERO
ItemStack(item)
}
else -> null
}
if (stack == null) return@put DoubleValue.ZERO
if (freeSlot == -1) {
if (dropIfFull) {
player.drop(stack, false)
return@put DoubleValue.ONE
} else {
return@put DoubleValue.ZERO
}
}
inventory.setItem(freeSlot, stack)
return@put DoubleValue.ONE
}
map.put("face") { params -> ObjectValue(PlayerDialogueFaceProvider(player.uuid, params.getBooleanOrNull(0) != false)) }
map.put("swing_hand") { _ -> player.swing(player.usedItemHand) }
map.put("food_level") { _ -> DoubleValue(player.foodData.foodLevel) }
@@ -615,8 +695,7 @@ object MoLangFunctions {
}
map.put("active_dialogue") { _ ->
if (player.isInDialogue) {
player.activeDialogue?.dialogueId.toString()
return@put DoubleValue.ONE
return@put player.activeDialogue?.toMoLangStruct() ?: DoubleValue.ZERO
} else {
DoubleValue.ZERO
}
@@ -793,6 +872,8 @@ object MoLangFunctions {
DoubleValue(value)
}
map.put("get_starter_uuid") { _ -> Cobblemon.playerDataManager.getGenericData(player).starterUUID?.let{ StringValue(it.toString()) } ?: DoubleValue.ZERO }
map.put("has_chosen_starter") { _ -> DoubleValue(Cobblemon.playerDataManager.getGenericData(player).starterSelected) }
}
map
}
@@ -813,6 +894,15 @@ object MoLangFunctions {
map.put("is_of") { params -> DoubleValue(holder.`is`(params.getString(0).asIdentifierDefaultingNamespace())) }
map.put("is_in") { params -> DoubleValue(holder.`is`(TagKey.create(Registries.ITEM, params.getString(0).replace("#", "").asIdentifierDefaultingNamespace()))) }
map.put("is_food") { params -> DoubleValue(stack.has(DataComponents.FOOD)) }
map.put("is_enchanted") { params -> DoubleValue(stack.hasFoil()) }
map.put("has_enchantment") { params ->
val enchantmentId = params.getString(0).asIdentifierDefaultingNamespace()
val minLevel = params.getIntOrNull(1) ?: 1
val enchantmentRegistry = registryAccess.registryOrThrow(Registries.ENCHANTMENT)
val holder = enchantmentRegistry.getHolder(enchantmentId).orElse(null) ?: return@put DoubleValue.ZERO
val level = EnchantmentHelper.getItemEnchantmentLevel(holder, stack)
return@put DoubleValue(level >= minLevel)
}
return@mutableListOf map
}
)
@@ -1752,6 +1842,30 @@ object MoLangFunctions {
map.put("remove_cosmetic_item") { _ ->
pokemon.removeCosmeticItem()
}
map.put("marks") { _ -> pokemon.marks.asArrayValue { StringValue(it.identifier.toString()) } }
map.put("has_mark") { params ->
var hasMark = false
val identifier = params.getString(0).asIdentifierDefaultingNamespace()
val mark = Marks.getByIdentifier(identifier)
if (mark != null) {
hasMark = pokemon.marks.contains(mark)
}
DoubleValue(hasMark)
}
map.put("remove_marks") { params ->
var removedMark = false
for (param in params.params) {
val identifier = param.asString().asIdentifierDefaultingNamespace()
val mark = Marks.getByIdentifier(identifier)
if (mark != null) {
pokemon.exchangeMark(mark, false)
removedMark = true
}
}
DoubleValue(removedMark)
}
map.put("add_marks") { params ->
var appliedMark = false
for (param in params.params) {
@@ -1945,9 +2059,13 @@ object MoLangFunctions {
}
}
map.put("is_sprinting") {
pokemonEntity.ifRidingAvailableSupply(DoubleValue.ZERO) { behaviour, settings, state ->
val moValue = behaviour.asMoLangValue(settings, state, pokemonEntity)
return@ifRidingAvailableSupply moValue.functions.get("sprinting")?.apply(MoParams.EMPTY) as? MoValue ?: DoubleValue.ZERO
if (pokemonEntity.hasControllingPassenger()) { // If its being ridden then the riding state sets the animation
pokemonEntity.ifRidingAvailableSupply(DoubleValue.ZERO) { behaviour, settings, state ->
val moValue = behaviour.asMoLangValue(settings, state, pokemonEntity)
return@ifRidingAvailableSupply moValue.functions.get("sprinting")?.apply(MoParams.EMPTY) as? MoValue ?: DoubleValue.ZERO
}
} else {
pokemonEntity.isPokemonSprinting
}
}
map.put("is_drifting") {
@@ -2737,8 +2855,8 @@ object MoLangFunctions {
}
variable
}
else -> null
} ?: throw IllegalArgumentException("Invalid NBT element type: ${nbt.type}")
else -> VariableStruct()
}
}
}
@@ -14,6 +14,7 @@ import net.minecraft.network.protocol.common.custom.CustomPacketPayload
import net.minecraft.resources.ResourceKey
import net.minecraft.server.level.ServerPlayer
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.entity.Entity
import net.minecraft.world.level.Level
/**
@@ -86,5 +87,9 @@ interface NetworkPacket<T: NetworkPacket<T>> : CustomPacketPayload, Encodable {
.forEach { player -> CobblemonNetwork.sendPacketToPlayer(player, this) }
}
fun sendToPlayersAround(entity: Entity, distance: Double, exclusionCondition: (ServerPlayer) -> Boolean = { false }) {
sendToPlayersAround(entity.x, entity.y, entity.z, distance, entity.level().dimension(), exclusionCondition)
}
override fun type() = CustomPacketPayload.Type<T>(id)
}
@@ -13,6 +13,8 @@ import com.bedrockk.molang.runtime.value.MoValue
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.ai.SleepDepth
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.config.task.TaskConfig
import com.cobblemon.mod.common.api.conditional.RegistryLikeCondition
import com.cobblemon.mod.common.api.data.JsonDataRegistry
@@ -80,6 +82,8 @@ object NPCClasses : JsonDataRegistry<NPCClass> {
.registerTypeAdapter(SensorType::class.java, SensorTypeAdapter)
.registerTypeAdapter(BehaviourConfig::class.java, BehaviourConfigAdapter)
.registerTypeAdapter(TaskConfig::class.java, TaskConfigAdapter)
.registerTypeAdapter(ObjectiveConfig::class.java, ObjectiveConfigAdapter)
.registerTypeAdapter(SenseConfig::class.java, SenseConfigAdapter)
.registerTypeAdapter(
TypeToken.getParameterized(Either::class.java, Expression::class.java, MoLangConfigVariable::class.java).type,
ExpressionOrEntityVariableAdapter
@@ -12,6 +12,8 @@ import com.bedrockk.molang.Expression
import com.bedrockk.molang.runtime.value.MoValue
import com.cobblemon.mod.common.api.ai.SleepDepth
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.config.task.TaskConfig
import com.cobblemon.mod.common.api.conditional.RegistryLikeCondition
import com.cobblemon.mod.common.api.data.JsonDataRegistry
@@ -75,6 +77,8 @@ object NPCPresets : JsonDataRegistry<NPCPreset> {
.registerTypeAdapter(SensorType::class.java, SensorTypeAdapter)
.registerTypeAdapter(BehaviourConfig::class.java, BehaviourConfigAdapter)
.registerTypeAdapter(TaskConfig::class.java, TaskConfigAdapter)
.registerTypeAdapter(ObjectiveConfig::class.java, ObjectiveConfigAdapter)
.registerTypeAdapter(SenseConfig::class.java, SenseConfigAdapter)
.registerTypeAdapter(
TypeToken.getParameterized(Either::class.java, Expression::class.java, MoLangConfigVariable::class.java).type,
ExpressionOrEntityVariableAdapter
@@ -149,6 +149,8 @@ object CobblemonPermissions {
@JvmStatic
val USE_RIDING_STATS_DEBUG = this.create("useridingstatsdebug", PermissionLevel.CHEAT_COMMANDS_AND_COMMAND_BLOCKS)
@JvmStatic
val DEBUG_COBBLEMON_AI = this.create("${COMMAND_PREFIX}debugcobblemonai", PermissionLevel.CHEAT_COMMANDS_AND_COMMAND_BLOCKS)
@JvmStatic
fun all(): Iterable<Permission> = this.permissions
@@ -14,6 +14,8 @@ import com.cobblemon.mod.common.api.abilities.AbilityPool
import com.cobblemon.mod.common.api.abilities.AbilityTemplate
import com.cobblemon.mod.common.api.ai.SleepDepth
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.config.task.TaskConfig
import com.cobblemon.mod.common.api.conditional.RegistryLikeCondition
import com.cobblemon.mod.common.api.data.JsonDataRegistry
@@ -90,6 +92,8 @@ object PokemonSpecies : JsonDataRegistry<Species> {
.registerTypeAdapter(SensorType::class.java, SensorTypeAdapter)
.registerTypeAdapter(BehaviourConfig::class.java, BehaviourConfigAdapter)
.registerTypeAdapter(TaskConfig::class.java, TaskConfigAdapter)
.registerTypeAdapter(ObjectiveConfig::class.java, ObjectiveConfigAdapter)
.registerTypeAdapter(SenseConfig::class.java, SenseConfigAdapter)
.registerTypeAdapter(
TypeToken.getParameterized(Either::class.java, Expression::class.java, MoLangConfigVariable::class.java).type,
ExpressionOrEntityVariableAdapter
@@ -9,7 +9,7 @@
package com.cobblemon.mod.common.api.pokemon.aspect
import com.cobblemon.mod.common.CobblemonBlocks
import com.cobblemon.mod.common.api.ai.config.task.PollinateFlowerTaskConfig
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.GatherNectar
import com.cobblemon.mod.common.api.spawning.influence.SaccharineLogSlatheredInfluence
import com.cobblemon.mod.common.block.entity.PokeSnackBlockEntity
import com.cobblemon.mod.common.client.entity.PokemonClientDelegate
@@ -28,7 +28,7 @@ val aspectParticleMap: Map<String, ParticleData> = mapOf(
ParticleTypes.BLOCK,
CobblemonBlocks.POKE_SNACK.defaultBlockState()
), 0.05, 3),
PollinateFlowerTaskConfig.HAS_NECTAR_ASPECT to ParticleData.MinecraftParticle(ParticleTypes.FALLING_NECTAR, 0.075, 1)
GatherNectar.HAS_NECTAR_ASPECT to ParticleData.MinecraftParticle(ParticleTypes.FALLING_NECTAR, 0.075, 1)
)
sealed class ParticleData {
@@ -13,6 +13,8 @@ import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.advancement.CobblemonCriteria
import com.cobblemon.mod.common.advancement.criterion.EvolvePokemonContext
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.DurationLockFixation
import com.cobblemon.mod.common.api.drop.DropTable
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.pokemon.PokemonGainedEvent
@@ -23,7 +25,6 @@ import com.cobblemon.mod.common.api.moves.MoveTemplate
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.requirement.Requirement
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.item.PokeBallItem
import com.cobblemon.mod.common.net.messages.client.animation.PlayPosableAnimationPacket
import com.cobblemon.mod.common.pokemon.Pokemon
@@ -168,17 +169,13 @@ interface Evolution : EvolutionLike {
evolutionMethod(pokemon)
pokemon.getOwnerPlayer()?.sendSystemMessage(lang("ui.evolve.into", preEvoName, pokemon.species.translatedName))
} else {
pokemonEntity.entityData.set(PokemonEntity.EVOLUTION_STARTED, true)
pokemonEntity.navigation.stop()
pokemonEntity.after(1F) {
evolutionAnimation(pokemonEntity)
}
pokemonEntity.after(11.2F) {
evolutionMethod(pokemon)
if (pokemonEntity.biggerBrain.distract(Distraction.FORCE)) {
pokemonEntity.biggerBrain.fixate(DurationLockFixation(description = "Evolving ({ticks} ticks remaining)", durationTicks = 14 * 20))
}
pokemonEntity.after(1F) { evolutionAnimation(pokemonEntity) }
pokemonEntity.after(11.2F) { evolutionMethod(pokemon) }
pokemonEntity.after(seconds = 12F) {
cryAnimation(pokemonEntity)
pokemonEntity.entityData.set(PokemonEntity.EVOLUTION_STARTED, false)
pokemon.getOwnerPlayer()?.sendSystemMessage(lang("ui.evolve.into", preEvoName, pokemon.species.translatedName))
}
}
@@ -22,6 +22,8 @@ import kotlin.math.min
class Vec3Spring(
var value: Vec3 = Vec3.ZERO,
var velocity: Vec3 = Vec3.ZERO
) {
val history = ArrayDeque<Vec3>()
@@ -15,6 +15,7 @@ import com.cobblemon.mod.common.CobblemonClientImplementation
import com.cobblemon.mod.common.CobblemonEntities
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.CobblemonMenuType
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrainState
import com.cobblemon.mod.common.api.berry.Berries
import com.cobblemon.mod.common.api.scheduling.ClientTaskTracker
import com.cobblemon.mod.common.api.storage.player.client.ClientGeneralPlayerData
@@ -22,6 +23,7 @@ import com.cobblemon.mod.common.api.storage.player.client.ClientPokedexManager
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
import com.cobblemon.mod.common.block.entity.TintBlockEntity
import com.cobblemon.mod.common.client.battle.ClientBattle
import com.cobblemon.mod.common.client.gui.BrainDebugOverlay
import com.cobblemon.mod.common.client.gui.PartyOverlay
import com.cobblemon.mod.common.client.gui.PartyOverlayDataControl
import com.cobblemon.mod.common.client.gui.RideControlsOverlay
@@ -108,15 +110,20 @@ object CobblemonClient {
var lastPcBoxViewed = 0
var requests = ClientPlayerActionRequests()
var teamData = ClientPlayerTeamData()
var biggerBrainDebugData: BiggerBrainState? = null
var debuggedEntityId : Int = -1
val overlay: PartyOverlay by lazy { PartyOverlay() }
val battleOverlay: BattleOverlay by lazy { BattleOverlay() }
val pokedexUsageContext: PokedexUsageContext by lazy { PokedexUsageContext() }
val rideControlsOverlay: RideControlsOverlay by lazy { RideControlsOverlay() }
val pokedexUsageContext: PokedexUsageContext by lazy(::PokedexUsageContext)
val rideControlsOverlay: RideControlsOverlay by lazy(::RideControlsOverlay)
val brainDebugOverlay: BrainDebugOverlay by lazy(::BrainDebugOverlay)
fun onLogin() {
clientPlayerData = ClientGeneralPlayerData()
requests = ClientPlayerActionRequests()
teamData = ClientPlayerTeamData()
biggerBrainDebugData = null
clientPokedexData = ClientPokedexManager(mutableMapOf())
storage.onLogin()
// CobblemonDataProvider.canReload = false
@@ -334,6 +341,7 @@ object CobblemonClient {
battleOverlay.render(context, partialDeltaTicks)
}
rideControlsOverlay.render(context, partialDeltaTicks)
brainDebugOverlay.render(context, partialDeltaTicks)
}
@Suppress("UNCHECKED_CAST")
@@ -20,8 +20,7 @@ import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.aspect.aspectParticleMap
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.pokemon.aspect.ParticleData
import com.cobblemon.mod.common.api.riding.behaviour.RidingBehaviourState
import com.cobblemon.mod.common.api.riding.stats.RidingStat
import com.cobblemon.mod.common.util.math.FloatSpring
import com.cobblemon.mod.common.api.scheduling.ScheduledTask
import com.cobblemon.mod.common.api.scheduling.SchedulingTracker
import com.cobblemon.mod.common.api.scheduling.afterOnClient
@@ -42,6 +41,7 @@ import com.cobblemon.mod.common.util.MovingSoundInstance
import com.cobblemon.mod.common.util.asExpressionLike
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.math.InertialVals
import com.cobblemon.mod.common.util.resolve
import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.Minecraft
@@ -90,6 +90,13 @@ class PokemonClientDelegate : PosableState(), PokemonSideDelegate {
var playedSendOutSound: Boolean = false
var playedThrowingSound: Boolean = false
var renderYRotSpring: FloatSpring = FloatSpring()
var lastRenderTime: Long = 0
var lastKnownYBodyRot: Float = 0F
var renderYRot: Float = 0F
var inertialYRot: InertialVals = InertialVals()
val secondsSinceBeamEffectStarted: Float
get() = (System.currentTimeMillis() - beamStartTime) / 1000F
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.gui
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrainState
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.ObjectiveStatus
import com.cobblemon.mod.common.client.CobblemonClient
import net.minecraft.client.DeltaTracker
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.Gui
import net.minecraft.client.gui.GuiGraphics
class BrainDebugOverlay : Gui(Minecraft.getInstance()) {
companion object {
const val FIXATED_COLOUR = 0xAA00FF
const val ACTIVE_COLOUR = 0x2CE121
const val INACTIVE_COLOUR = 0xCCCCCC
const val BLOCKED_COLOUR = 0xEA1313
const val INVALID_COLOUR = 0x8C8C8C
}
override fun render(guiGraphics: GuiGraphics, deltaTracker: DeltaTracker) {
val brainDebug = CobblemonClient.biggerBrainDebugData ?: return
renderSenses(guiGraphics, deltaTracker, brainDebug)
renderObjectives(guiGraphics, deltaTracker, brainDebug)
renderFixation(guiGraphics, deltaTracker, brainDebug)
}
fun renderSenses(guiGraphics: GuiGraphics, deltaTracker: DeltaTracker, data: BiggerBrainState) {
val mc = Minecraft.getInstance()
val senseX = mc.window.guiScaledWidth / 2 - 165
val senseY = 50
guiGraphics.drawString(mc.font, "Senses", senseX, senseY, 0xFFFFFF)
var i = 0
for (sense in data.senses) {
i++
guiGraphics.drawString(mc.font, sense.className, senseX, senseY + i * 12, 0xFFFFFF)
guiGraphics.drawString(mc.font, sense.ticksUntilNextExecution.toString(), senseX - 20, senseY + i * 12, 0xFFFFFF)
}
}
fun renderObjectives(guiGraphics: GuiGraphics, deltaTracker: DeltaTracker, data: BiggerBrainState) {
val mc = Minecraft.getInstance()
val objectiveX = mc.window.guiScaledWidth / 2 + 50
val objectiveY = 50
guiGraphics.drawString(mc.font, "Objectives", objectiveX, objectiveY, 0xFFFFFF)
var i = 0
for (objective in data.objectives) {
i++
val colour = when (objective.status) {
ObjectiveStatus.FIXATED -> FIXATED_COLOUR
ObjectiveStatus.ACTIVE -> ACTIVE_COLOUR
ObjectiveStatus.INACTIVE -> INACTIVE_COLOUR
ObjectiveStatus.BLOCKED -> BLOCKED_COLOUR
ObjectiveStatus.INVALID -> INVALID_COLOUR
}
guiGraphics.drawString(mc.font, objective.description, objectiveX, objectiveY + i * 12, colour)
}
}
fun renderFixation(guiGraphics: GuiGraphics, deltaTracker: DeltaTracker, data: BiggerBrainState) {
val mc = Minecraft.getInstance()
val fixation = data.fixation ?: return
val fixationX = Minecraft.getInstance().window.guiScaledWidth / 2
val fixationY = 8
guiGraphics.drawCenteredString(mc.font, "Fixation:", fixationX, fixationY, 0xFFFFFF)
guiGraphics.drawCenteredString(mc.font, fixation, fixationX, fixationY + 12, FIXATED_COLOUR)
}
}
@@ -29,7 +29,8 @@ object DebugKeybindings {
TranslateUpKeybinding(),
TranslateDownKeybinding(),
PrintModelSettingsKeybinding(),
ToggleRidingStatsDebugGUIKeybinding()
ToggleRidingStatsDebugGUIKeybinding(),
ToggleAIDebugKeybinding()
)
class ScaleUpKeybinding: CobblemonKeyBinding(
@@ -164,4 +165,16 @@ object DebugKeybindings {
}
}
class ToggleAIDebugKeybinding : CobblemonKeyBinding(
"key.cobblemon.toggleaidebug",
InputConstants.Type.KEYSYM,
InputConstants.KEY_LBRACKET,
KeybindCategories.COBBLEMON_DEBUG_CATEGORY
) {
override fun onPress() {
Minecraft.getInstance().player?.connection?.sendCommand("debugcobblemonai")
}
}
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.net.debug
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.render.debug.LineState
import com.cobblemon.mod.common.client.render.debug.SteerForceRenderer
import com.cobblemon.mod.common.net.messages.client.debug.ClientboundUpdateObsAvoidPacket
import net.minecraft.client.Minecraft
object S2CUpdateObsAvoidHandler : ClientNetworkPacketHandler<ClientboundUpdateObsAvoidPacket> {
override fun handle(packet: ClientboundUpdateObsAvoidPacket, client: Minecraft) {
client.executeIfPossible {
//ObjectAvoidanceRenderer.avoidanceLines[packet.entityId] = packet.lines
val lineState = SteerForceRenderer.lineStates.getOrPut(packet.entityId) { LineState() }
lineState.update(packet.lines)
}
}
}

Some files were not shown because too many files have changed in this diff Show More