mirror of
https://gitlab.com/cable-mc/cobblemon.git
synced 2026-10-23 07:36:25 -04:00
Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
35b2b33eb4 | ||
|
|
9900fbf3d6 | ||
|
|
1e8d012371 | ||
|
|
82ef84d82b | ||
|
|
c0154cd82d | ||
|
|
1c9c833a49 | ||
|
|
901e3e09e1 | ||
|
|
94c159b42b | ||
|
|
3c80a61011 | ||
|
|
e29087c805 | ||
|
|
e850253d88 | ||
|
|
bbb692f521 | ||
|
|
da1d67bbe6 | ||
|
|
792834f219 | ||
|
|
94b31cd658 | ||
|
|
19364f39c6 | ||
|
|
2fc8f6b9df | ||
|
|
9089ff3bbb | ||
|
|
90f581051c | ||
|
|
061bdcc478 | ||
|
|
6811394f71 | ||
|
|
1235a70323 | ||
|
|
d94952347f | ||
|
|
7fe6141640 | ||
|
|
4b1653ca6c | ||
|
|
7265ab57b9 | ||
|
|
27e3a95b06 | ||
|
|
38de3c6267 | ||
|
|
376e5ac906 | ||
|
|
b225283dcc | ||
|
|
b90f852a71 | ||
|
|
fdf7a9703a | ||
|
|
bb41f28342 | ||
|
|
c5ee7ebe7a | ||
|
|
f6ae10e1d9 | ||
|
|
b2070b53fb | ||
|
|
7fb873dc2c | ||
|
|
641f529de3 | ||
|
|
db9fb4fefa |
+34
-38
@@ -1,45 +1,41 @@
|
||||
# Changelog
|
||||
## [1.8.2 (MONTH xth, 2026)](#1-8-2)
|
||||
|
||||
### Additions
|
||||
- The following items can now be placed on the ground as blocks:
|
||||
- King's Rock, Galarica Cuff, Unremarkable Teacup, Masterpiece Teacup, Chipped Pot, Cracked Pot, Sachet, Metal Powder, Quick Powder, Bright Powder, Icy Rock, Heat Rock, Smooth Rock, Damp Rock, Destiny Knot, Luminous Moss, Never-Melt Ice, Wide Lens, Scope Lens, and Zoom Lens.
|
||||
- Iron Ball, Metal Coat, Throat Spray, HP Up, Protein, Iron, Carbos, Calcium, Zinc, PP Up, PP Max, Upgrade, Dubious Disc, and Loaded Dice.
|
||||
- The following items can now be placed on various surfaces:
|
||||
- Galarica Wreath, Magnet, Flame Orb, Life Orb, Toxic Orb, Light Ball, and Smoke Ball.
|
||||
- The following items can now be placed as blocks, and have additional functionality:
|
||||
- Ring Target, Metronome, and Eject Button.
|
||||
- The following items can now be worn by Players and Pokémon:
|
||||
- Galarica Wreath, Cleanse Tag, Spell Tag, Sharp Beak, Covert Cloak, Shell Helmet, and Never-Melt Ice.
|
||||
- Wearable items can now be equipped by a player by holding it and right-clicking (or rebound use/interact)
|
||||
- Wearable items that can be placed down are exempt from this behaviour.
|
||||
|
||||
### New rideable Pokémon
|
||||
|
||||
### Pokémon Added
|
||||
|
||||
#### Regional Forms
|
||||
|
||||
### Model updates for the following Pokémon
|
||||
## [1.8.1 (September 13th, 2026)](#1-8-1)
|
||||
|
||||
### Animation updates for the following Pokémon
|
||||
|
||||
#### Added sounds to the following moves
|
||||
|
||||
### Changes
|
||||
- Flapple, Appletun, Dipplin, Hydrapple (placeholder animations only).
|
||||
|
||||
### Fixes
|
||||
- Correctly grants "They're Minerals!" advancement when planting a type gem
|
||||
- Type Gem Blocks now have advancements to give you the recipe in the recipe book (the data for the advancements were inside the recipes somehow??)
|
||||
- Corrected the TM Recipes for Charge Beam and Payday
|
||||
|
||||
### Developer
|
||||
|
||||
### Molang & Datapacks
|
||||
|
||||
### Particles
|
||||
|
||||
#### New Move Animations
|
||||
- Fixed a potential world generation stall caused by Type Gem clusters.
|
||||
- Fixed Pokémon on shoulders not animating if they are visibly holding a held item.
|
||||
- Fixed NPCs getting their own TM progress file.
|
||||
- Fixed odd NeoForge crash due to a dependency being outdated. It will now correctly flag the dependency for being outdated.
|
||||
- Fixed the TM Machine refusing move selections that the `unlockAllMoveDexMovesByDefault` config had made visible, leaving the move slot blank and the craft button unresponsive.
|
||||
- Fixed the Beast Ball not applying its 0.1× penalty to Pokémon that are not Ultra Beasts.
|
||||
- Fixed the Moon Ball reading the world's total elapsed time instead of the time of day, so its bonus applied during the day instead.
|
||||
- Fixed the Love Ball never awarding its 2.5× opposite gender bonus, and matching species by display name instead of identifier.
|
||||
- Fixed the Timer Ball being weaker than a regular Poké Ball on early turns and only reaching 4× on turn 14 instead of turn 10.
|
||||
- Fixed the Luxury Ball only doubling Friendship gains of 1, leaving level up and berry gains unaffected.
|
||||
- Fixed Rufflet, Braviary, and Hisuian Braviary flooding logs with errors about missing sound events.
|
||||
- Fixed Pokémon property typos in Pangoro and Dedenne herd spawn files.
|
||||
- Fixed unintentional watermelon cosmetic for Hisuian Electrode.
|
||||
- Fixed Blastoise having an unintentional passenger seat.
|
||||
- Fixed form typo in Rockruff-Dusk spawn, preventing it from being able to spawn.
|
||||
- Fixed the `stat_compare` and `stat_equal` evolution requirements crashing the game when given `special_attack` or `special_defence`, and made them treat any non-permanent stat as a failed requirement instead of crashing.
|
||||
- Fixed Rowap and Jacoba berries not correctly altering Pokémon sizes when used as bait.
|
||||
- Fixed Ampharos' eyes not emitting particles.
|
||||
- Fixed Alolan Raticate's cry not playing.
|
||||
- Fixed several incorrect light-based spawning conditions for ghosts and bugs.
|
||||
- Removed unused, placeholder habitat pools.
|
||||
- Fixed Mantyke, Mantine, and Quaxly getting stuck in a recoil 'expression' during battles due to having an expression assigned as a recoil animation.
|
||||
- Fixed Lucario's aura particles not emitting.
|
||||
- Fixed Lycanroc's head movement.
|
||||
- Added head movement to Archaludon.
|
||||
- Fixed Duraludon line not having their sleep animations.
|
||||
- Fixed Diglett line not having their faint animations.
|
||||
- Fixed Kingambit moving its legs while walking.
|
||||
|
||||
### Localization
|
||||
- Updated translations for:
|
||||
- Updated translations for:
|
||||
- Brazilian Portuguese
|
||||
- Simplified Chinese
|
||||
- Japanese
|
||||
@@ -1,41 +0,0 @@
|
||||
# Changelog
|
||||
## [1.8.1 (September 13th, 2026)](#1-8-1)
|
||||
|
||||
### Animation updates for the following Pokémon
|
||||
- Flapple, Appletun, Dipplin, Hydrapple (placeholder animations only).
|
||||
|
||||
### Fixes
|
||||
- Fixed a potential world generation stall caused by Type Gem clusters.
|
||||
- Fixed Pokémon on shoulders not animating if they are visibly holding a held item.
|
||||
- Fixed NPCs getting their own TM progress file.
|
||||
- Fixed odd NeoForge crash due to a dependency being outdated. It will now correctly flag the dependency for being outdated.
|
||||
- Fixed the TM Machine refusing move selections that the `unlockAllMoveDexMovesByDefault` config had made visible, leaving the move slot blank and the craft button unresponsive.
|
||||
- Fixed the Beast Ball not applying its 0.1× penalty to Pokémon that are not Ultra Beasts.
|
||||
- Fixed the Moon Ball reading the world's total elapsed time instead of the time of day, so its bonus applied during the day instead.
|
||||
- Fixed the Love Ball never awarding its 2.5× opposite gender bonus, and matching species by display name instead of identifier.
|
||||
- Fixed the Timer Ball being weaker than a regular Poké Ball on early turns and only reaching 4× on turn 14 instead of turn 10.
|
||||
- Fixed the Luxury Ball only doubling Friendship gains of 1, leaving level up and berry gains unaffected.
|
||||
- Fixed Rufflet, Braviary, and Hisuian Braviary flooding logs with errors about missing sound events.
|
||||
- Fixed Pokémon property typos in Pangoro and Dedenne herd spawn files.
|
||||
- Fixed unintentional watermelon cosmetic for Hisuian Electrode.
|
||||
- Fixed Blastoise having an unintentional passenger seat.
|
||||
- Fixed form typo in Rockruff-Dusk spawn, preventing it from being able to spawn.
|
||||
- Fixed the `stat_compare` and `stat_equal` evolution requirements crashing the game when given `special_attack` or `special_defence`, and made them treat any non-permanent stat as a failed requirement instead of crashing.
|
||||
- Fixed Rowap and Jacoba berries not correctly altering Pokémon sizes when used as bait.
|
||||
- Fixed Ampharos' eyes not emitting particles.
|
||||
- Fixed Alolan Raticate's cry not playing.
|
||||
- Fixed several incorrect light-based spawning conditions for ghosts and bugs.
|
||||
- Removed unused, placeholder habitat pools.
|
||||
- Fixed Mantyke, Mantine, and Quaxly getting stuck in a recoil 'expression' during battles due to having an expression assigned as a recoil animation.
|
||||
- Fixed Lucario's aura particles not emitting.
|
||||
- Fixed Lycanroc's head movement.
|
||||
- Added head movement to Archaludon.
|
||||
- Fixed Duraludon line not having their sleep animations.
|
||||
- Fixed Diglett line not having their faint animations.
|
||||
- Fixed Kingambit moving its legs while walking.
|
||||
|
||||
### Localization
|
||||
- Updated translations for:
|
||||
- Brazilian Portuguese
|
||||
- Simplified Chinese
|
||||
- Japanese
|
||||
@@ -1,9 +1,9 @@
|
||||
|
||||
import utilities.isSnapshot
|
||||
import utilities.version
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneOffset
|
||||
import java.time.format.DateTimeFormatter
|
||||
import utilities.isSnapshot
|
||||
import utilities.version
|
||||
|
||||
/*
|
||||
*
|
||||
@@ -66,8 +66,6 @@ dependencies {
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
// Static GL mocks must not load a graphics driver on headless CI.
|
||||
systemProperty("org.lwjgl.opengl.explicitInit", "true")
|
||||
testLogging {
|
||||
setEvents(listOf("failed"))
|
||||
setExceptionFormat("full")
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
|
||||
package com.cobblemon.mod.common.mixin;
|
||||
|
||||
import com.cobblemon.mod.common.CobblemonNetwork;
|
||||
import com.cobblemon.mod.common.OrientationControllable;
|
||||
import com.cobblemon.mod.common.api.orientation.OrientationController;
|
||||
import com.cobblemon.mod.common.api.pokemon.effect.ShoulderEffectRegistry;
|
||||
@@ -18,7 +17,6 @@ import com.cobblemon.mod.common.api.riding.behaviour.types.liquid.SubmarineBehav
|
||||
import com.cobblemon.mod.common.client.entity.PokemonClientDelegate;
|
||||
import com.cobblemon.mod.common.client.render.MatrixWrapper;
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity;
|
||||
import com.cobblemon.mod.common.net.messages.server.orientation.ServerboundUpdateOrientationPacket;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
-2
@@ -10,9 +10,7 @@ package com.cobblemon.mod.common.mixin.accessor;
|
||||
|
||||
import net.minecraft.client.gui.components.StateSwitchingButton;
|
||||
import net.minecraft.client.gui.screens.recipebook.RecipeBookComponent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Mutable;
|
||||
import org.spongepowered.asm.mixin.gen.Accessor;
|
||||
|
||||
@Mixin(RecipeBookComponent.class)
|
||||
|
||||
+1
-2
@@ -15,11 +15,9 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
|
||||
import com.llamalad7.mixinextras.sugar.Local;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.NonNullList;
|
||||
import net.minecraft.world.Containers;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.alchemy.PotionBrewing;
|
||||
import net.minecraft.world.item.crafting.RecipeHolder;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
@@ -34,6 +32,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Mixin(BrewingStandBlockEntity.class)
|
||||
public class BrewingStandBlockEntityMixin {
|
||||
|
||||
|
||||
@@ -9,17 +9,11 @@
|
||||
package com.cobblemon.mod.common.mixin.brewing;
|
||||
|
||||
import com.cobblemon.mod.common.duck.RecipeAwareSlot;
|
||||
import com.cobblemon.mod.common.item.crafting.brewingstand.BrewingStandRecipe;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
|
||||
import com.llamalad7.mixinextras.sugar.Local;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.inventory.BrewingStandMenu;
|
||||
import net.minecraft.world.inventory.ContainerData;
|
||||
import net.minecraft.world.inventory.Slot;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
|
||||
@@ -13,7 +13,6 @@ import com.cobblemon.mod.common.item.crafting.brewingstand.BrewingStandRecipe;
|
||||
import net.minecraft.world.inventory.BrewingStandMenu;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Unique;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
|
||||
@@ -19,7 +19,6 @@ import net.minecraft.client.Camera;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
import org.spongepowered.asm.mixin.Final;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
|
||||
@@ -10,9 +10,7 @@ package com.cobblemon.mod.common.mixin.client;
|
||||
|
||||
import com.cobblemon.mod.common.CobblemonRecipeCategories;
|
||||
import com.cobblemon.mod.common.item.crafting.CookingPotBookCategory;
|
||||
import com.cobblemon.mod.common.item.crafting.CookingPotRecipe;
|
||||
import com.cobblemon.mod.common.item.crafting.CookingPotRecipeBase;
|
||||
import com.cobblemon.mod.common.item.crafting.CookingPotShapelessRecipe;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
@@ -1,30 +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.mixin.client;
|
||||
|
||||
import com.cobblemon.mod.common.client.render.RenderAlphaScope;
|
||||
import net.minecraft.client.renderer.RenderStateShard;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(RenderStateShard.class)
|
||||
public abstract class RenderStateShardMixin {
|
||||
@Inject(method = "setupRenderState", at = @At("RETURN"))
|
||||
private void cobblemon$applyScopedAlpha(CallbackInfo ci) {
|
||||
if ((Object) this instanceof RenderType) RenderAlphaScope.afterMaterialSetup();
|
||||
}
|
||||
|
||||
@Inject(method = "clearRenderState", at = @At("RETURN"))
|
||||
private void cobblemon$restoreScopedAlpha(CallbackInfo ci) {
|
||||
if ((Object) this instanceof RenderType) RenderAlphaScope.afterMaterialClear();
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,6 @@ import com.cobblemon.mod.common.api.habitats.HabitatPools
|
||||
import com.cobblemon.mod.common.api.interaction.RequestManager
|
||||
import com.cobblemon.mod.common.api.molang.MoLangLoadedFilesCache
|
||||
import com.cobblemon.mod.common.api.molang.ObjectValue
|
||||
import com.cobblemon.mod.common.api.molangui.MolangUiActionRegistry
|
||||
import com.cobblemon.mod.common.api.molangui.MolangUiService
|
||||
import com.cobblemon.mod.common.api.permission.PermissionValidator
|
||||
import com.cobblemon.mod.common.api.pokeball.catching.calculators.CaptureCalculator
|
||||
import com.cobblemon.mod.common.api.pokeball.catching.calculators.CaptureCalculators
|
||||
@@ -71,7 +69,6 @@ import com.cobblemon.mod.common.api.storage.player.adapter.TMMoveNbtBackend
|
||||
import com.cobblemon.mod.common.api.storage.player.factory.CachedPlayerDataStoreFactory
|
||||
import com.cobblemon.mod.common.api.tags.CobblemonEntityTypeTags
|
||||
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
|
||||
import com.cobblemon.mod.common.api.vending.VendingMachinePageHandler
|
||||
import com.cobblemon.mod.common.battles.BagItems
|
||||
import com.cobblemon.mod.common.battles.BattleFormat
|
||||
import com.cobblemon.mod.common.battles.BattleRegistry
|
||||
@@ -100,10 +97,10 @@ import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.aspects.ALPHA_ASPECT
|
||||
import com.cobblemon.mod.common.pokemon.aspects.CHARACTERISTIC_RAINBOW_ASPECT
|
||||
import com.cobblemon.mod.common.pokemon.aspects.COSMETIC_SLOT_ASPECT
|
||||
import com.cobblemon.mod.common.pokemon.aspects.FORM_ASPECTS
|
||||
import com.cobblemon.mod.common.pokemon.aspects.GENDER_ASPECT
|
||||
import com.cobblemon.mod.common.pokemon.aspects.MARK_ASPECT
|
||||
import com.cobblemon.mod.common.pokemon.aspects.SHINY_ASPECT
|
||||
import com.cobblemon.mod.common.pokemon.evolution.variants.BlockClickEvolution
|
||||
import com.cobblemon.mod.common.pokemon.feature.SlowpokeTailRegrowthSpeciesFeature
|
||||
import com.cobblemon.mod.common.pokemon.feature.SlowpokeTailRegrowthSpeciesFeatureProvider
|
||||
import com.cobblemon.mod.common.pokemon.feature.TagSeasonResolver
|
||||
@@ -118,6 +115,7 @@ import com.cobblemon.mod.common.pokemon.properties.NoAIProperty
|
||||
import com.cobblemon.mod.common.pokemon.properties.UnaspectPropertyType
|
||||
import com.cobblemon.mod.common.pokemon.properties.UncatchableProperty
|
||||
import com.cobblemon.mod.common.pokemon.stat.CobblemonStatProvider
|
||||
import com.cobblemon.mod.common.pokemon.transformation.triggers.BlockClickTrigger
|
||||
import com.cobblemon.mod.common.starter.CobblemonStarterHandler
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import com.cobblemon.mod.common.world.feature.CobblemonPlacedFeatures
|
||||
@@ -262,7 +260,6 @@ object Cobblemon {
|
||||
playerDataManager.onPlayerDisconnect(it.player)
|
||||
RequestManager.onLogoff(it.player)
|
||||
serverPlayerStructs.remove(it.player.uuid)
|
||||
MolangUiService.closeAllForPlayer(it.player.uuid)
|
||||
}
|
||||
PlatformEvents.PLAYER_DEATH.subscribe {
|
||||
PCLinkManager.removeLink(it.player.uuid)
|
||||
@@ -277,13 +274,8 @@ object Cobblemon {
|
||||
PlatformEvents.RIGHT_CLICK_BLOCK.subscribe { event ->
|
||||
val player = event.player
|
||||
val block = player.level().getBlockState(event.pos).block
|
||||
player.party().forEach { pokemon ->
|
||||
pokemon.lockedEvolutions
|
||||
.filterIsInstance<BlockClickEvolution>()
|
||||
.forEach { evolution ->
|
||||
evolution.attemptEvolution(pokemon, BlockClickEvolution.BlockInteractionContext(block, player.level()))
|
||||
}
|
||||
}
|
||||
val context = BlockClickTrigger.Context(block, player.level())
|
||||
player.party().forEach { pokemon -> pokemon.triggerTransformations<BlockClickTrigger>(context) }
|
||||
}
|
||||
|
||||
PlatformEvents.CHANGE_DIMENSION.subscribe {
|
||||
@@ -325,13 +317,9 @@ object Cobblemon {
|
||||
// Start up the data provider.
|
||||
CobblemonDataProvider.registerDefaults()
|
||||
|
||||
MolangUiActionRegistry.register(
|
||||
VendingMachinePageHandler.ACTION,
|
||||
VendingMachinePageHandler
|
||||
)
|
||||
|
||||
SHINY_ASPECT.register()
|
||||
GENDER_ASPECT.register()
|
||||
FORM_ASPECTS.register()
|
||||
COSMETIC_SLOT_ASPECT.register()
|
||||
CHARACTERISTIC_RAINBOW_ASPECT.register()
|
||||
ALPHA_ASPECT.register()
|
||||
@@ -459,7 +447,6 @@ object Cobblemon {
|
||||
}
|
||||
|
||||
PlatformEvents.SERVER_STOPPED.subscribe {
|
||||
MolangUiService.closeAll()
|
||||
storage.unregisterAll(it.server.registryAccess())
|
||||
playerDataManager.saveAllStores()
|
||||
playerDataManager.saveExecutor.shutdown()
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
package com.cobblemon.mod.common
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.cobblemon.mod.common.CobblemonBehaviours.autoPokemonBehaviours
|
||||
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
|
||||
import com.cobblemon.mod.common.api.ai.CobblemonBehaviour
|
||||
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
|
||||
@@ -19,16 +20,7 @@ import com.cobblemon.mod.common.api.molang.ExpressionLike
|
||||
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
|
||||
import com.cobblemon.mod.common.api.reactive.SimpleObservable
|
||||
import com.cobblemon.mod.common.net.messages.client.data.BehaviourSyncPacket
|
||||
import com.cobblemon.mod.common.util.adapters.ActivityAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.BehaviourConfigAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.ExpressionAdapter
|
||||
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.SensorTypeAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.TaskConfigAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.TranslatedTextAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.*
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.endsWith
|
||||
import com.google.gson.Gson
|
||||
|
||||
@@ -16,8 +16,6 @@ import com.cobblemon.mod.common.block.MintBlock.MintType
|
||||
import com.cobblemon.mod.common.block.campfirepot.CampfireBlock
|
||||
import com.cobblemon.mod.common.block.campfirepot.CampfirePotBlock
|
||||
import com.cobblemon.mod.common.block.chest.GildedChestBlock
|
||||
import com.cobblemon.mod.common.block.decor.ActivatableDecorationBlock
|
||||
import com.cobblemon.mod.common.block.decor.RingTargetBlock
|
||||
import com.cobblemon.mod.common.block.general.BaleBlock
|
||||
import com.cobblemon.mod.common.block.general.HorizontalRotationCarpetBlock
|
||||
import com.cobblemon.mod.common.block.general.HorizontalRotationalBlock
|
||||
@@ -622,88 +620,6 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
|
||||
@JvmField
|
||||
val WEAKNESS_POLICY = create("weakness_policy", WallAttachedDirectionalShapeBlock(BlockBehaviour.Properties.of().sound(CobblemonSounds.ITEM_BLOCK_PAPER_LARGE_SOUNDS).mapColor(MapColor.NONE).noOcclusion().noCollission(), 14, 12, 1))
|
||||
|
||||
@JvmField
|
||||
val RING_TARGET = create("ring_target", RingTargetBlock(BlockBehaviour.Properties.of().sound(SoundType.WOOD).mapColor(MapColor.NONE).noOcclusion().strength(0.125f)))
|
||||
@JvmField
|
||||
val MAGNET = create("magnet", MagnetBlock(BlockBehaviour.Properties.of().sound(SoundType.METAL).mapColor(MapColor.NONE).noOcclusion().strength(0.075f)))
|
||||
@JvmField
|
||||
val GALARICA_WREATH = create("galarica_wreath", GalaricaWreathBlock(BlockBehaviour.Properties.of().sound(SoundType.AZALEA_LEAVES).mapColor(MapColor.NONE).noOcclusion().noCollission()))
|
||||
|
||||
@JvmField
|
||||
val FLAME_ORB = create("flame_orb", OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion().lightLevel{15}))
|
||||
@JvmField
|
||||
val TOXIC_ORB = create("toxic_orb", OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion()))
|
||||
@JvmField
|
||||
val LIFE_ORB = create("life_orb", OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion().lightLevel{7}))
|
||||
@JvmField
|
||||
val LIGHT_BALL = create("light_ball", OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion().lightLevel{13}))
|
||||
@JvmField
|
||||
val SMOKE_BALL = create("smoke_ball", OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion()))
|
||||
|
||||
@JvmField
|
||||
val KINGS_ROCK = create("kings_rock", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(CobblemonSounds.TUMBLESTONE_BLOCK_SOUNDS).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.CENTERED_6x))
|
||||
|
||||
@JvmField
|
||||
val GALARICA_CUFF = create("galarica_cuff", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.AZALEA_LEAVES).mapColor(MapColor.NONE).noCollission().noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.FLATTENED_10x4))
|
||||
@JvmField
|
||||
val UNREMARKABLE_TEACUP = create("unremarkable_teacup", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DECORATED_POT).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.TEACUP))
|
||||
@JvmField
|
||||
val MASTERPIECE_TEACUP = create("masterpiece_teacup", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DECORATED_POT).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.TEACUP))
|
||||
@JvmField
|
||||
val CHIPPED_POT = create("chipped_pot", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DECORATED_POT).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.TEAPOT))
|
||||
@JvmField
|
||||
val CRACKED_POT = create("cracked_pot", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DECORATED_POT).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.TEAPOT))
|
||||
|
||||
@JvmField
|
||||
val SACHET = create("sachet", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.WOOL).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.POUCH))
|
||||
@JvmField
|
||||
val METAL_POWDER = create("metal_powder", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.WOOL).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.POUCH))
|
||||
@JvmField
|
||||
val QUICK_POWDER = create("quick_powder", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.WOOL).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.POUCH))
|
||||
@JvmField
|
||||
val BRIGHT_POWDER = create("bright_powder", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.WOOL).mapColor(MapColor.NONE).noOcclusion().lightLevel{3}, DecorativeItemBlock.DecorativeItemBlockType.POUCH))
|
||||
|
||||
@JvmField
|
||||
val NEVER_MELT_ICE = create("never_melt_ice", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion().friction(0.989F), DecorativeItemBlock.DecorativeItemBlockType.NEVERMELT))
|
||||
@JvmField
|
||||
val SCOPE_LENS = create("scope_lens", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.COPPER).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.SCOPE))
|
||||
@JvmField
|
||||
val WIDE_LENS = create("wide_lens", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.COPPER).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.WIDE))
|
||||
@JvmField
|
||||
val ZOOM_LENS = create("zoom_lens", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.COPPER).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.ZOOM))
|
||||
|
||||
@JvmField
|
||||
val ICY_ROCK = create("icy_rock", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DEEPSLATE).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.FLATTENED_8x4))
|
||||
@JvmField
|
||||
val HEAT_ROCK = create("heat_rock", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DEEPSLATE).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.FLATTENED_8x4))
|
||||
@JvmField
|
||||
val SMOOTH_ROCK = create("smooth_rock", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DEEPSLATE).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.FLATTENED_8x4))
|
||||
@JvmField
|
||||
val DAMP_ROCK = create("damp_rock", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.DEEPSLATE).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.FLATTENED_8x6))
|
||||
@JvmField
|
||||
val DESTINY_KNOT = create("destiny_knot", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.WOOL).mapColor(MapColor.NONE).noOcclusion(), DecorativeItemBlock.DecorativeItemBlockType.KNOT))
|
||||
@JvmField
|
||||
val LUMINOUS_MOSS = create("luminous_moss", DecorativeItemBlock(BlockBehaviour.Properties.of().sound(SoundType.MOSS).mapColor(MapColor.NONE).noOcclusion().lightLevel{5}, DecorativeItemBlock.DecorativeItemBlockType.CENTERED_8x))
|
||||
|
||||
@JvmField
|
||||
val METRONOME = create("metronome", ActivatableDecorationBlock(BlockBehaviour.Properties.of().sound(SoundType.METAL).mapColor(MapColor.NONE).pushReaction(PushReaction.DESTROY).noOcclusion(), ActivatableDecorationBlock.ActivatableDecorationBlockType.METRONOME))
|
||||
@JvmField
|
||||
val EJECT_BUTTON = create("eject_button", EjectButtonBlock(BlockBehaviour.Properties.of().sound(SoundType.METAL).mapColor(MapColor.NONE).pushReaction(PushReaction.DESTROY).noOcclusion().strength(0.125f), 40))
|
||||
|
||||
@JvmField
|
||||
val LOADED_DICE = create("loaded_dice", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.DICE))
|
||||
@JvmField
|
||||
val IRON_BALL = create("iron_ball", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.METAL).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.IRON_BALL))
|
||||
@JvmField
|
||||
val METAL_COAT = create("metal_coat", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.METAL).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.METAL_COAT))
|
||||
@JvmField
|
||||
val UPGRADE = create("upgrade", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.UPGRADE))
|
||||
@JvmField
|
||||
val DUBIOUS_DISC = create("dubious_disc", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.UPGRADE))
|
||||
|
||||
@JvmField
|
||||
val THROAT_SPRAY = create("throat_spray", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.THROAT_SPRAY))
|
||||
|
||||
@JvmField
|
||||
val FULL_HEAL = create("full_heal", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.STATUS_RESTORE))
|
||||
@JvmField
|
||||
@@ -754,23 +670,6 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
|
||||
@JvmField
|
||||
val X_SPEED = create("x_${Stats.SPEED.identifier.path}", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.BATTLE_ITEM))
|
||||
|
||||
@JvmField
|
||||
val HP_UP = create("hp_up", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
@JvmField
|
||||
val PROTEIN = create("protein", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
@JvmField
|
||||
val IRON = create("iron", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
@JvmField
|
||||
val CARBOS = create("carbos", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
@JvmField
|
||||
val CALCIUM = create("calcium", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
@JvmField
|
||||
val ZINC = create("zinc", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
@JvmField
|
||||
val PP_UP = create("pp_up", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
@JvmField
|
||||
val PP_MAX = create("pp_max", StackableItemBlock(BlockBehaviour.Properties.of().sound(SoundType.CANDLE).mapColor(MapColor.NONE).noOcclusion(), StackableItemBlock.StackableItemBlockType.VITAMIN))
|
||||
|
||||
@JvmField
|
||||
val MONITOR = create("monitor", MonitorBlock(BlockBehaviour.Properties.of().mapColor(MapColor.METAL).sound(SoundType.METAL).pushReaction(PushReaction.BLOCK).requiresCorrectToolForDrops().strength(5.0F, 6.0F).lightLevel { if (it.getValue(MonitorBlock.SCREEN) != MonitorBlock.MonitorScreen.OFF) 13 else 0 }))
|
||||
@JvmField
|
||||
@@ -808,9 +707,6 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
|
||||
@JvmField
|
||||
val DISPLAY_CASE = create("display_case", DisplayCaseBlock(BlockBehaviour.Properties.of().sound(CobblemonSounds.DISPLAY_CASE_SOUNDS).noOcclusion().pushReaction(PushReaction.BLOCK).mapColor(MapColor.STONE).strength(0.3F).requiresCorrectToolForDrops()))
|
||||
|
||||
@JvmField
|
||||
val VENDING_MACHINE = create("vending_machine", VendingMachineBlock(BlockBehaviour.Properties.of().mapColor(MapColor.METAL).sound(SoundType.METAL).pushReaction(PushReaction.BLOCK).strength(2F).requiresCorrectToolForDrops()))
|
||||
|
||||
// TODO after 1.7
|
||||
// @JvmField
|
||||
// val INCENSE_SWEET = create("incense_sweet", SweetIncenseBlock(BlockBehaviour.Properties.of().sound(CobblemonSounds.DISPLAY_CASE_SOUNDS).noOcclusion().pushReaction(PushReaction.BLOCK).mapColor(MapColor.STONE).strength(0.3F)))
|
||||
|
||||
@@ -41,6 +41,8 @@ object CobblemonCommands {
|
||||
HeldItemCommand.register(dispatcher, registry)
|
||||
PcCommand.register(dispatcher)
|
||||
SpawnPokemonFromPool.register(dispatcher)
|
||||
SpawnMeteorCommand.register(dispatcher)
|
||||
SetMegaBondCommand.register(dispatcher)
|
||||
PokeboxCommand.register(dispatcher)
|
||||
PokedexCommand.register(dispatcher)
|
||||
TestStoreCommand.register(dispatcher)
|
||||
@@ -77,6 +79,5 @@ object CobblemonCommands {
|
||||
// Possibly lock down registration if and only if under dev environment or running in an environment
|
||||
// with a certain system environment variable set
|
||||
CobblemonInfoCommand.register(dispatcher)
|
||||
MolangUiCommand.register(dispatcher)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import com.cobblemon.mod.common.entity.generic.GenericBedrockEntity
|
||||
import com.cobblemon.mod.common.entity.npc.NPCEntity
|
||||
import com.cobblemon.mod.common.entity.pokeball.EmptyPokeBallEntity
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.entity.projectile.FallingStarEntity
|
||||
import com.cobblemon.mod.common.platform.PlatformRegistry
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import net.minecraft.core.Registry
|
||||
@@ -95,6 +96,15 @@ object CobblemonEntities : PlatformRegistry<Registry<EntityType<*>>, ResourceKey
|
||||
EntityType.Builder.of({ _, world -> NPCEntity(world) }, MobCategory.CREATURE).build("$NPC_KEY")
|
||||
)
|
||||
|
||||
@JvmField
|
||||
val FALLING_STAR_KEY = cobblemonResource("falling_star")
|
||||
@JvmField
|
||||
val FALLING_STAR: EntityType<FallingStarEntity> = create(
|
||||
FALLING_STAR_KEY.path,
|
||||
EntityType.Builder.of(::FallingStarEntity, MobCategory.MISC).sized(0.5F, 0.5F).clientTrackingRange(8)
|
||||
.build(FALLING_STAR_KEY.toString())
|
||||
)
|
||||
|
||||
fun registerAttributes(consumer: (EntityType<out LivingEntity>, AttributeSupplier.Builder) -> Unit) {
|
||||
consumer(POKEMON, PokemonEntity.createAttributes())
|
||||
consumer(NPC, NPCEntity.createAttributes())
|
||||
|
||||
@@ -19,7 +19,6 @@ import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.server.packs.PackType
|
||||
import net.minecraft.server.packs.resources.PreparableReloadListener
|
||||
import net.minecraft.tags.TagKey
|
||||
import net.minecraft.world.inventory.MenuType
|
||||
import net.minecraft.world.level.GameRules
|
||||
import net.minecraft.world.level.ItemLike
|
||||
import net.minecraft.world.level.biome.Biome
|
||||
|
||||
@@ -33,6 +33,12 @@ object CobblemonItemComponents : PlatformRegistry<Registry<DataComponentType<*>>
|
||||
.networkSynchronized(HeldItemEffectComponent.PACKET_CODEC)
|
||||
.build())
|
||||
|
||||
@JvmField
|
||||
val MEGA_BOND: DataComponentType<MegaBondComponent> = create("mega_bond", DataComponentType.builder<MegaBondComponent>()
|
||||
.persistent(MegaBondComponent.CODEC)
|
||||
.networkSynchronized(MegaBondComponent.PACKET_CODEC)
|
||||
.build())
|
||||
|
||||
@JvmField
|
||||
val BAIT: DataComponentType<RodBaitComponent> = create("bait", DataComponentType.builder<RodBaitComponent>()
|
||||
.persistent(RodBaitComponent.CODEC)
|
||||
|
||||
@@ -465,8 +465,6 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
val PASTURE = blockItem("pasture", CobblemonBlocks.PASTURE)
|
||||
@JvmField
|
||||
val DISPLAY_CASE = blockItem("display_case", CobblemonBlocks.DISPLAY_CASE)
|
||||
@JvmField
|
||||
val VENDING_MACHINE = blockItem("vending_machine", CobblemonBlocks.VENDING_MACHINE)
|
||||
// @JvmField
|
||||
// val INCENSE_SWEET = blockItem("incense_sweet", CobblemonBlocks.INCENSE_SWEET) // TODO after 1.7
|
||||
|
||||
@@ -474,9 +472,9 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
// Evolution items
|
||||
@JvmField val LINK_CABLE = create("link_cable", LinkCableItem())
|
||||
@JvmField val DRAGON_SCALE = noSettingsItem("dragon_scale")
|
||||
@JvmField val METAL_COAT = itemNameBlockItem("metal_coat", CobblemonBlocks.METAL_COAT)
|
||||
@JvmField val UPGRADE = itemNameBlockItem("upgrade", CobblemonBlocks.UPGRADE)
|
||||
@JvmField val DUBIOUS_DISC = itemNameBlockItem("dubious_disc", CobblemonBlocks.DUBIOUS_DISC)
|
||||
@JvmField val METAL_COAT = noSettingsItem("metal_coat")
|
||||
@JvmField val UPGRADE = noSettingsItem("upgrade")
|
||||
@JvmField val DUBIOUS_DISC = noSettingsItem("dubious_disc")
|
||||
@JvmField val DEEP_SEA_SCALE = noSettingsItem("deep_sea_scale")
|
||||
@JvmField val DEEP_SEA_TOOTH = noSettingsItem("deep_sea_tooth")
|
||||
@JvmField val ELECTIRIZER = noSettingsItem("electirizer")
|
||||
@@ -485,7 +483,7 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField val PROTECTOR = noSettingsItem("protector")
|
||||
@JvmField val REAPER_CLOTH = noSettingsItem("reaper_cloth")
|
||||
@JvmField val PRISM_SCALE = noSettingsItem("prism_scale")
|
||||
@JvmField val SACHET = itemNameBlockItem("sachet", CobblemonBlocks.SACHET)
|
||||
@JvmField val SACHET = noSettingsItem("sachet")
|
||||
@JvmField val WHIPPED_DREAM = create("whipped_dream", foodItem(8, 0.3f))
|
||||
@JvmField val STRAWBERRY_SWEET = create("strawberry_sweet", foodItem(6, 0.125f))
|
||||
@JvmField val LOVE_SWEET = create("love_sweet", foodItem(6, 0.125f))
|
||||
@@ -494,20 +492,22 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField val FLOWER_SWEET = create("flower_sweet", foodItem(6, 0.125f))
|
||||
@JvmField val STAR_SWEET = create("star_sweet", foodItem(6, 0.125f))
|
||||
@JvmField val RIBBON_SWEET = create("ribbon_sweet", foodItem(6, 0.125f))
|
||||
@JvmField val CHIPPED_POT = itemNameBlockItem("chipped_pot", CobblemonBlocks.CHIPPED_POT)
|
||||
@JvmField val CRACKED_POT = itemNameBlockItem("cracked_pot", CobblemonBlocks.CRACKED_POT)
|
||||
@JvmField val MASTERPIECE_TEACUP = itemNameBlockItem("masterpiece_teacup", CobblemonBlocks.MASTERPIECE_TEACUP)
|
||||
@JvmField val UNREMARKABLE_TEACUP = itemNameBlockItem("unremarkable_teacup", CobblemonBlocks.UNREMARKABLE_TEACUP)
|
||||
@JvmField val CHIPPED_POT = noSettingsItem("chipped_pot")
|
||||
@JvmField val CRACKED_POT = noSettingsItem("cracked_pot")
|
||||
@JvmField val MASTERPIECE_TEACUP = noSettingsItem("masterpiece_teacup")
|
||||
@JvmField val UNREMARKABLE_TEACUP = noSettingsItem("unremarkable_teacup")
|
||||
@JvmField val SWEET_APPLE = compostableItem("sweet_apple", foodItem(4, 0.3f), 0.65f)
|
||||
@JvmField val TART_APPLE = compostableItem("tart_apple", foodItem(4, 0.3f), 0.65f)
|
||||
@JvmField val SYRUPY_APPLE = compostableItem("syrupy_apple", foodItem(4, 0.3f), 0.65f)
|
||||
@JvmField val GALARICA_CUFF = itemNameBlockItem("galarica_cuff", CobblemonBlocks.GALARICA_CUFF)
|
||||
@JvmField val GALARICA_CUFF = noSettingsItem("galarica_cuff")
|
||||
@JvmField val GALARICA_WREATH = noSettingsItem("galarica_wreath")
|
||||
@JvmField val BLACK_AUGURITE = noSettingsItem("black_augurite")
|
||||
@JvmField val PEAT_BLOCK = noSettingsItem("peat_block")
|
||||
@JvmField val RAZOR_CLAW = noSettingsItem("razor_claw")
|
||||
@JvmField val RAZOR_FANG = noSettingsItem("razor_fang")
|
||||
@JvmField val AUSPICIOUS_ARMOR = heldItem("auspicious_armor")
|
||||
@JvmField val MALICIOUS_ARMOR = heldItem("malicious_armor")
|
||||
@JvmField val SHELL_HELMET = heldItem("shell_helmet")
|
||||
@JvmField val METAL_ALLOY = noSettingsItem("metal_alloy")
|
||||
@JvmField val SCROLL_OF_DARKNESS = noSettingsItem("scroll_of_darkness")
|
||||
@JvmField val SCROLL_OF_WATERS = noSettingsItem("scroll_of_waters")
|
||||
@@ -651,17 +651,17 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField
|
||||
val EXPERIENCE_CANDY_XL = candyItem("exp_candy_xl") { _, _ -> CandyItem.DEFAULT_XL_CANDY_YIELD }
|
||||
@JvmField
|
||||
val CALCIUM = create("calcium", VitaminItem(Stats.SPECIAL_ATTACK, CobblemonBlocks.CALCIUM))
|
||||
val CALCIUM = create("calcium", VitaminItem(Stats.SPECIAL_ATTACK))
|
||||
@JvmField
|
||||
val CARBOS = create("carbos", VitaminItem(Stats.SPEED, CobblemonBlocks.CARBOS))
|
||||
val CARBOS = create("carbos", VitaminItem(Stats.SPEED))
|
||||
@JvmField
|
||||
val HP_UP = create("hp_up", VitaminItem(Stats.HP, CobblemonBlocks.HP_UP))
|
||||
val HP_UP = create("hp_up", VitaminItem(Stats.HP))
|
||||
@JvmField
|
||||
val IRON = create("iron", VitaminItem(Stats.DEFENCE, CobblemonBlocks.IRON))
|
||||
val IRON = create("iron", VitaminItem(Stats.DEFENCE))
|
||||
@JvmField
|
||||
val PROTEIN = create("protein", VitaminItem(Stats.ATTACK, CobblemonBlocks.PROTEIN))
|
||||
val PROTEIN = create("protein", VitaminItem(Stats.ATTACK))
|
||||
@JvmField
|
||||
val ZINC = create("zinc", VitaminItem(Stats.SPECIAL_DEFENCE, CobblemonBlocks.ZINC))
|
||||
val ZINC = create("zinc", VitaminItem(Stats.SPECIAL_DEFENCE))
|
||||
@JvmField
|
||||
val HEALTH_MOCHI = create("health_mochi", MochiItem(Stats.HP))
|
||||
@JvmField
|
||||
@@ -743,9 +743,9 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField
|
||||
val MAX_REVIVE = create("max_revive", ReviveItem(max = true))
|
||||
@JvmField
|
||||
val PP_UP = create("pp_up", PPUpItem(1, CobblemonBlocks.PP_UP))
|
||||
val PP_UP = create("pp_up", PPUpItem(1))
|
||||
@JvmField
|
||||
val PP_MAX = create("pp_max", PPUpItem(3, CobblemonBlocks.PP_MAX))
|
||||
val PP_MAX = create("pp_max", PPUpItem(3))
|
||||
|
||||
@JvmField
|
||||
val RED_MINT_SEEDS = mintSeed("red", MintType.RED.getCropBlock())
|
||||
@@ -914,6 +914,10 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
val THUNDER_STONE = noSettingsItem("thunder_stone")
|
||||
@JvmField
|
||||
val WATER_STONE = noSettingsItem("water_stone")
|
||||
@JvmField
|
||||
val MEGA_SHARD = noSettingsItem("mega_shard")
|
||||
@JvmField
|
||||
val DORMANT_MEGA_STONE = heldItem("dormant_mega_stone")
|
||||
|
||||
val wearables = mutableListOf<WearableItem>()
|
||||
//Wearable items (these items should have a corresponding 3D model)
|
||||
@@ -922,31 +926,44 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField val CHOICE_SPECS = wearableItem("choice_specs")
|
||||
@JvmField val EXP_SHARE = wearableItem("exp_share")
|
||||
@JvmField val FOCUS_BAND = wearableItem("focus_band")
|
||||
@JvmField val KINGS_ROCK = wearableBlockItem("kings_rock", CobblemonBlocks.KINGS_ROCK)
|
||||
@JvmField val NEVER_MELT_ICE = wearableBlockItem("never_melt_ice", CobblemonBlocks.NEVER_MELT_ICE)
|
||||
@JvmField val KINGS_ROCK = wearableItem("kings_rock")
|
||||
@JvmField val MUSCLE_BAND = wearableItem("muscle_band")
|
||||
@JvmField val ROCKY_HELMET = wearableItem("rocky_helmet")
|
||||
@JvmField val SAFETY_GOGGLES = wearableItem("safety_goggles")
|
||||
@JvmField val WISE_GLASSES = wearableItem("wise_glasses")
|
||||
@JvmField val SHARP_BEAK = wearableItem("sharp_beak")
|
||||
@JvmField val COVERT_CLOAK = wearableItem("covert_cloak")
|
||||
@JvmField val SHELL_HELMET = wearableItem("shell_helmet")
|
||||
@JvmField val GALARICA_WREATH = wearableBlockItem("galarica_wreath", CobblemonBlocks.GALARICA_WREATH)
|
||||
@JvmField val CLEANSE_TAG = wearableBlockItem("cleanse_tag", CobblemonBlocks.CLEANSE_TAG)
|
||||
@JvmField val SPELL_TAG = wearableBlockItem("spell_tag", CobblemonBlocks.SPELL_TAG)
|
||||
|
||||
// Held Items
|
||||
@JvmField
|
||||
val ABILITY_SHIELD = heldItem("ability_shield")
|
||||
@JvmField
|
||||
val ABOMASITE = heldItem("abomasite")
|
||||
@JvmField
|
||||
val ABSOLITE = heldItem("absolite")
|
||||
@JvmField
|
||||
val ABSORB_BULB = heldItem("absorb_bulb")
|
||||
@JvmField
|
||||
val AERODACTYLITE = heldItem("aerodactylite")
|
||||
@JvmField
|
||||
val AGGRONITE = heldItem("aggronite")
|
||||
@JvmField
|
||||
val AIR_BALLOON = heldItem("air_balloon")
|
||||
@JvmField
|
||||
val ALAKAZITE = heldItem("alakazite")
|
||||
@JvmField
|
||||
val ALTARIANITE = heldItem("altarianite")
|
||||
@JvmField
|
||||
val AMPHAROSITE = heldItem("ampharosite")
|
||||
@JvmField
|
||||
val ASSAULT_VEST = heldItem("assault_vest")
|
||||
@JvmField
|
||||
val BIG_ROOT = compostableBlockItem("big_root", CobblemonBlocks.BIG_ROOT, 0.30f)
|
||||
@JvmField
|
||||
val AUDINITE = heldItem("audinite")
|
||||
@JvmField
|
||||
val BANETTITE = heldItem("banettite")
|
||||
@JvmField
|
||||
val BEEDRILLITE = heldItem("beedrillite")
|
||||
@JvmField
|
||||
val BINDING_BAND = heldItem("binding_band")
|
||||
@JvmField
|
||||
val BLACK_BELT = heldItem("black_belt")
|
||||
@@ -955,19 +972,35 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField
|
||||
val BLUNDER_POLICY = itemNameBlockItem("blunder_policy", CobblemonBlocks.BLUNDER_POLICY)
|
||||
@JvmField
|
||||
val BLASTOISINITE = heldItem("blastoisinite")
|
||||
@JvmField
|
||||
val BLAZIKENITE = heldItem("blazikenite")
|
||||
@JvmField
|
||||
val CAMERUPTITE = heldItem("cameruptite")
|
||||
@JvmField
|
||||
val CELL_BATTERY = heldItem("cell_battery")
|
||||
@JvmField
|
||||
val CHARCOAL = heldItem("charcoal_stick", remappedName = "charcoal")
|
||||
@JvmField
|
||||
val CHARIZARDITE_X = heldItem("charizardite_x")
|
||||
@JvmField
|
||||
val CHARIZARDITE_Y = heldItem("charizardite_y")
|
||||
@JvmField
|
||||
val CHOICE_SCARF = heldItem("choice_scarf")
|
||||
@JvmField
|
||||
val CLEANSE_TAG = itemNameBlockItem("cleanse_tag", CobblemonBlocks.CLEANSE_TAG)
|
||||
@JvmField
|
||||
val CLEAR_AMULET = heldItem("clear_amulet")
|
||||
@JvmField
|
||||
val DESTINY_KNOT = itemNameBlockItem("destiny_knot", CobblemonBlocks.DESTINY_KNOT)
|
||||
val COVERT_CLOAK = heldItem("covert_cloak")
|
||||
@JvmField
|
||||
val DESTINY_KNOT = heldItem("destiny_knot")
|
||||
@JvmField
|
||||
val DIANCITE = heldItem("diancite")
|
||||
@JvmField
|
||||
val DRAGON_FANG = heldItem("dragon_fang")
|
||||
@JvmField
|
||||
val EJECT_BUTTON = itemNameBlockItem("eject_button", CobblemonBlocks.EJECT_BUTTON)
|
||||
val EJECT_BUTTON = heldItem("eject_button")
|
||||
@JvmField
|
||||
val EJECT_PACK = heldItem("eject_pack")
|
||||
@JvmField
|
||||
@@ -981,46 +1014,90 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField
|
||||
val FAIRY_FEATHER = heldItem("fairy_feather")
|
||||
@JvmField
|
||||
val FLAME_ORB = itemNameBlockItem("flame_orb", CobblemonBlocks.FLAME_ORB)
|
||||
val FLAME_ORB = heldItem("flame_orb")
|
||||
@JvmField
|
||||
val FLOAT_STONE = heldItem("float_stone")
|
||||
@JvmField
|
||||
val FOCUS_SASH = heldItem("focus_sash")
|
||||
@JvmField
|
||||
val GALLADITE = heldItem("galladite")
|
||||
@JvmField
|
||||
val GARCHOMPITE = heldItem("garchompite")
|
||||
@JvmField
|
||||
val GARDEVOIRITE = heldItem("gardevoirite")
|
||||
@JvmField
|
||||
val GENGARITE = heldItem("gengarite")
|
||||
@JvmField
|
||||
val GLALITITE = heldItem("glalitite")
|
||||
@JvmField
|
||||
val GRASSY_SEED = heldItem("grassy_seed")
|
||||
@JvmField
|
||||
val GRIP_CLAW = heldItem("grip_claw")
|
||||
@JvmField
|
||||
val GYARADOSITE = heldItem("gyaradosite")
|
||||
@JvmField
|
||||
val HARD_STONE = heldItem("hard_stone")
|
||||
@JvmField
|
||||
val HEAVY_DUTY_BOOTS = heldItem("heavy_duty_boots")
|
||||
@JvmField
|
||||
val IRON_BALL = itemNameBlockItem("iron_ball", CobblemonBlocks.IRON_BALL)
|
||||
val HERACRONITE = heldItem("heracronite")
|
||||
@JvmField
|
||||
val HOUNDOOMINITE = heldItem("houndoominite")
|
||||
@JvmField
|
||||
val IRON_BALL = heldItem("iron_ball")
|
||||
@JvmField
|
||||
val KANGASKHANITE = heldItem("kangaskhanite")
|
||||
@JvmField
|
||||
val LAGGING_TAIL = heldItem("lagging_tail")
|
||||
@JvmField
|
||||
val LEFTOVERS = compostableHeldItem("leftovers", null, 0.50f)
|
||||
@JvmField
|
||||
val LIFE_ORB = itemNameBlockItem("life_orb", CobblemonBlocks.LIFE_ORB)
|
||||
val LATIASITE = heldItem("latiasite")
|
||||
@JvmField
|
||||
val LIGHT_BALL = itemNameBlockItem("light_ball", CobblemonBlocks.LIGHT_BALL)
|
||||
val LATIOSITE = heldItem("latiosite")
|
||||
@JvmField
|
||||
val LIFE_ORB = heldItem("life_orb")
|
||||
@JvmField
|
||||
val LIGHT_BALL = heldItem("light_ball")
|
||||
@JvmField
|
||||
val LIGHT_CLAY = heldItem("light_clay")
|
||||
@JvmField
|
||||
val LOADED_DICE = itemNameBlockItem("loaded_dice", CobblemonBlocks.LOADED_DICE)
|
||||
val LOADED_DICE = heldItem("loaded_dice")
|
||||
@JvmField
|
||||
val LOPUNNITE = heldItem("lopunnite")
|
||||
@JvmField
|
||||
val LUCARIONITE = heldItem("lucarionite")
|
||||
@JvmField
|
||||
val LUCKY_EGG = heldItem("lucky_egg")
|
||||
@JvmField
|
||||
val LUMINOUS_MOSS = itemNameBlockItem("luminous_moss", CobblemonBlocks.LUMINOUS_MOSS)
|
||||
val LUMINOUS_MOSS = heldItem("luminous_moss")
|
||||
@JvmField
|
||||
val MAGNET = itemNameBlockItem("magnet", CobblemonBlocks.MAGNET)
|
||||
val MAGNET = heldItem("magnet")
|
||||
@JvmField
|
||||
val METRONOME = itemNameBlockItem("metronome", CobblemonBlocks.METRONOME)
|
||||
val MANECTITE = heldItem("manectite")
|
||||
@JvmField
|
||||
val MAWILITE = heldItem("mawilite")
|
||||
@JvmField
|
||||
val MEDICHAMITE = heldItem("medichamite")
|
||||
@JvmField
|
||||
val METAGROSSITE = heldItem("metagrossite")
|
||||
@JvmField
|
||||
val METRONOME = heldItem("metronome")
|
||||
@JvmField
|
||||
val MEWTWONITE_X = heldItem("mewtwonite_x")
|
||||
@JvmField
|
||||
val MEWTWONITE_Y = heldItem("mewtwonite_y")
|
||||
@JvmField
|
||||
val MIRACLE_SEED = heldItem("miracle_seed")
|
||||
@JvmField
|
||||
val MYSTIC_WATER = heldItem("mystic_water")
|
||||
@JvmField
|
||||
val NEVER_MELT_ICE = heldItem("never_melt_ice")
|
||||
@JvmField
|
||||
val PIDGEOTITE = heldItem("pidgeotite")
|
||||
@JvmField
|
||||
val PINSIRITE = heldItem("pinsirite")
|
||||
@JvmField
|
||||
val POISON_BARB = heldItem("poison_barb")
|
||||
@JvmField
|
||||
val POWER_ANKLET = heldItem("power_anklet")
|
||||
@@ -1045,11 +1122,23 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField
|
||||
val RED_CARD = heldItem("red_card")
|
||||
@JvmField
|
||||
val RING_TARGET = itemNameBlockItem("ring_target", CobblemonBlocks.RING_TARGET)
|
||||
val RING_TARGET = heldItem("ring_target")
|
||||
@JvmField
|
||||
val ROOM_SERVICE = heldItem("room_service")
|
||||
@JvmField
|
||||
val SCOPE_LENS = itemNameBlockItem("scope_lens", CobblemonBlocks.SCOPE_LENS)
|
||||
val SABLENITE = heldItem("sablenite")
|
||||
@JvmField
|
||||
val SALAMENCITE = heldItem("salamencite")
|
||||
@JvmField
|
||||
val SCEPTILITE = heldItem("sceptilite")
|
||||
@JvmField
|
||||
val SCIZORITE = heldItem("scizorite")
|
||||
@JvmField
|
||||
val SCOPE_LENS = heldItem("scope_lens")
|
||||
@JvmField
|
||||
val SHARP_BEAK = heldItem("sharp_beak")
|
||||
@JvmField
|
||||
val SHARPEDONITE = heldItem("sharpedonite")
|
||||
@JvmField
|
||||
val SHED_SHELL = heldItem("shed_shell")
|
||||
@JvmField
|
||||
@@ -1059,29 +1148,41 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField
|
||||
val SILVER_POWDER = heldItem("silver_powder")
|
||||
@JvmField
|
||||
val SLOWBRONITE = heldItem("slowbronite")
|
||||
@JvmField
|
||||
val SOFT_SAND = heldItem("soft_sand")
|
||||
@JvmField
|
||||
val SMOKE_BALL = itemNameBlockItem("smoke_ball", CobblemonBlocks.SMOKE_BALL)
|
||||
val SPELL_TAG = itemNameBlockItem("spell_tag", CobblemonBlocks.SPELL_TAG)
|
||||
@JvmField
|
||||
val SMOKE_BALL = heldItem("smoke_ball")
|
||||
@JvmField
|
||||
val SOOTHE_BELL = heldItem("soothe_bell")
|
||||
@JvmField
|
||||
val STEELIXITE = heldItem("steelixite")
|
||||
@JvmField
|
||||
val STICKY_BARB = heldItem("sticky_barb")
|
||||
@JvmField
|
||||
val SWAMPERTITE = heldItem("swampertite")
|
||||
@JvmField
|
||||
val TERRAIN_EXTENDER = heldItem("terrain_extender")
|
||||
@JvmField
|
||||
val THROAT_SPRAY = itemNameBlockItem("throat_spray", CobblemonBlocks.THROAT_SPRAY)
|
||||
val THROAT_SPRAY = heldItem("throat_spray")
|
||||
@JvmField
|
||||
val TOXIC_ORB = itemNameBlockItem("toxic_orb", CobblemonBlocks.TOXIC_ORB)
|
||||
val TOXIC_ORB = heldItem("toxic_orb")
|
||||
@JvmField
|
||||
val TWISTED_SPOON = heldItem("twisted_spoon")
|
||||
@JvmField
|
||||
val TYRANITARITE = heldItem("tyranitarite")
|
||||
@JvmField
|
||||
val UTILITY_UMBRELLA = heldItem("utility_umbrella")
|
||||
@JvmField
|
||||
val WEAKNESS_POLICY = itemNameBlockItem("weakness_policy", CobblemonBlocks.WEAKNESS_POLICY)
|
||||
@JvmField
|
||||
val WIDE_LENS = itemNameBlockItem("wide_lens", CobblemonBlocks.WIDE_LENS)
|
||||
val VENUSAURITE = heldItem("venusaurite")
|
||||
@JvmField
|
||||
val ZOOM_LENS = itemNameBlockItem("zoom_lens", CobblemonBlocks.ZOOM_LENS)
|
||||
val WIDE_LENS = heldItem("wide_lens")
|
||||
@JvmField
|
||||
val ZOOM_LENS = heldItem("zoom_lens")
|
||||
@JvmField
|
||||
val MENTAL_HERB = compostableHeldItem("mental_herb", null, 0.85F)
|
||||
@JvmField
|
||||
@@ -1093,19 +1194,19 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
@JvmField
|
||||
val WHITE_HERB = compostableHeldItem("white_herb", null, 0.85F)
|
||||
@JvmField
|
||||
val BRIGHT_POWDER = itemNameBlockItem("bright_powder", CobblemonBlocks.BRIGHT_POWDER)
|
||||
val BRIGHT_POWDER = heldItem("bright_powder")
|
||||
@JvmField
|
||||
val METAL_POWDER = itemNameBlockItem("metal_powder", CobblemonBlocks.METAL_POWDER)
|
||||
val METAL_POWDER = heldItem("metal_powder")
|
||||
@JvmField
|
||||
val QUICK_POWDER = itemNameBlockItem("quick_powder", CobblemonBlocks.QUICK_POWDER)
|
||||
val QUICK_POWDER = heldItem("quick_powder")
|
||||
@JvmField
|
||||
val DAMP_ROCK = itemNameBlockItem("damp_rock", CobblemonBlocks.DAMP_ROCK)
|
||||
val DAMP_ROCK = heldItem("damp_rock")
|
||||
@JvmField
|
||||
val HEAT_ROCK = itemNameBlockItem("heat_rock", CobblemonBlocks.HEAT_ROCK)
|
||||
val HEAT_ROCK = heldItem("heat_rock")
|
||||
@JvmField
|
||||
val SMOOTH_ROCK = itemNameBlockItem("smooth_rock", CobblemonBlocks.SMOOTH_ROCK)
|
||||
val SMOOTH_ROCK = heldItem("smooth_rock")
|
||||
@JvmField
|
||||
val ICY_ROCK = itemNameBlockItem("icy_rock", CobblemonBlocks.ICY_ROCK)
|
||||
val ICY_ROCK = heldItem("icy_rock")
|
||||
|
||||
// Mulch
|
||||
@JvmField
|
||||
@@ -1596,16 +1697,7 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
|
||||
private fun wearableItem(name: String, heldItemRemappedName: String? = null): CobblemonItem = create(
|
||||
name,
|
||||
WearableHatItem(name).also {
|
||||
wearables.add(it)
|
||||
if (heldItemRemappedName != null) {
|
||||
CobblemonHeldItemManager.registerRemap(it, heldItemRemappedName)
|
||||
}
|
||||
}
|
||||
)
|
||||
private fun wearableBlockItem(name: String, block: Block, heldItemRemappedName: String? = null): WearableBlockItem = create(
|
||||
name,
|
||||
WearableBlockItem(name, block).also {
|
||||
WearableItem(name).also {
|
||||
wearables.add(it)
|
||||
if (heldItemRemappedName != null) {
|
||||
CobblemonHeldItemManager.registerRemap(it, heldItemRemappedName)
|
||||
@@ -1762,4 +1854,4 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
|
||||
private fun foodItem(nutrition: Int, saturationModifier: Float): Item {
|
||||
return CobblemonItem(Item.Properties().food(FoodProperties.Builder().nutrition(nutrition).saturationModifier(saturationModifier).build()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<*>>()
|
||||
|
||||
@@ -10,7 +10,6 @@ package com.cobblemon.mod.common
|
||||
|
||||
|
||||
import com.cobblemon.mod.common.block.campfirepot.CookingPotMenu
|
||||
import com.cobblemon.mod.common.api.molangui.container.MolangContainerMenu
|
||||
import com.cobblemon.mod.common.block.tmmachine.TMMachineMenu
|
||||
import com.cobblemon.mod.common.platform.PlatformRegistry
|
||||
import net.minecraft.core.Registry
|
||||
@@ -23,10 +22,9 @@ object CobblemonMenuType : PlatformRegistry<Registry<MenuType<*>>, ResourceKey<R
|
||||
|
||||
val COOKING_POT = MenuType.register("cooking_pot_menu", ::CookingPotMenu)
|
||||
val TM_MACHINE = MenuType.register("tm_machine_menu", ::TMMachineMenu)
|
||||
val MOLANG_UI = MenuType.register("molang_ui", ::MolangContainerMenu)
|
||||
|
||||
override val registry: Registry<MenuType<*>>
|
||||
get() = BuiltInRegistries.MENU
|
||||
override val resourceKey: ResourceKey<Registry<MenuType<*>>>
|
||||
get() = Registries.MENU
|
||||
}
|
||||
}
|
||||
@@ -32,10 +32,6 @@ import com.cobblemon.mod.common.client.net.effect.SpawnSnowstormParticleHandler
|
||||
import com.cobblemon.mod.common.client.net.gui.ExpGainedDataPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.gui.InteractPokemonUIPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.gui.PokedexUIPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.molangui.MolangUiCloseHandler
|
||||
import com.cobblemon.mod.common.client.net.molangui.MolangUiCompatibilityRequestHandler
|
||||
import com.cobblemon.mod.common.client.net.molangui.MolangUiOpenHandler
|
||||
import com.cobblemon.mod.common.client.net.molangui.MolangUiUpdateHandler
|
||||
import com.cobblemon.mod.common.client.net.gui.SetActiveTMPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.gui.SetTMMachineContainerDataPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.gui.SummaryUIPacketHandler
|
||||
@@ -87,10 +83,6 @@ 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.molangui.MolangUiClosePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.molangui.MolangUiCompatibilityRequestPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.molangui.MolangUiOpenPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.molangui.MolangUiUpdatePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.debug.RequestOpenRidingStatsDebugGUIPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueClosedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueOpenedPacket
|
||||
@@ -115,10 +107,14 @@ import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.Add
|
||||
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.ClearEvolutionsPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.ClientboundSeatAssignmentPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.RemoveEvolutionPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.pokemon.update.form.AddFormPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.pokemon.update.form.ClearFormsPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.pokemon.update.form.RemoveFormPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.settings.OpenCobblemonConfigScreenPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.settings.ServerSettingsPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.sound.UnvalidatedPlaySoundS2CPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnGenericBedrockPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnFallingStarPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnNPCPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnPokeballPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnPokemonPacket
|
||||
@@ -188,9 +184,6 @@ import com.cobblemon.mod.common.net.messages.server.dialogue.EscapeDialoguePacke
|
||||
import com.cobblemon.mod.common.net.messages.server.dialogue.InputToDialoguePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.habitat.SaveHabitatBlockSettingsPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.npc.SaveNPCPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.molangui.MolangUiActionPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.molangui.MolangUiClosedPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.molangui.MolangUiCompatibilityResponsePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.orientation.ServerboundUpdateOrientationPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.pasture.PasturePokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.pasture.SetPastureConflictPacket
|
||||
@@ -205,6 +198,8 @@ import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetItemHidden
|
||||
import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetMarkingsPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetNicknamePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.pokemon.update.evolution.AcceptEvolutionPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.pokemon.update.form.AcceptFormPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.pokemon.update.form.RevertFormPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.riding.DismountPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.riding.ServerboundUpdateDriverInputPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.riding.ServerboundUpdatePassengerPositionPacket
|
||||
@@ -222,9 +217,11 @@ import com.cobblemon.mod.common.net.messages.server.trade.ChangeTradeAcceptanceP
|
||||
import com.cobblemon.mod.common.net.messages.server.trade.OfferTradePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.trade.PerformTradePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.trade.UpdateTradeOfferPacket
|
||||
import com.cobblemon.mod.common.net.serverhandling.AcceptFormHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.ChallengeHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.ChallengeResponseHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.RequestInteractionsHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.RevertFormHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.BattleSelectActionsHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.RemoveSpectatorHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.SpectateBattleHandler
|
||||
@@ -250,9 +247,6 @@ import com.cobblemon.mod.common.net.serverhandling.dialogue.InputToDialogueHandl
|
||||
import com.cobblemon.mod.common.net.serverhandling.evolution.AcceptEvolutionHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.habitat.SaveHabitatBlockSettingsHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.npc.SaveNPCHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.molangui.MolangUiActionHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.molangui.MolangUiClosedHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.molangui.MolangUiCompatibilityResponseHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.orientation.ServerboundUpdateOrientationHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.pasture.PasturePokemonHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.pasture.SetPastureConflictHandler
|
||||
@@ -459,11 +453,6 @@ object CobblemonNetwork {
|
||||
list.add(PacketRegisterInfo(RideSettingsSyncPacket.ID, RideSettingsSyncPacket::decode, RideSettingsSyncHandler))
|
||||
list.add(PacketRegisterInfo(TechnicalMachineRegistrySyncPacket.ID, TechnicalMachineRegistrySyncPacket::decode, DataRegistrySyncPacketHandler()))
|
||||
|
||||
list.add(PacketRegisterInfo(MolangUiOpenPacket.ID, MolangUiOpenPacket::decode, MolangUiOpenHandler))
|
||||
list.add(PacketRegisterInfo(MolangUiClosePacket.ID, MolangUiClosePacket::decode, MolangUiCloseHandler))
|
||||
list.add(PacketRegisterInfo(MolangUiUpdatePacket.ID, MolangUiUpdatePacket::decode, MolangUiUpdateHandler))
|
||||
list.add(PacketRegisterInfo(MolangUiCompatibilityRequestPacket.ID, MolangUiCompatibilityRequestPacket::decode, MolangUiCompatibilityRequestHandler))
|
||||
|
||||
// Effects
|
||||
list.add(PacketRegisterInfo(SpawnSnowstormParticlePacket.ID, SpawnSnowstormParticlePacket::decode, SpawnSnowstormParticleHandler))
|
||||
list.add(PacketRegisterInfo(SpawnSnowstormEntityParticlePacket.ID, SpawnSnowstormEntityParticlePacket::decode, SpawnSnowstormEntityParticleHandler))
|
||||
@@ -476,6 +465,7 @@ object CobblemonNetwork {
|
||||
list.add(PacketRegisterInfo(SpawnPokemonPacket.ID, SpawnPokemonPacket::decode, SpawnExtraDataEntityHandler()))
|
||||
list.add(PacketRegisterInfo(SpawnPokeballPacket.ID, SpawnPokeballPacket::decode, SpawnExtraDataEntityHandler()))
|
||||
list.add(PacketRegisterInfo(SpawnGenericBedrockPacket.ID, SpawnGenericBedrockPacket::decode, SpawnExtraDataEntityHandler()))
|
||||
list.add(PacketRegisterInfo(SpawnFallingStarPacket.ID, SpawnFallingStarPacket::decode, SpawnExtraDataEntityHandler()))
|
||||
list.add(PacketRegisterInfo(SpawnNPCPacket.ID, SpawnNPCPacket::decode, SpawnExtraDataEntityHandler()))
|
||||
list.add(PacketRegisterInfo(ToastPacket.ID, ToastPacket::decode, ToastPacketHandler))
|
||||
|
||||
@@ -525,6 +515,11 @@ object CobblemonNetwork {
|
||||
// Pokédex scanning
|
||||
list.add(PacketRegisterInfo(ServerConfirmedRegisterPacket.ID, ServerConfirmedRegisterPacket::decode, ServerConfirmedRegisterHandler))
|
||||
|
||||
// Form packets
|
||||
list.add(PacketRegisterInfo(AddFormPacket.ID, AddFormPacket::decode, PokemonUpdatePacketHandler()))
|
||||
list.add(PacketRegisterInfo(ClearFormsPacket.ID, ClearFormsPacket::decode, PokemonUpdatePacketHandler()))
|
||||
list.add(PacketRegisterInfo(RemoveFormPacket.ID, RemoveFormPacket::decode, PokemonUpdatePacketHandler()))
|
||||
|
||||
// Riding
|
||||
list.add(PacketRegisterInfo(ClientboundUpdateRidingStatePacket.ID, ClientboundUpdateRidingStatePacket::decode, ClientboundUpdateRidingStateHandler))
|
||||
list.add(PacketRegisterInfo(ClientboundUpdateDriverInputPacket.ID, ClientboundUpdateDriverInputPacket::decode, ClientboundUpdateDriverInputHandler))
|
||||
@@ -640,6 +635,10 @@ object CobblemonNetwork {
|
||||
// NPC packets
|
||||
list.add(PacketRegisterInfo(SaveNPCPacket.ID, SaveNPCPacket::decode, SaveNPCHandler))
|
||||
|
||||
// Form Packets
|
||||
list.add(PacketRegisterInfo(AcceptFormPacket.ID, AcceptFormPacket::decode, AcceptFormHandler))
|
||||
list.add(PacketRegisterInfo(RevertFormPacket.ID, RevertFormPacket::decode, RevertFormHandler))
|
||||
|
||||
// Riding packet(s)
|
||||
list.add(PacketRegisterInfo(ServerboundUpdateOrientationPacket.ID, ServerboundUpdateOrientationPacket::decode, ServerboundUpdateOrientationHandler))
|
||||
list.add(PacketRegisterInfo(ServerboundUpdateRidingStatePacket.ID, ServerboundUpdateRidingStatePacket::decode, ServerboundUpdateRidingStateHandler))
|
||||
@@ -662,10 +661,6 @@ object CobblemonNetwork {
|
||||
list.add(PacketRegisterInfo(SetEntityBehaviourPacket.ID, SetEntityBehaviourPacket::decode, SetEntityBehaviourHandler))
|
||||
list.add(PacketRegisterInfo(DamageOnCollisionPacket.ID, DamageOnCollisionPacket::decode, DamageOnCollisionPacketHandler))
|
||||
|
||||
list.add(PacketRegisterInfo(MolangUiActionPacket.ID, MolangUiActionPacket::decode, MolangUiActionHandler))
|
||||
list.add(PacketRegisterInfo(MolangUiClosedPacket.ID, MolangUiClosedPacket::decode, MolangUiClosedHandler))
|
||||
list.add(PacketRegisterInfo(MolangUiCompatibilityResponsePacket.ID, MolangUiCompatibilityResponsePacket::decode, MolangUiCompatibilityResponseHandler))
|
||||
|
||||
// Habitat blocks
|
||||
list.add(PacketRegisterInfo(SaveHabitatBlockSettingsPacket.ID, SaveHabitatBlockSettingsPacket::decode, SaveHabitatBlockSettingsHandler))
|
||||
|
||||
@@ -679,4 +674,4 @@ object CobblemonNetwork {
|
||||
fun sendPacketToPlayer(player: ServerPlayer, packet: NetworkPacket<*>) {
|
||||
Cobblemon.implementation.networkManager.sendPacketToPlayer(player, packet)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@
|
||||
package com.cobblemon.mod.common
|
||||
|
||||
import com.cobblemon.mod.common.entity.pokemon.ai.sensors.*
|
||||
import com.cobblemon.mod.common.pokemon.ai.PokemonDisturbancesSensor
|
||||
import com.cobblemon.mod.common.entity.sensor.BattlingPokemonSensor
|
||||
import com.cobblemon.mod.common.entity.sensor.NPCBattlingSensor
|
||||
import com.cobblemon.mod.common.pokemon.ai.PokemonDisturbancesSensor
|
||||
import java.util.function.Supplier
|
||||
import net.minecraft.world.entity.Entity
|
||||
import net.minecraft.world.entity.ai.sensing.Sensor
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
package com.cobblemon.mod.common
|
||||
|
||||
import java.util.Optional
|
||||
import net.minecraft.core.registries.BuiltInRegistries
|
||||
import net.minecraft.util.RandomSource
|
||||
import net.minecraft.world.entity.Entity
|
||||
@@ -18,7 +19,6 @@ import net.minecraft.world.item.ItemStack
|
||||
import net.minecraft.world.item.Items
|
||||
import net.minecraft.world.item.trading.ItemCost
|
||||
import net.minecraft.world.item.trading.MerchantOffer
|
||||
import java.util.Optional
|
||||
|
||||
/**
|
||||
* A generator for various trade offers in the mod.
|
||||
|
||||
+1
-1
@@ -11,10 +11,10 @@ package com.cobblemon.mod.common.advancement.criterion
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.mojang.serialization.Codec
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder
|
||||
import java.util.Optional
|
||||
import net.minecraft.advancements.critereon.ContextAwarePredicate
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import java.util.Optional
|
||||
|
||||
class AspectCriterion(
|
||||
playerCtx: Optional<ContextAwarePredicate>,
|
||||
|
||||
+1
-1
@@ -14,8 +14,8 @@ import com.mojang.serialization.codecs.RecordCodecBuilder
|
||||
import java.util.Optional
|
||||
import net.minecraft.advancements.critereon.ContextAwarePredicate
|
||||
import net.minecraft.advancements.critereon.EntityPredicate
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
class CastPokeRodContext(val baitId: ResourceLocation)
|
||||
|
||||
|
||||
+1
-1
@@ -10,10 +10,10 @@ package com.cobblemon.mod.common.advancement.criterion
|
||||
|
||||
import com.mojang.serialization.Codec
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder
|
||||
import java.util.Optional
|
||||
import net.minecraft.advancements.critereon.ContextAwarePredicate
|
||||
import net.minecraft.advancements.critereon.EntityPredicate
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import java.util.Optional
|
||||
|
||||
/**
|
||||
* A context that is used when you require a [CountableContext] along with some type string.
|
||||
|
||||
+1
-1
@@ -14,8 +14,8 @@ import com.mojang.serialization.codecs.RecordCodecBuilder
|
||||
import java.util.Optional
|
||||
import net.minecraft.advancements.critereon.ContextAwarePredicate
|
||||
import net.minecraft.advancements.critereon.EntityPredicate
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
class ReelInPokemonContext(val species : ResourceLocation, val baitId: ResourceLocation)
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
package com.cobblemon.mod.common.api.abilities
|
||||
|
||||
import com.cobblemon.mod.common.api.Priority
|
||||
import com.cobblemon.mod.common.api.data.ShowdownIdentifiable
|
||||
import com.cobblemon.mod.common.util.codec.CodecUtils
|
||||
import com.google.gson.JsonObject
|
||||
import com.mojang.serialization.Codec
|
||||
@@ -25,7 +26,7 @@ class AbilityTemplate(
|
||||
var builder: (AbilityTemplate, forced: Boolean, priority: Priority) -> Ability = { template, forced, priority -> Ability(template, forced, priority) },
|
||||
val displayName: String = "cobblemon.ability.$name",
|
||||
val description: String = "cobblemon.ability.$name.desc"
|
||||
) {
|
||||
) : ShowdownIdentifiable {
|
||||
/**
|
||||
* Returns the Ability or if applicable the extension connected to this template
|
||||
*/
|
||||
@@ -45,6 +46,8 @@ class AbilityTemplate(
|
||||
*/
|
||||
fun create(json: JsonObject) = create().loadFromJSON(json)
|
||||
|
||||
override fun showdownId(): String = ShowdownIdentifiable.REGEX.replace(this.name.lowercase(), "")
|
||||
|
||||
companion object {
|
||||
|
||||
@JvmStatic
|
||||
|
||||
-1
@@ -18,7 +18,6 @@ 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
|
||||
|
||||
@@ -13,7 +13,6 @@ 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.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
|
||||
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
|
||||
import com.cobblemon.mod.common.util.asTranslated
|
||||
import com.cobblemon.mod.common.util.resolve
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
|
||||
@@ -13,7 +13,6 @@ 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
|
||||
|
||||
@@ -8,16 +8,12 @@
|
||||
|
||||
package com.cobblemon.mod.common.api.ai.config
|
||||
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
|
||||
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
|
||||
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
|
||||
import com.cobblemon.mod.common.util.asExpression
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.resolveBoolean
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
|
||||
|
||||
@@ -11,13 +11,8 @@ package com.cobblemon.mod.common.api.ai.config.task
|
||||
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.molang.ExpressionLike
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.util.asExpression
|
||||
import com.cobblemon.mod.common.util.asExpressionLike
|
||||
import com.cobblemon.mod.common.util.resolveBoolean
|
||||
import com.cobblemon.mod.common.util.weightedSelection
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import com.mojang.datafixers.util.Either
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.ai.behavior.BehaviorControl
|
||||
|
||||
-2
@@ -8,12 +8,10 @@
|
||||
|
||||
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.api.ai.BehaviourConfigurationContext
|
||||
import com.cobblemon.mod.common.api.ai.WrapperLivingEntityTask.Companion.wrapped
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
|
||||
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
|
||||
import com.cobblemon.mod.common.util.mainThreadRuntime
|
||||
import com.cobblemon.mod.common.util.resolveBoolean
|
||||
|
||||
-2
@@ -10,8 +10,6 @@ package com.cobblemon.mod.common.api.ai.config.task
|
||||
|
||||
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
|
||||
import com.cobblemon.mod.common.api.ai.asVariables
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.ai.behavior.BehaviorControl
|
||||
import net.minecraft.world.entity.ai.behavior.StopBeingAngryIfTargetDead
|
||||
|
||||
-2
@@ -9,9 +9,7 @@
|
||||
package com.cobblemon.mod.common.api.ai.config.task
|
||||
|
||||
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import net.minecraft.world.Difficulty
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
|
||||
import com.cobblemon.mod.common.entity.npc.ai.SwitchToBattleTask
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.ai.behavior.BehaviorControl
|
||||
import net.minecraft.world.entity.ai.memory.MemoryModuleType
|
||||
|
||||
class SwitchToNPCBattleTaskConfig : SingleTaskConfig {
|
||||
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) = emptyList<MoLangConfigVariable>()
|
||||
|
||||
-2
@@ -10,8 +10,6 @@ package com.cobblemon.mod.common.api.ai.config.task
|
||||
|
||||
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
|
||||
import com.cobblemon.mod.common.api.ai.asVariables
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.PathfinderMob
|
||||
import net.minecraft.world.entity.ai.behavior.BehaviorControl
|
||||
|
||||
-2
@@ -10,8 +10,6 @@ package com.cobblemon.mod.common.api.ai.config.task
|
||||
|
||||
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
|
||||
import com.cobblemon.mod.common.api.ai.asVariables
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.PathfinderMob
|
||||
import net.minecraft.world.entity.ai.behavior.BehaviorControl
|
||||
|
||||
-1
@@ -25,7 +25,6 @@ import net.minecraft.world.entity.ai.behavior.BehaviorControl
|
||||
import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder
|
||||
import net.minecraft.world.entity.ai.behavior.declarative.Trigger
|
||||
import net.minecraft.world.entity.ai.memory.MemoryModuleType
|
||||
import net.minecraft.world.entity.ai.memory.MemoryStatus
|
||||
import net.minecraft.world.entity.ai.sensing.SensorType
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -22,6 +22,7 @@ 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 kotlin.math.ceil
|
||||
import net.minecraft.core.BlockPos
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.PathfinderMob
|
||||
@@ -34,7 +35,6 @@ import net.minecraft.world.entity.ai.memory.MemoryModuleType
|
||||
import net.minecraft.world.level.material.Fluids
|
||||
import net.minecraft.world.level.pathfinder.PathType
|
||||
import net.minecraft.world.phys.Vec3
|
||||
import kotlin.math.ceil
|
||||
|
||||
class WaterWanderTaskConfig : SingleTaskConfig {
|
||||
val condition = booleanVariable(WANDER, "water_wanders", true).asExpressible()
|
||||
|
||||
+12
-11
@@ -54,9 +54,9 @@ import com.cobblemon.mod.common.net.messages.client.battle.BattleEndPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.battle.BattleMakeChoicePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.battle.BattleMessagePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.battle.BattleQueueRequestPacket
|
||||
import com.cobblemon.mod.common.pokemon.evolution.progress.DefeatEvolutionProgress
|
||||
import com.cobblemon.mod.common.pokemon.evolution.progress.LastBattleCriticalHitsEvolutionProgress
|
||||
import com.cobblemon.mod.common.pokemon.requirements.DefeatRequirement
|
||||
import com.cobblemon.mod.common.pokemon.transformation.progress.DefeatTransformationProgress
|
||||
import com.cobblemon.mod.common.pokemon.transformation.progress.LastBattleCriticalHitsTransformationProgress
|
||||
import com.cobblemon.mod.common.pokemon.transformation.requirements.DefeatRequirement
|
||||
import com.cobblemon.mod.common.util.battleLang
|
||||
import com.cobblemon.mod.common.util.getPlayer
|
||||
import com.cobblemon.mod.common.util.giveOrDropItemStack
|
||||
@@ -97,8 +97,8 @@ open class PokemonBattle(
|
||||
this.actors.forEach { actor ->
|
||||
actor.battle = this
|
||||
actor.pokemonList.forEach { battlePokemon ->
|
||||
battlePokemon.effectedPokemon.evolutionProxy.current().progress()
|
||||
.filterIsInstance<LastBattleCriticalHitsEvolutionProgress>()
|
||||
battlePokemon.effectedPokemon.requirementProgress
|
||||
.filterIsInstance<LastBattleCriticalHitsTransformationProgress>()
|
||||
.forEach { it.reset() }
|
||||
}
|
||||
}
|
||||
@@ -271,12 +271,13 @@ open class PokemonBattle(
|
||||
val facedFainted = opponentPokemon.facedOpponents.contains(faintedPokemon)
|
||||
val pokemon = opponentPokemon.effectedPokemon
|
||||
if (facedFainted) {
|
||||
pokemon.lockedEvolutions.forEach { evolution ->
|
||||
evolution.requirements.filterIsInstance<DefeatRequirement>().forEach { defeatRequirement ->
|
||||
if (defeatRequirement.target.matches(faintedPokemon.effectedPokemon)) {
|
||||
val progress = pokemon.evolutionProxy.current().progressFirstOrCreate({ it is DefeatEvolutionProgress && it.currentProgress().target == defeatRequirement.target }) { DefeatEvolutionProgress() }
|
||||
progress.updateProgress(DefeatEvolutionProgress.Progress(defeatRequirement.target, progress.currentProgress().amount + 1))
|
||||
}
|
||||
if (pokemon.hasMatchingRequirement<DefeatRequirement>({ it.target.matches(faintedPokemon.effectedPokemon) })) {
|
||||
val requiredPokemonProperties = pokemon.getRelevantRequirements<DefeatRequirement> { it.target.matches(faintedPokemon.effectedPokemon) }
|
||||
.map { it.target }
|
||||
.distinctBy { it.asString() }
|
||||
for (props in requiredPokemonProperties) {
|
||||
val progress = pokemon.progressFirstOrCreate({ it is DefeatTransformationProgress && it.currentProgress().target.asString().equals(props.asString(), ignoreCase = true) }, ::DefeatTransformationProgress)
|
||||
progress.updateProgress(DefeatTransformationProgress.Progress(props.copy(), progress.currentProgress().amount + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -22,9 +22,9 @@ import com.cobblemon.mod.common.item.battle.BagItem
|
||||
import com.cobblemon.mod.common.net.messages.client.battle.BattleApplyPassResponsePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.battle.BattleMakeChoicePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.battle.BattleMessagePacket
|
||||
import java.util.UUID
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.network.chat.MutableComponent
|
||||
import java.util.UUID
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
abstract class BattleActor(
|
||||
|
||||
@@ -21,6 +21,7 @@ import com.cobblemon.mod.common.util.adapters.*
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import java.awt.Color
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds
|
||||
import net.minecraft.core.registries.Registries
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
@@ -30,7 +31,6 @@ import net.minecraft.tags.TagKey
|
||||
import net.minecraft.world.level.biome.Biome
|
||||
import net.minecraft.world.phys.AABB
|
||||
import net.minecraft.world.phys.Vec3
|
||||
import java.awt.Color
|
||||
|
||||
/**
|
||||
* The data registry for [Berry].
|
||||
|
||||
@@ -26,10 +26,10 @@ import com.cobblemon.mod.common.util.writeBox
|
||||
import com.cobblemon.mod.common.util.writeEnumConstant
|
||||
import com.cobblemon.mod.common.util.writeIdentifier
|
||||
import com.google.gson.annotations.SerializedName
|
||||
import net.minecraft.core.BlockPos
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import java.awt.Color
|
||||
import java.util.EnumSet
|
||||
import net.minecraft.core.BlockPos
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.tags.TagKey
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
|
||||
package com.cobblemon.mod.common.api.drop
|
||||
|
||||
import com.cobblemon.mod.common.api.pokemon.requirement.Requirement
|
||||
import com.cobblemon.mod.common.api.pokemon.transformation.requirement.TransformationRequirement
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
|
||||
class EvolutionItemDropEntry : ItemDropEntry() {
|
||||
val requirements: MutableSet<Requirement> = mutableSetOf()
|
||||
val requirements: MutableSet<TransformationRequirement> = mutableSetOf()
|
||||
|
||||
override fun canDrop(pokemon: Pokemon?): Boolean = pokemon != null && requirements.all { it.check(pokemon) }
|
||||
}
|
||||
@@ -48,6 +48,10 @@ import com.cobblemon.mod.common.api.events.pokemon.evolution.EvolutionAcceptedEv
|
||||
import com.cobblemon.mod.common.api.events.pokemon.evolution.EvolutionCompleteEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.evolution.EvolutionDisplayEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.evolution.EvolutionTestedEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.form.FormAcceptedEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.form.FormCompleteEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.form.FormDisplayEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.form.FormTestedEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.healing.PokemonHealedEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.interaction.ExperienceCandyUseEvent
|
||||
import com.cobblemon.mod.common.api.events.pokemon.interaction.PokemonInteractionGUICreationEvent
|
||||
@@ -103,6 +107,18 @@ object CobblemonEvents {
|
||||
@JvmField
|
||||
val EVOLUTION_COMPLETE = EventObservable<EvolutionCompleteEvent>()
|
||||
|
||||
@JvmField
|
||||
val FORM_ACCEPTED = CancelableObservable<FormAcceptedEvent>()
|
||||
|
||||
@JvmField
|
||||
val FORM_DISPLAY = EventObservable<FormDisplayEvent>()
|
||||
|
||||
@JvmField
|
||||
val FORM_TESTED = EventObservable<FormTestedEvent>()
|
||||
|
||||
@JvmField
|
||||
val FORM_COMPLETE = EventObservable<FormCompleteEvent>()
|
||||
|
||||
@JvmField
|
||||
val POKEMON_NICKNAMED = CancelableObservable<PokemonNicknamedEvent>()
|
||||
|
||||
|
||||
-2
@@ -15,9 +15,7 @@ import com.cobblemon.mod.common.api.battles.model.actor.ActorType
|
||||
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
|
||||
import com.cobblemon.mod.common.api.battles.model.actor.EntityBackedBattleActor
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
|
||||
import com.cobblemon.mod.common.battles.actor.PlayerBattleActor
|
||||
import com.cobblemon.mod.common.entity.MoLangScriptingEntity
|
||||
import com.cobblemon.mod.common.entity.npc.NPCBattleActor
|
||||
import com.cobblemon.mod.common.util.asArrayValue
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.api.events.Cancelable
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.trade.TradeParticipant
|
||||
import com.cobblemon.mod.common.util.getPlayer
|
||||
|
||||
+1
-1
@@ -12,8 +12,8 @@ import com.bedrockk.molang.runtime.value.MoValue
|
||||
import com.cobblemon.mod.common.api.events.Cancelable
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.Evolution
|
||||
|
||||
/**
|
||||
* Fired when an evolution is accepted.
|
||||
|
||||
+1
-1
@@ -10,8 +10,8 @@ package com.cobblemon.mod.common.api.events.pokemon.evolution
|
||||
|
||||
import com.bedrockk.molang.runtime.value.MoValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.Evolution
|
||||
|
||||
/**
|
||||
* Fired after an evolution finishes.
|
||||
|
||||
+2
-2
@@ -8,9 +8,9 @@
|
||||
|
||||
package com.cobblemon.mod.common.api.events.pokemon.evolution
|
||||
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.EvolutionDisplay
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.EvolutionDisplay
|
||||
|
||||
/**
|
||||
* Fired before an evolution is sent to clients.
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
|
||||
package com.cobblemon.mod.common.api.events.pokemon.evolution
|
||||
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -12,8 +12,8 @@ import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.MoValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.Evolution
|
||||
import com.cobblemon.mod.common.util.getBoolean
|
||||
|
||||
/**
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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.events.pokemon.form
|
||||
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.api.events.Cancelable
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.form.TemporaryForm
|
||||
|
||||
/**
|
||||
* Fired when a temporary form change is accepted.
|
||||
* Cancelling will not notify users nor remove the form from the pending list.
|
||||
*
|
||||
* @param pokemon The [Pokemon] about to change form.
|
||||
* @param form The [TemporaryForm] being used.
|
||||
*
|
||||
* @author Hiroku
|
||||
* @since June 3rd, 2026
|
||||
*/
|
||||
data class FormAcceptedEvent(
|
||||
override val pokemon: Pokemon,
|
||||
override val form: TemporaryForm
|
||||
) : Cancelable(), FormEvent {
|
||||
val context = mutableMapOf(
|
||||
"pokemon" to pokemon.struct,
|
||||
"form" to StringValue(form.formOnlyShowdownId())
|
||||
)
|
||||
|
||||
val functions = moLangFunctionMap(cancelFunc)
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* 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.events.pokemon.form
|
||||
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.form.TemporaryForm
|
||||
|
||||
/**
|
||||
* Fired after a temporary form change finishes.
|
||||
*
|
||||
* @param pokemon The [Pokemon] resulting from the form change.
|
||||
* @param form The [TemporaryForm] that was used.
|
||||
*
|
||||
* @author Hiroku
|
||||
* @since June 3rd, 2026
|
||||
*/
|
||||
data class FormCompleteEvent(
|
||||
/** The [Pokemon] that did the form change. */
|
||||
override val pokemon: Pokemon,
|
||||
/** The [TemporaryForm] that was used. */
|
||||
override val form: TemporaryForm
|
||||
) : FormEvent {
|
||||
val context = mutableMapOf(
|
||||
"pokemon" to pokemon.struct,
|
||||
"form" to StringValue(form.formOnlyShowdownId())
|
||||
)
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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.events.pokemon.form
|
||||
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.form.FormDisplay
|
||||
import com.cobblemon.mod.common.pokemon.transformation.form.TemporaryForm
|
||||
|
||||
/**
|
||||
* Fired before a form is sent to clients. For modifications on the actual output when they accept it modify
|
||||
* the [display] directly.
|
||||
*
|
||||
* @param pokemon The [Pokemon] that will change form if this proposition is accepted.
|
||||
* @param display The current [FormDisplay] the client will see.
|
||||
* @param form The [TemporaryForm] being used.
|
||||
*
|
||||
* @author Hiroku
|
||||
* @since June 3rd, 2026
|
||||
*/
|
||||
data class FormDisplayEvent(
|
||||
override val pokemon: Pokemon,
|
||||
var display: FormDisplay,
|
||||
override val form: TemporaryForm
|
||||
) : FormEvent {
|
||||
val context = mutableMapOf(
|
||||
"pokemon" to pokemon.struct,
|
||||
"display" to display.struct,
|
||||
"form" to StringValue(form.formOnlyShowdownId())
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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.events.pokemon.form
|
||||
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.form.TemporaryForm
|
||||
|
||||
/**
|
||||
* The root of the various [TemporaryForm]-related events.
|
||||
*/
|
||||
interface FormEvent {
|
||||
/** The Pokémon impacted in this event.*/
|
||||
val pokemon: Pokemon
|
||||
/*** The form triggering this event.*/
|
||||
val form: TemporaryForm
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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.events.pokemon.form
|
||||
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.transformation.form.TemporaryForm
|
||||
import com.cobblemon.mod.common.util.getBoolean
|
||||
|
||||
/**
|
||||
* An event fired when [TemporaryForm.test] has been performed.
|
||||
* The final state [result] will be the return value of the test function.
|
||||
*
|
||||
* @property pokemon The [Pokemon] being tested against.
|
||||
* @property form The [TemporaryForm] instance performing the test.
|
||||
* @property originalResult The base result from the Cobblemon implementation.
|
||||
* @property result The final value returned by [TemporaryForm.test].
|
||||
*/
|
||||
data class FormTestedEvent(
|
||||
override val pokemon: Pokemon,
|
||||
override val form: TemporaryForm,
|
||||
val originalResult: Boolean,
|
||||
) : FormEvent {
|
||||
var result: Boolean = originalResult
|
||||
|
||||
val context = mutableMapOf(
|
||||
"pokemon" to pokemon.struct,
|
||||
"form" to StringValue(form.formOnlyShowdownId()),
|
||||
"original_result" to DoubleValue(originalResult),
|
||||
)
|
||||
|
||||
val functions = moLangFunctionMap(
|
||||
"result" to { DoubleValue(result) },
|
||||
"set_result" to {
|
||||
result = it.getBoolean(0)
|
||||
DoubleValue.ONE
|
||||
}
|
||||
)
|
||||
}
|
||||
-1
@@ -15,7 +15,6 @@ import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
|
||||
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.util.getPlayer
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
/**
|
||||
|
||||
-1
@@ -8,7 +8,6 @@
|
||||
|
||||
package com.cobblemon.mod.common.api.events.storage
|
||||
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.api.events.Cancelable
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
|
||||
-2
@@ -16,9 +16,7 @@ import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
|
||||
import com.cobblemon.mod.common.api.storage.PokemonStore
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.util.getPlayer
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* The base of the events around the release of Pokémon from pc or party.
|
||||
|
||||
@@ -14,7 +14,7 @@ import com.cobblemon.mod.common.api.data.JsonDataRegistry
|
||||
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
|
||||
import com.cobblemon.mod.common.api.reactive.SimpleObservable
|
||||
import com.cobblemon.mod.common.net.messages.client.data.FossilRegistrySyncPacket
|
||||
import com.cobblemon.mod.common.pokemon.evolution.adapters.LegacyItemConditionWrapperAdapter
|
||||
import com.cobblemon.mod.common.pokemon.transformation.adapters.LegacyItemConditionWrapperAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.ItemLikeConditionAdapter
|
||||
import com.cobblemon.mod.common.util.adapters.pokemonPropertiesShortAdapter
|
||||
|
||||
+5
-5
@@ -13,13 +13,13 @@ import com.cobblemon.mod.common.api.conditional.RegistryLikeCondition
|
||||
import com.cobblemon.mod.common.api.data.JsonDataRegistry
|
||||
import com.cobblemon.mod.common.api.molang.ExpressionLike
|
||||
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
|
||||
import com.cobblemon.mod.common.api.pokemon.requirement.Requirement
|
||||
import com.cobblemon.mod.common.api.pokemon.transformation.requirement.TransformationRequirement
|
||||
import com.cobblemon.mod.common.api.reactive.SimpleObservable
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.net.messages.client.data.PokemonInteractionsSyncPacket
|
||||
import com.cobblemon.mod.common.pokemon.adapters.CobblemonRequirementAdapter
|
||||
import com.cobblemon.mod.common.pokemon.evolution.adapters.LegacyItemConditionWrapperAdapter
|
||||
import com.cobblemon.mod.common.pokemon.requirements.PokemonPropertiesRequirement
|
||||
import com.cobblemon.mod.common.pokemon.transformation.adapters.CobblemonRequirementAdapter
|
||||
import com.cobblemon.mod.common.pokemon.transformation.adapters.LegacyItemConditionWrapperAdapter
|
||||
import com.cobblemon.mod.common.pokemon.transformation.requirements.PokemonPropertiesRequirement
|
||||
import com.cobblemon.mod.common.util.adapters.*
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.google.gson.Gson
|
||||
@@ -46,7 +46,7 @@ object PokemonInteractions : JsonDataRegistry<PokemonInteractionSet> {
|
||||
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
|
||||
.registerTypeAdapter(PokemonProperties::class.java, pokemonPropertiesShortAdapter)
|
||||
.registerTypeAdapter(ItemPredicate::class.java, LegacyItemConditionWrapperAdapter)
|
||||
.registerTypeAdapter(Requirement::class.java, CobblemonRequirementAdapter)
|
||||
.registerTypeAdapter(TransformationRequirement::class.java, CobblemonRequirementAdapter)
|
||||
.registerTypeAdapter(InteractionEffect::class.java, InteractionEffectAdapter)
|
||||
.registerTypeAdapter(ExpressionLike::class.java, ExpressionLikeAdapter)
|
||||
.registerTypeAdapter(TypeToken.getParameterized(RegistryLikeCondition::class.java, Biome::class.java).type, BiomeLikeConditionAdapter)
|
||||
|
||||
+10
-5
@@ -12,11 +12,16 @@ import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import com.cobblemon.mod.common.api.molang.ExpressionLike
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
|
||||
import com.cobblemon.mod.common.api.pokemon.requirement.Requirement
|
||||
import com.cobblemon.mod.common.api.pokemon.transformation.requirement.TransformationRequirement
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.net.messages.client.sound.UnvalidatedPlaySoundS2CPacket
|
||||
import com.cobblemon.mod.common.pokemon.adapters.CobblemonRequirementAdapter
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import com.cobblemon.mod.common.pokemon.transformation.adapters.CobblemonRequirementAdapter
|
||||
import com.cobblemon.mod.common.util.asExpressionLike
|
||||
import com.cobblemon.mod.common.util.giveOrDropItemStack
|
||||
import com.cobblemon.mod.common.util.readExpressionLike
|
||||
import com.cobblemon.mod.common.util.withPlayerValue
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import com.cobblemon.mod.common.util.writeExpressionLike
|
||||
import com.google.gson.annotations.SerializedName
|
||||
import net.minecraft.core.registries.Registries
|
||||
import net.minecraft.network.FriendlyByteBuf
|
||||
@@ -29,7 +34,7 @@ import net.minecraft.world.entity.item.ItemEntity
|
||||
import net.minecraft.world.item.ItemStack
|
||||
|
||||
data class PokemonInteractionSet(
|
||||
val requirements: List<Requirement> = listOf(),
|
||||
val requirements: List<TransformationRequirement> = listOf(),
|
||||
val interactions: List<PokemonInteraction> = listOf(),
|
||||
) {
|
||||
fun encode(buffer: FriendlyByteBuf) {
|
||||
@@ -51,7 +56,7 @@ data class PokemonInteractionSet(
|
||||
}
|
||||
|
||||
data class PokemonInteraction(
|
||||
val requirements: List<Requirement> = listOf(),
|
||||
val requirements: List<TransformationRequirement> = listOf(),
|
||||
val effects: List<InteractionEffect> = listOf(),
|
||||
val cooldown: ExpressionLike = "0".asExpressionLike()
|
||||
) {
|
||||
|
||||
@@ -74,7 +74,7 @@ abstract class RequestManager<T : ServerPlayerActionRequest> {
|
||||
?: this.getInboundRequest(receiver.uuid, requestID)
|
||||
|
||||
/** Determines whether [player] can receive a [T]. */
|
||||
open fun isBusy(player: ServerPlayer): Boolean = player.isInBattle() || player.isTrading() || player.party().find { it.entity?.isBusy == true } != null
|
||||
open fun isBusy(player: ServerPlayer): Boolean = player.isBusy() || player.isPartyBusy()
|
||||
|
||||
/** Determines if the [target] is a valid interaction request target. */
|
||||
abstract fun isValidInteraction(player: ServerPlayer, target: ServerPlayer): Boolean
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
package com.cobblemon.mod.common.api.item
|
||||
|
||||
import com.cobblemon.mod.common.api.data.DataRegistry
|
||||
import com.cobblemon.mod.common.api.data.ShowdownIdentifiable
|
||||
import com.cobblemon.mod.common.api.reactive.SimpleObservable
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.pokemon.helditem.CobblemonHeldItemManager
|
||||
@@ -29,9 +30,11 @@ object HeldItems : DataRegistry {
|
||||
// val heldItems = PrioritizedList<BagItemLike>()
|
||||
internal val heldItemsScripts = mutableMapOf<String, String>() // showdown item ID to JavaScript
|
||||
val showdownItems = hashSetOf<String>()
|
||||
val megaStones = hashMapOf<String, String>()
|
||||
|
||||
override fun reload(manager: ResourceManager) {
|
||||
heldItemsScripts.clear()
|
||||
megaStones.clear()
|
||||
ShowdownService.service.resetRegistryData("heldItem")
|
||||
manager.listResources("held_items") { it.path.endsWith(".js") }.forEach { (identifier, resource) ->
|
||||
resource.open().use { stream ->
|
||||
@@ -48,6 +51,9 @@ object HeldItems : DataRegistry {
|
||||
for (i in 0 until itemsJson.size()) {
|
||||
val jsItem = itemsJson[i].asJsonObject
|
||||
showdownItems += jsItem.get("id").asString
|
||||
if (jsItem.has("megaEvolves")) {
|
||||
megaStones[jsItem.get("id").asString] = ShowdownIdentifiable.REGEX.replace(jsItem.get("megaEvolves").asString.lowercase(), "")
|
||||
}
|
||||
}
|
||||
|
||||
CobblemonHeldItemManager.load()
|
||||
|
||||
@@ -21,34 +21,9 @@ import com.cobblemon.mod.common.api.battles.interpreter.BattleMessage
|
||||
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
|
||||
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
|
||||
import com.cobblemon.mod.common.api.drop.DropEntry
|
||||
import com.cobblemon.mod.common.api.molang.function.BattleActorMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.BattleMessageMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.BattleMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.BiomeMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.BlockMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.DimensionTypeMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.DropEntryMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.EntityMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.EvolutionMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.GeneralMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.ItemStackMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.LivingEntityMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.NPCMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PCMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PartyMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PlayerMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PokedexMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PokemonEntityMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PokemonMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PokemonPropertiesMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.PokemonStoreMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.ServerMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.SpawnablePositionMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.SpeciesMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.WorldMoLangFunctions
|
||||
import com.cobblemon.mod.common.api.molang.function.*
|
||||
import com.cobblemon.mod.common.api.pokedex.AbstractPokedexManager
|
||||
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
|
||||
import com.cobblemon.mod.common.api.spawning.position.SpawnablePosition
|
||||
import com.cobblemon.mod.common.api.storage.PokemonStore
|
||||
@@ -58,8 +33,10 @@ import com.cobblemon.mod.common.entity.npc.NPCEntity
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.pokemon.Species
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.Evolution
|
||||
import com.cobblemon.mod.common.util.effectiveName
|
||||
import com.mojang.datafixers.util.Either
|
||||
import java.util.function.Function
|
||||
import net.minecraft.core.Holder
|
||||
import net.minecraft.core.Registry
|
||||
import net.minecraft.core.RegistryAccess
|
||||
@@ -84,7 +61,6 @@ import net.minecraft.world.level.biome.Biome
|
||||
import net.minecraft.world.level.block.Block
|
||||
import net.minecraft.world.level.dimension.DimensionType
|
||||
import net.minecraft.world.phys.Vec3
|
||||
import java.util.function.Function
|
||||
|
||||
/**
|
||||
* Holds a bunch of useful MoLang trickery that can be used or extended in API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
|
||||
import com.cobblemon.mod.common.util.asArrayValue
|
||||
import java.util.*
|
||||
import java.util.UUID
|
||||
|
||||
object BattleMoLangFunctions : AbstractMoLangFunctionHolder<PokemonBattle>() {
|
||||
override fun PokemonBattle.moLangFunctions(): MutableMap<String, (MoParams) -> Any> {
|
||||
|
||||
+20
-17
@@ -11,31 +11,34 @@ package com.cobblemon.mod.common.api.molang.function
|
||||
import com.bedrockk.molang.runtime.MoParams
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.evolution.variants.ItemInteractionEvolution
|
||||
import com.cobblemon.mod.common.pokemon.evolution.variants.LevelUpEvolution
|
||||
import com.cobblemon.mod.common.pokemon.evolution.variants.TradeEvolution
|
||||
import com.cobblemon.mod.common.api.pokemon.transformation.Transformation
|
||||
import com.cobblemon.mod.common.pokemon.transformation.evolution.Evolution
|
||||
import com.cobblemon.mod.common.pokemon.transformation.triggers.ItemInteractionTrigger
|
||||
import com.cobblemon.mod.common.pokemon.transformation.triggers.LevelUpTrigger
|
||||
import com.cobblemon.mod.common.pokemon.transformation.triggers.TradeTrigger
|
||||
|
||||
object EvolutionMoLangFunctions : AbstractMoLangFunctionHolder<Evolution>() {
|
||||
override fun Evolution.moLangFunctions(): MutableMap<String, (MoParams) -> Any> {
|
||||
object EvolutionMoLangFunctions : AbstractMoLangFunctionHolder<Transformation>() {
|
||||
override fun Transformation.moLangFunctions(): MutableMap<String, (MoParams) -> Any> {
|
||||
val evolution = this
|
||||
val functions = hashMapOf<String, (MoParams) -> Any>()
|
||||
|
||||
functions["result"] = { evolution.result.asMoLangValue() }
|
||||
functions["reevaluate"] = { DoubleValue(evolution.reevaluate) }
|
||||
functions["is_optional"] = { DoubleValue(evolution.optional) }
|
||||
functions["consumes_held_item"] = { DoubleValue(evolution.consumeHeldItem) }
|
||||
|
||||
when (evolution) {
|
||||
is LevelUpEvolution -> {
|
||||
functions["is_level_up"] = { DoubleValue.ONE }
|
||||
}
|
||||
if (evolution is Evolution) {
|
||||
functions["result"] = { evolution.result.asMoLangValue() }
|
||||
when (evolution.trigger) {
|
||||
is LevelUpTrigger -> {
|
||||
functions["is_level_up"] = { DoubleValue.ONE }
|
||||
}
|
||||
|
||||
is TradeEvolution -> {
|
||||
functions["is_trade"] = { DoubleValue.ONE }
|
||||
}
|
||||
is TradeTrigger -> {
|
||||
functions["is_trade"] = { DoubleValue.ONE }
|
||||
}
|
||||
|
||||
is ItemInteractionEvolution -> {
|
||||
functions["is_item"] = { DoubleValue.ONE }
|
||||
is ItemInteractionTrigger -> {
|
||||
functions["is_item"] = { DoubleValue.ONE }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-5
@@ -45,11 +45,6 @@ object GeneralMoLangFunctions {
|
||||
val functions: MutableMap<String, (MoParams) -> Any> = mutableMapOf()
|
||||
|
||||
init {
|
||||
functions["format"] = { params ->
|
||||
val value = params.get<MoValue>(0).asDouble()
|
||||
val decimals = params.get<MoValue>(1).asDouble().toInt().coerceIn(0, 10)
|
||||
StringValue(String.format("%.${decimals}f", value))
|
||||
}
|
||||
functions["print"] = { params ->
|
||||
val message = params.get<MoValue>(0).asString()
|
||||
LOGGER.info(message)
|
||||
|
||||
+1
-1
@@ -445,7 +445,7 @@ object PokemonMoLangFunctions : AbstractMoLangFunctionHolder<Pokemon>() {
|
||||
val idx = params.getInt(0)
|
||||
val evolution =
|
||||
if (idx >= 0) pokemon.evolutions.elementAtOrNull(idx) else return@forceEvolve DoubleValue.ZERO
|
||||
evolution?.forceEvolve(pokemon)
|
||||
evolution?.perform(pokemon)
|
||||
StringValue(evolution.toString())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +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.molangui
|
||||
|
||||
enum class GuiMode {
|
||||
OVERLAY,
|
||||
SCREEN;
|
||||
|
||||
companion object {
|
||||
fun fromString(value: String): GuiMode? = entries.firstOrNull { it.name.equals(value, ignoreCase = true) }
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +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.molangui
|
||||
|
||||
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
object MolangUiActionRegistry {
|
||||
private val handlers = ConcurrentHashMap<ActionKey, MolangUiActionHandler>()
|
||||
|
||||
fun register(key: ActionKey, handler: MolangUiActionHandler) {
|
||||
check(handlers.putIfAbsent(key, handler) == null) { "Molang UI action '$key' is already registered" }
|
||||
}
|
||||
|
||||
fun unregister(key: ActionKey): Boolean = handlers.remove(key) != null
|
||||
|
||||
internal fun dispatch(
|
||||
session: MolangUiSession,
|
||||
action: ActionKey,
|
||||
parameters: Map<String, ParameterValue>
|
||||
) {
|
||||
val definition = session.contract.actions[action]
|
||||
?: throw IllegalArgumentException("undeclared action '${action.value}'")
|
||||
val registered = handlers[action]
|
||||
if (registered != null) {
|
||||
registered.handle(MolangUiActionContext(session, session.player, parameters))
|
||||
return
|
||||
}
|
||||
val scriptId = definition.handler
|
||||
?: throw IllegalStateException("action '${action.value}' has no registered handler")
|
||||
val script = CobblemonScripts.scripts[scriptId]
|
||||
?: throw IllegalStateException("Molang UI action script '$scriptId' was not loaded")
|
||||
val runtime = MolangUiServerRuntimeFactory.create(session)
|
||||
parameters.forEach { (name, value) -> runtime.environment.setSimpleVariable(name, value.asMoLangValue()) }
|
||||
script.resolve(runtime, emptyMap())
|
||||
}
|
||||
|
||||
internal fun executeOnOpen(session: MolangUiSession) {
|
||||
val scriptId = session.contract.onOpen ?: return
|
||||
val script = CobblemonScripts.scripts[scriptId]
|
||||
?: throw IllegalStateException("Molang UI on_open script '$scriptId' was not loaded")
|
||||
script.resolve(MolangUiServerRuntimeFactory.create(session), emptyMap())
|
||||
}
|
||||
}
|
||||
-201
@@ -1,201 +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.molangui
|
||||
|
||||
import com.google.gson.JsonArray
|
||||
import com.cobblemon.mod.common.api.data.DataRegistry
|
||||
import com.cobblemon.mod.common.api.molangui.container.CollectionConfig
|
||||
import com.cobblemon.mod.common.api.molangui.container.CollectionSource
|
||||
import com.cobblemon.mod.common.api.molangui.container.CloseItemsPolicy
|
||||
import com.cobblemon.mod.common.api.molangui.container.ItemFilterEntry
|
||||
import com.cobblemon.mod.common.api.molangui.container.ShiftClickRule
|
||||
import com.cobblemon.mod.common.api.molangui.container.SlotLayout
|
||||
import com.cobblemon.mod.common.api.reactive.SimpleObservable
|
||||
import com.cobblemon.mod.common.net.messages.client.molangui.MolangUiCompatibilityRequestPacket
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.google.gson.JsonElement
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.core.registries.BuiltInRegistries
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.server.packs.PackType
|
||||
import net.minecraft.server.packs.resources.ResourceManager
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
object MolangUiContractRegistry : DataRegistry {
|
||||
override val id = cobblemonResource("molang_ui_contracts")
|
||||
override val type = PackType.SERVER_DATA
|
||||
override val observable = SimpleObservable<MolangUiContractRegistry>()
|
||||
private val contracts = linkedMapOf<ResourceLocation, MolangUiContract>()
|
||||
private val parseFailures = AtomicLong()
|
||||
private const val DIRECTORY = "molang_ui"
|
||||
|
||||
override fun reload(manager: ResourceManager) {
|
||||
val next = linkedMapOf<ResourceLocation, MolangUiContract>()
|
||||
manager.listResources(DIRECTORY) { it.path.endsWith(".json") }.forEach { (location, resource) ->
|
||||
val id = ResourceLocation.fromNamespaceAndPath(
|
||||
location.namespace,
|
||||
location.path.removePrefix("$DIRECTORY/").removeSuffix(".json")
|
||||
)
|
||||
try {
|
||||
val json = resource.openAsReader().use { JsonParser.parseReader(it).asJsonObject }
|
||||
next[id] = parse(id, json)
|
||||
} catch (error: Exception) {
|
||||
parseFailures.incrementAndGet()
|
||||
Cobblemon.LOGGER.error("Rejected Molang UI contract '$location': ${error.message}")
|
||||
}
|
||||
}
|
||||
require(next.size <= MolangUiPacketLimits.MAX_CONTRACTS) {
|
||||
"Molang UI contract count exceeds ${MolangUiPacketLimits.MAX_CONTRACTS}"
|
||||
}
|
||||
contracts.clear()
|
||||
contracts.putAll(next)
|
||||
Cobblemon.LOGGER.info("Loaded ${contracts.size} validated Molang UI contracts")
|
||||
observable.emit(this)
|
||||
}
|
||||
|
||||
override fun sync(player: ServerPlayer) {
|
||||
MolangUiCompatibilityRequestPacket(versions()).sendToPlayer(player)
|
||||
}
|
||||
|
||||
internal fun parse(
|
||||
id: ResourceLocation,
|
||||
json: JsonObject,
|
||||
itemExists: (ResourceLocation) -> Boolean = BuiltInRegistries.ITEM::containsKey
|
||||
): MolangUiContract {
|
||||
require(!json.has("blocks_input")) { "blocks_input is unsupported; input handling is determined by mode" }
|
||||
val formatVersion = json.get("format_version").requireUiInt("format_version")
|
||||
require(formatVersion == MOLANG_UI_FORMAT_VERSION) { "unsupported format_version $formatVersion" }
|
||||
val contractVersion = json.get("contract_version").requireUiString("contract_version")
|
||||
MolangUiPacketLimits.requireIdentifier(contractVersion, "contract_version")
|
||||
val mode = GuiMode.fromString(json.get("mode").requireUiString("mode"))
|
||||
?: throw IllegalArgumentException("unknown mode '${json.get("mode").asString}'")
|
||||
val parameters = parseParameters(json.getAsJsonObject("parameters"))
|
||||
val actions = parseActions(json.getAsJsonObject("actions"))
|
||||
val collections = parseCollections(json.getAsJsonObject("collections"), itemExists)
|
||||
val shiftRules = parseShiftRules(json.getAsJsonArray("shift_click_rules"), collections.keys)
|
||||
val closePolicy = json.get("on_close_items")?.requireUiString("on_close_items")?.let { raw ->
|
||||
CloseItemsPolicy.fromId(raw) ?: throw IllegalArgumentException("unknown on_close_items policy '$raw'")
|
||||
} ?: CloseItemsPolicy.RETURN
|
||||
return MolangUiContract(
|
||||
id, formatVersion, contractVersion, mode, parameters, actions,
|
||||
json.get("on_open")?.requireUiString("on_open")?.let { ResourceLocation.tryParse(it) ?: error("invalid on_open script id") },
|
||||
collections, shiftRules, closePolicy,
|
||||
json.get("exclusive")?.requireUiBoolean("exclusive") ?: false
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseParameters(json: JsonObject?): Map<String, ParameterDefinition> {
|
||||
require((json?.size() ?: 0) <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "too many parameters" }
|
||||
return json?.entrySet()?.associate { (name, element) ->
|
||||
MolangUiParameters.requireName(name)
|
||||
val obj = element.asJsonObject
|
||||
val type = ParameterType.fromId(obj.get("type").requireUiString("parameters.$name.type"))
|
||||
?: throw IllegalArgumentException("unknown type for parameter '$name'")
|
||||
val default = obj.get("default")?.let { parseDefault(type, it, "parameters.$name.default") }
|
||||
name to ParameterDefinition(type, obj.get("required")?.requireUiBoolean("parameters.$name.required") ?: (default == null), default)
|
||||
}?.toMap() ?: emptyMap()
|
||||
}
|
||||
|
||||
private fun parseDefault(type: ParameterType, element: JsonElement, path: String): ParameterDefault {
|
||||
if (element.isJsonObject && element.asJsonObject.has("molang")) {
|
||||
require(element.asJsonObject.size() == 1) { "expression '$path' contains unknown fields" }
|
||||
return ParameterDefault.Molang(element.asJsonObject.get("molang").requireUiString("$path.molang"))
|
||||
}
|
||||
val value = when (type) {
|
||||
ParameterType.STRING -> ParameterValue.StringValue(element.requireUiString(path))
|
||||
ParameterType.NUMBER -> ParameterValue.NumberValue(element.requireUiNumber(path))
|
||||
ParameterType.BOOLEAN -> ParameterValue.BooleanValue(element.requireUiBoolean(path))
|
||||
ParameterType.VEC3 -> {
|
||||
require(element.isJsonArray && element.asJsonArray.size() == 3) { "'$path' must be a three-number array" }
|
||||
ParameterValue.Vec3Value(
|
||||
element.asJsonArray[0].requireUiNumber("$path[0]"),
|
||||
element.asJsonArray[1].requireUiNumber("$path[1]"),
|
||||
element.asJsonArray[2].requireUiNumber("$path[2]")
|
||||
)
|
||||
}
|
||||
}
|
||||
MolangUiPacketLimits.requireValue(value.asWireValue(), path)
|
||||
return ParameterDefault.Literal(value)
|
||||
}
|
||||
|
||||
private fun parseActions(json: JsonObject?): Map<ActionKey, ActionDefinition> {
|
||||
val result = json?.entrySet()?.associate { (name, element) ->
|
||||
val key = ActionKey(name)
|
||||
val obj = element.asJsonObject
|
||||
val handler = obj.get("handler")?.requireUiString("actions.$name.handler")?.let { ResourceLocation.tryParse(it) ?: error("invalid handler for action '$name'") }
|
||||
val params = obj.getAsJsonObject("parameters")?.entrySet()?.associate { (paramName, typeElement) ->
|
||||
MolangUiPacketLimits.requireIdentifier(paramName, "action parameter name")
|
||||
paramName to (ParameterType.fromId(typeElement.requireUiString("actions.$name.parameters.$paramName"))
|
||||
?: throw IllegalArgumentException("unknown type for action parameter '$name.$paramName'"))
|
||||
}?.toMap() ?: emptyMap()
|
||||
require(params.size <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "action '$name' has too many parameters" }
|
||||
key to ActionDefinition(handler, params)
|
||||
}?.toMap() ?: emptyMap()
|
||||
require(result.size <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "contract has too many actions" }
|
||||
return result
|
||||
}
|
||||
|
||||
private fun parseCollections(
|
||||
json: JsonObject?,
|
||||
itemExists: (ResourceLocation) -> Boolean
|
||||
): Map<String, CollectionConfig> {
|
||||
require((json?.size() ?: 0) <= MolangUiPacketLimits.MAX_CONTRACTS) { "too many container collections" }
|
||||
return json?.entrySet()?.associate { (name, element) ->
|
||||
MolangUiPacketLimits.requireIdentifier(name, "collection name")
|
||||
val obj = element.asJsonObject
|
||||
val source = CollectionSource.fromId(obj.get("source")?.requireUiString("collections.$name.source") ?: "session")
|
||||
?: throw IllegalArgumentException("unknown source for collection '$name'")
|
||||
val filters = obj.getAsJsonArray("allowed_items")?.map { raw ->
|
||||
val filter = ItemFilterEntry.parse(raw.requireUiString("collections.$name.allowed_items"))
|
||||
?: throw IllegalArgumentException("invalid item filter '${raw.asString}' in '$name'")
|
||||
if (filter is ItemFilterEntry.Item) require(itemExists(filter.id)) {
|
||||
"unknown item '${filter.id}' in collection '$name'"
|
||||
}
|
||||
filter
|
||||
}?.toList() ?: emptyList()
|
||||
val layoutObj = obj.getAsJsonObject("layout") ?: throw IllegalArgumentException("collection '$name' is missing layout")
|
||||
val offset = layoutObj.pair("offset", 0, 0)
|
||||
val grid = layoutObj.pair("grid_dimensions", 1, 1)
|
||||
val slotSize = layoutObj.pair("slot_size", 18, 18)
|
||||
val spacing = layoutObj.pair("slot_spacing", 0, 0)
|
||||
val layout = SlotLayout(offset.first, offset.second, grid.first, grid.second, slotSize.first, slotSize.second, spacing.first, spacing.second)
|
||||
name to CollectionConfig(
|
||||
obj.get("size").requireUiInt("collections.$name.size"), filters,
|
||||
obj.get("take_only")?.requireUiBoolean("collections.$name.take_only") ?: false, source,
|
||||
obj.getAsJsonArray("slots")?.map { it.requireUiInt("collections.$name.slots") }?.toList(), layout
|
||||
)
|
||||
}?.toMap() ?: emptyMap()
|
||||
}
|
||||
|
||||
private fun parseShiftRules(array: JsonArray?, collections: Set<String>): List<ShiftClickRule> =
|
||||
array?.map { element ->
|
||||
val obj = element.asJsonObject
|
||||
val from = obj.stringList("from")
|
||||
val to = obj.stringList("to")
|
||||
val valid = collections + ShiftClickRule.PLAYER_SIDE_NAMES
|
||||
require(from.isNotEmpty() && to.isNotEmpty() && (from + to).all { it in valid }) { "shift-click rule references an unknown collection" }
|
||||
ShiftClickRule(from, to)
|
||||
}?.toList() ?: emptyList()
|
||||
|
||||
fun getContract(id: ResourceLocation): MolangUiContract? = contracts[id]
|
||||
fun getAllContracts(): Map<ResourceLocation, MolangUiContract> = contracts.toMap()
|
||||
fun versions(): Map<ResourceLocation, String> = contracts.mapValues { it.value.contractVersion }
|
||||
fun parseFailureCount(): Long = parseFailures.get()
|
||||
}
|
||||
|
||||
private fun JsonObject.pair(name: String, first: Int, second: Int): Pair<Int, Int> {
|
||||
val value = getAsJsonArray(name) ?: return first to second
|
||||
require(value.size() == 2) { "'$name' must have two entries" }
|
||||
return value[0].requireUiInt(name) to value[1].requireUiInt(name)
|
||||
}
|
||||
private fun JsonObject.stringList(name: String): List<String> = getAsJsonArray(name)?.map { it.requireUiString(name) }?.toList()
|
||||
?: throw IllegalArgumentException("missing array '$name'")
|
||||
@@ -1,24 +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.molangui
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetDefinition
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
|
||||
data class MolangUiDefinition(
|
||||
val guiId: ResourceLocation,
|
||||
val formatVersion: Int,
|
||||
val contractVersion: String,
|
||||
val mode: GuiMode,
|
||||
val parameters: Map<String, ParameterType>,
|
||||
val actions: Set<ActionKey>,
|
||||
val exclusive: Boolean,
|
||||
val root: WidgetDefinition,
|
||||
val variables: Map<String, Double>
|
||||
)
|
||||
@@ -1,26 +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.molangui
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
object MolangUiDiagnostics {
|
||||
private val activeSessions = AtomicLong()
|
||||
private val rejectedActions = AtomicLong()
|
||||
private val compatibilityFailures = AtomicLong()
|
||||
|
||||
internal fun sessionOpened() { activeSessions.incrementAndGet() }
|
||||
internal fun sessionClosed() { activeSessions.updateAndGet { value -> (value - 1).coerceAtLeast(0) } }
|
||||
internal fun actionRejected() { rejectedActions.incrementAndGet() }
|
||||
internal fun compatibilityFailures(count: Long) { compatibilityFailures.addAndGet(count) }
|
||||
|
||||
fun snapshot() = Snapshot(activeSessions.get(), rejectedActions.get(), compatibilityFailures.get(), MolangUiContractRegistry.parseFailureCount())
|
||||
|
||||
data class Snapshot(val activeSessions: Long, val rejectedActions: Long, val compatibilityFailures: Long, val parseFailures: Long)
|
||||
}
|
||||
@@ -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.molangui
|
||||
|
||||
import com.google.gson.JsonElement
|
||||
|
||||
internal fun JsonElement?.requireUiString(path: String): String {
|
||||
require(this != null && isJsonPrimitive && asJsonPrimitive.isString) { "'$path' must be a string" }
|
||||
return asString
|
||||
}
|
||||
|
||||
internal fun JsonElement?.requireUiBoolean(path: String): Boolean {
|
||||
require(this != null && isJsonPrimitive && asJsonPrimitive.isBoolean) { "'$path' must be a boolean" }
|
||||
return asBoolean
|
||||
}
|
||||
|
||||
internal fun JsonElement?.requireUiNumber(path: String): Double {
|
||||
require(this != null && isJsonPrimitive && asJsonPrimitive.isNumber) { "'$path' must be a number" }
|
||||
return asDouble.also { require(it.isFinite()) { "'$path' must be finite" } }
|
||||
}
|
||||
|
||||
internal fun JsonElement?.requireUiInt(path: String): Int {
|
||||
require(this != null && isJsonPrimitive && asJsonPrimitive.isNumber) { "'$path' must be an integer" }
|
||||
return try {
|
||||
asBigDecimal.intValueExact()
|
||||
} catch (error: ArithmeticException) {
|
||||
throw IllegalArgumentException("'$path' must be an integer in the 32-bit range", error)
|
||||
}
|
||||
}
|
||||
@@ -1,151 +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.molangui
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.container.SlotLayout
|
||||
import com.cobblemon.mod.common.api.molangui.container.CollectionConfig
|
||||
import com.cobblemon.mod.common.api.molangui.container.CloseItemsPolicy
|
||||
import com.cobblemon.mod.common.api.molangui.container.ShiftClickRule
|
||||
import net.minecraft.core.BlockPos
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import java.util.UUID
|
||||
|
||||
const val MOLANG_UI_FORMAT_VERSION = 1
|
||||
|
||||
enum class ParameterType(val id: String) {
|
||||
STRING("string"),
|
||||
NUMBER("number"),
|
||||
BOOLEAN("boolean"),
|
||||
VEC3("vec3");
|
||||
|
||||
companion object {
|
||||
fun fromId(id: String): ParameterType? = entries.firstOrNull { it.id == id }
|
||||
}
|
||||
}
|
||||
|
||||
sealed interface ParameterValue {
|
||||
val type: ParameterType
|
||||
fun asWireValue(): String
|
||||
|
||||
data class StringValue(val value: String) : ParameterValue {
|
||||
override val type = ParameterType.STRING
|
||||
override fun asWireValue() = value
|
||||
}
|
||||
|
||||
data class NumberValue(val value: Double) : ParameterValue {
|
||||
init { require(value.isFinite()) { "number parameters must be finite" } }
|
||||
override val type = ParameterType.NUMBER
|
||||
override fun asWireValue() = value.toString()
|
||||
}
|
||||
|
||||
data class BooleanValue(val value: Boolean) : ParameterValue {
|
||||
override val type = ParameterType.BOOLEAN
|
||||
override fun asWireValue() = value.toString()
|
||||
}
|
||||
|
||||
data class Vec3Value(val x: Double, val y: Double, val z: Double) : ParameterValue {
|
||||
init { require(x.isFinite() && y.isFinite() && z.isFinite()) { "vec3 parameters must be finite" } }
|
||||
override val type = ParameterType.VEC3
|
||||
override fun asWireValue() = "$x,$y,$z"
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun parse(type: ParameterType, value: String): ParameterValue? = when (type) {
|
||||
ParameterType.STRING -> StringValue(value)
|
||||
ParameterType.NUMBER -> value.toDoubleOrNull()?.takeIf(Double::isFinite)?.let(::NumberValue)
|
||||
ParameterType.BOOLEAN -> value.toBooleanStrictOrNull()?.let(::BooleanValue)
|
||||
ParameterType.VEC3 -> value.split(',').takeIf { it.size == 3 }
|
||||
?.map { it.trim().toDoubleOrNull() }
|
||||
?.takeIf { it.all { part -> part != null && part.isFinite() } }
|
||||
?.let { Vec3Value(it[0]!!, it[1]!!, it[2]!!) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ParameterDefinition(
|
||||
val type: ParameterType,
|
||||
val required: Boolean = true,
|
||||
val default: ParameterDefault? = null
|
||||
)
|
||||
|
||||
sealed interface ParameterDefault {
|
||||
data class Literal(val value: ParameterValue) : ParameterDefault
|
||||
data class Molang(val expression: String) : ParameterDefault
|
||||
}
|
||||
|
||||
@JvmInline
|
||||
value class ActionKey(val value: String) {
|
||||
init { require(value.isNotBlank() && value.length <= MolangUiPacketLimits.MAX_IDENTIFIER_LENGTH) }
|
||||
}
|
||||
|
||||
data class ActionDefinition(
|
||||
val handler: ResourceLocation? = null,
|
||||
val parameters: Map<String, ParameterType> = emptyMap()
|
||||
)
|
||||
|
||||
data class MolangUiContract(
|
||||
val id: ResourceLocation,
|
||||
val formatVersion: Int,
|
||||
val contractVersion: String,
|
||||
val mode: GuiMode,
|
||||
val parameters: Map<String, ParameterDefinition>,
|
||||
val actions: Map<ActionKey, ActionDefinition>,
|
||||
val onOpen: ResourceLocation?,
|
||||
val collections: Map<String, CollectionConfig>,
|
||||
val shiftClickRules: List<ShiftClickRule>,
|
||||
val closeItemsPolicy: CloseItemsPolicy,
|
||||
val exclusive: Boolean
|
||||
) {
|
||||
init {
|
||||
require(mode == GuiMode.SCREEN || collections.isEmpty()) { "overlay views cannot have container collections" }
|
||||
SlotLayout.validateCollections(collections.mapValues { it.value.layout })
|
||||
}
|
||||
}
|
||||
|
||||
data class MolangUiOpenRequest(
|
||||
val uiId: ResourceLocation,
|
||||
val parameters: Map<String, ParameterValue> = emptyMap(),
|
||||
val blockPos: BlockPos? = null
|
||||
)
|
||||
|
||||
sealed interface MolangUiOpenResult {
|
||||
data class Opened(val session: MolangUiSessionHandle) : MolangUiOpenResult
|
||||
data class Rejected(val reason: RejectionReason, val detail: String) : MolangUiOpenResult
|
||||
}
|
||||
|
||||
enum class RejectionReason {
|
||||
UNKNOWN_UI,
|
||||
INCOMPATIBLE_CLIENT,
|
||||
INVALID_PARAMETERS,
|
||||
SESSION_LIMIT,
|
||||
INVALID_CONTAINER,
|
||||
INTERNAL_ERROR
|
||||
}
|
||||
|
||||
enum class SessionState { OPENING, ACTIVE, CLOSING, CLOSED }
|
||||
|
||||
interface MolangUiSessionHandle : AutoCloseable {
|
||||
val sessionId: UUID
|
||||
val uiId: ResourceLocation
|
||||
val state: SessionState
|
||||
fun updateParameters(parameters: Map<String, ParameterValue>): Boolean
|
||||
fun updateVariables(variables: Map<String, Double>): Boolean
|
||||
override fun close()
|
||||
}
|
||||
|
||||
data class MolangUiActionContext(
|
||||
val session: MolangUiSessionHandle,
|
||||
val player: ServerPlayer,
|
||||
val parameters: Map<String, ParameterValue>
|
||||
)
|
||||
|
||||
fun interface MolangUiActionHandler {
|
||||
fun handle(context: MolangUiActionContext)
|
||||
}
|
||||
@@ -1,29 +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.molangui
|
||||
|
||||
object MolangUiPacketLimits {
|
||||
const val MAX_CONTRACTS = 256
|
||||
const val MAX_ACTION_FIELDS = 32
|
||||
const val MAX_IDENTIFIER_LENGTH = 128
|
||||
const val MAX_VALUE_LENGTH = 4 * 1024
|
||||
const val MAX_PACKET_BYTES = 256 * 1024
|
||||
|
||||
fun requireIdentifier(value: String, label: String): String {
|
||||
require(value.isNotBlank() && value.length <= MAX_IDENTIFIER_LENGTH) {
|
||||
"$label must contain 1..$MAX_IDENTIFIER_LENGTH characters"
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
fun requireValue(value: String, label: String): String {
|
||||
require(value.length <= MAX_VALUE_LENGTH) { "$label exceeds $MAX_VALUE_LENGTH characters" }
|
||||
return value
|
||||
}
|
||||
}
|
||||
@@ -1,68 +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.molangui
|
||||
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.MoValue
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
|
||||
internal object MolangUiParameters {
|
||||
val GENERAL_FUNCTIONS = setOf("format", "to_string", "to_number", "to_int", "is_number", "is_int", "is_blank")
|
||||
private val reserved = GENERAL_FUNCTIONS + setOf(
|
||||
"gui_id", "gui_time", "delta", "screen_width", "screen_height", "mouse_x", "mouse_y", "item", "translate", "event"
|
||||
)
|
||||
private val namePattern = Regex("[a-z_][a-z0-9_]*")
|
||||
|
||||
fun requireName(name: String) {
|
||||
MolangUiPacketLimits.requireIdentifier(name, "parameter name")
|
||||
require(namePattern.matches(name) && name !in reserved) { "invalid or reserved parameter name '$name'" }
|
||||
}
|
||||
|
||||
fun decode(types: Map<String, ParameterType>, values: Map<String, String>): Map<String, ParameterValue> {
|
||||
require(values.size <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "too many parameters" }
|
||||
return values.mapValues { (name, raw) ->
|
||||
requireName(name)
|
||||
val type = types[name] ?: throw IllegalArgumentException("undeclared parameter '$name'")
|
||||
MolangUiPacketLimits.requireValue(raw, name)
|
||||
ParameterValue.parse(type, raw) ?: throw IllegalArgumentException("invalid ${type.id} parameter '$name'")
|
||||
}
|
||||
}
|
||||
|
||||
fun validate(values: Map<String, ParameterValue>) {
|
||||
require(values.size <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "too many parameters" }
|
||||
values.forEach { (name, value) ->
|
||||
requireName(name)
|
||||
MolangUiPacketLimits.requireValue(value.asWireValue(), name)
|
||||
}
|
||||
}
|
||||
|
||||
fun requireVariableName(name: String): String {
|
||||
MolangUiPacketLimits.requireIdentifier(name, "variable name")
|
||||
return name.removePrefix("v.").also {
|
||||
require(namePattern.matches(it)) { "invalid variable '$name'" }
|
||||
}
|
||||
}
|
||||
|
||||
fun validateVariables(values: Map<String, Double>) {
|
||||
val names = mutableSetOf<String>()
|
||||
values.forEach { (name, value) ->
|
||||
val canonical = requireVariableName(name)
|
||||
require(names.add(canonical) && value.isFinite()) {
|
||||
"invalid or duplicate variable '$name'"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun ParameterValue.asMoLangValue(): MoValue = when (this) {
|
||||
is ParameterValue.StringValue -> StringValue(value)
|
||||
is ParameterValue.NumberValue -> DoubleValue(value)
|
||||
is ParameterValue.BooleanValue -> DoubleValue(value)
|
||||
is ParameterValue.Vec3Value -> StringValue(asWireValue())
|
||||
}
|
||||
@@ -1,95 +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.molangui
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.api.molangui.template.TemplateLibraryRegistry
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetDefinition
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetTree
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.packs.resources.ResourceManager
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** Client asset registry. Server code must use [MolangUiContractRegistry]. */
|
||||
object MolangUiRegistry {
|
||||
private const val DIRECTORY = "molang_ui"
|
||||
private val definitions = linkedMapOf<ResourceLocation, MolangUiDefinition>()
|
||||
private val parseFailures = AtomicLong()
|
||||
|
||||
fun reload(manager: ResourceManager) {
|
||||
TemplateLibraryRegistry.reload(manager)
|
||||
val next = linkedMapOf<ResourceLocation, MolangUiDefinition>()
|
||||
manager.listResources(DIRECTORY) { it.path.endsWith(".json") && !it.path.contains("/templates/") }
|
||||
.forEach { (identifier, resource) ->
|
||||
val guiId = ResourceLocation.fromNamespaceAndPath(
|
||||
identifier.namespace,
|
||||
identifier.path.removePrefix("$DIRECTORY/").removeSuffix(".json")
|
||||
)
|
||||
try {
|
||||
val json = resource.openAsReader().use { JsonParser.parseReader(it).asJsonObject }
|
||||
next[guiId] = parse(guiId, json)
|
||||
} catch (error: Exception) {
|
||||
parseFailures.incrementAndGet()
|
||||
Cobblemon.LOGGER.error("Rejected Molang UI view '$identifier': ${error.message}")
|
||||
}
|
||||
}
|
||||
require(next.size <= MolangUiPacketLimits.MAX_CONTRACTS) { "too many Molang UI views" }
|
||||
definitions.clear()
|
||||
definitions.putAll(next)
|
||||
Cobblemon.LOGGER.info("Loaded ${definitions.size} validated Molang UI views")
|
||||
}
|
||||
|
||||
internal fun parse(guiId: ResourceLocation, json: JsonObject): MolangUiDefinition {
|
||||
require(!json.has("blocks_input")) { "blocks_input is unsupported; input handling is determined by mode" }
|
||||
val formatVersion = json.get("format_version").requireUiInt("format_version")
|
||||
require(formatVersion == MOLANG_UI_FORMAT_VERSION) { "unsupported format_version $formatVersion" }
|
||||
val contractVersion = json.get("contract_version").requireUiString("contract_version")
|
||||
MolangUiPacketLimits.requireIdentifier(contractVersion, "contract_version")
|
||||
val mode = GuiMode.fromString(json.get("mode").requireUiString("mode"))
|
||||
?: throw IllegalArgumentException("unknown mode '${json.get("mode").asString}'")
|
||||
val parameterJson = json.getAsJsonObject("parameters")
|
||||
require((parameterJson?.size() ?: 0) <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "too many parameters" }
|
||||
val parameters = parameterJson?.entrySet()?.associate { (name, value) ->
|
||||
MolangUiParameters.requireName(name)
|
||||
val type = ParameterType.fromId(value.requireUiString("parameters.$name"))
|
||||
?: throw IllegalArgumentException("unknown parameter type for '$name'")
|
||||
name to type
|
||||
}?.toMap() ?: emptyMap()
|
||||
val actions = json.getAsJsonArray("actions")?.map { ActionKey(it.requireUiString("actions")) }?.toSet() ?: emptySet()
|
||||
require(actions.size <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "too many declared actions" }
|
||||
val variables = json.getAsJsonObject("variables")?.entrySet()?.associate { (name, value) ->
|
||||
MolangUiPacketLimits.requireIdentifier(name, "variable name")
|
||||
name to value.requireUiNumber("variables.$name")
|
||||
}?.toMap() ?: emptyMap()
|
||||
MolangUiParameters.validateVariables(variables)
|
||||
require(!json.has("imports")) { "template imports are unsupported; use qualified template references" }
|
||||
val root = WidgetTree.parse(json)
|
||||
val referencedActions = linkedSetOf<ActionKey>().also { collectActions(root, it) }
|
||||
val undeclared = referencedActions - actions
|
||||
require(undeclared.isEmpty()) { "widgets reference undeclared actions: ${undeclared.joinToString { it.value }}" }
|
||||
return MolangUiDefinition(
|
||||
guiId, formatVersion, contractVersion, mode, parameters, actions,
|
||||
json.get("exclusive")?.requireUiBoolean("exclusive") ?: false,
|
||||
root, variables
|
||||
)
|
||||
}
|
||||
|
||||
private fun collectActions(node: WidgetDefinition, output: MutableSet<ActionKey>) {
|
||||
node.events.values.forEach { output += it.action }
|
||||
node.children.forEach { collectActions(it, output) }
|
||||
node.itemTemplate?.let { collectActions(it, output) }
|
||||
}
|
||||
|
||||
fun getDefinition(guiId: ResourceLocation): MolangUiDefinition? = definitions[guiId]
|
||||
fun getAllDefinitions(): Map<ResourceLocation, MolangUiDefinition> = definitions.toMap()
|
||||
fun getVersionMap(): Map<ResourceLocation, String> = definitions.mapValues { it.value.contractVersion }
|
||||
fun parseFailureCount(): Long = parseFailures.get()
|
||||
}
|
||||
-93
@@ -1,93 +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.molangui
|
||||
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.MoValue
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.api.molang.function.GeneralMoLangFunctions
|
||||
import net.minecraft.core.registries.BuiltInRegistries
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.world.item.Item
|
||||
import net.minecraft.world.item.ItemStack
|
||||
|
||||
/** Builds a server runtime with only UI-scoped capabilities. It never exposes q.player. */
|
||||
internal object MolangUiServerRuntimeFactory {
|
||||
fun create(session: MolangUiSession): MoLangRuntime = MoLangRuntime().also { runtime ->
|
||||
GeneralMoLangFunctions.functions.filterKeys { it in MolangUiParameters.GENERAL_FUNCTIONS }.forEach { (name, function) ->
|
||||
runtime.environment.query.addFunction(name) { function(it) }
|
||||
}
|
||||
runtime.environment.query.addFunction("parameter") { params ->
|
||||
session.getParameter(params.getString(0))?.asMoLangValue() ?: DoubleValue.ZERO
|
||||
}
|
||||
runtime.environment.query.addFunction("update_parameter") { params ->
|
||||
val name = params.getString(0)
|
||||
val raw = params.get<MoValue>(1).asString()
|
||||
val type = session.contract.parameters[name]?.type
|
||||
DoubleValue(type != null && ParameterValue.parse(type, raw)?.let { session.updateParameters(mapOf(name to it)) } == true)
|
||||
}
|
||||
runtime.environment.query.addFunction("update_variable") { params ->
|
||||
val value = params.getDouble(1)
|
||||
DoubleValue(value.isFinite() && session.updateVariables(mapOf(params.getString(0) to value)))
|
||||
}
|
||||
runtime.environment.query.addFunction("close_ui") {
|
||||
session.close()
|
||||
DoubleValue.ONE
|
||||
}
|
||||
runtime.environment.query.addFunction("count_item") { params ->
|
||||
val item = validatedItem(params.getString(0)) ?: return@addFunction DoubleValue.ZERO
|
||||
DoubleValue(session.player.inventory.items.filter { it.`is`(item) }.sumOf(ItemStack::getCount).toDouble())
|
||||
}
|
||||
runtime.environment.query.addFunction("remove_items") { params ->
|
||||
val item = validatedItem(params.getString(0)) ?: return@addFunction DoubleValue.ZERO
|
||||
val count = params.getDouble(1).asNonnegativeInt() ?: return@addFunction DoubleValue.ZERO
|
||||
DoubleValue(count > 0 && removeAtomically(session, item, count))
|
||||
}
|
||||
runtime.environment.query.addFunction("slot") { params ->
|
||||
val index = params.getDouble(1).asNonnegativeInt() ?: return@addFunction StringValue("")
|
||||
val stack = session.containerMenu?.getStack(params.getString(0), index)
|
||||
if (stack == null || stack.isEmpty) StringValue("") else StringValue(BuiltInRegistries.ITEM.getKey(stack.item).toString())
|
||||
}
|
||||
runtime.environment.query.addFunction("replace_slot") { params ->
|
||||
val itemId = params.getString(5)
|
||||
validatedItem(itemId) ?: return@addFunction DoubleValue.ZERO
|
||||
val inputIndex = params.getDouble(1).asNonnegativeInt() ?: return@addFunction DoubleValue.ZERO
|
||||
val consumeCount = params.getDouble(2).asNonnegativeInt() ?: return@addFunction DoubleValue.ZERO
|
||||
val outputIndex = params.getDouble(4).asNonnegativeInt() ?: return@addFunction DoubleValue.ZERO
|
||||
val outputCount = params.getDouble(6).asNonnegativeInt() ?: return@addFunction DoubleValue.ZERO
|
||||
val result = session.containerMenu?.replaceSlotAtomically(
|
||||
params.getString(0), inputIndex, consumeCount,
|
||||
params.getString(3), outputIndex, itemId, outputCount
|
||||
) ?: false
|
||||
DoubleValue(result)
|
||||
}
|
||||
}
|
||||
|
||||
private fun validatedItem(raw: String) = ResourceLocation.tryParse(raw)
|
||||
?.takeIf(BuiltInRegistries.ITEM::containsKey)
|
||||
?.let(BuiltInRegistries.ITEM::get)
|
||||
|
||||
private fun Double.asNonnegativeInt(): Int? =
|
||||
takeIf { it.isFinite() && it in 0.0..Int.MAX_VALUE.toDouble() && it % 1.0 == 0.0 }?.toInt()
|
||||
|
||||
private fun removeAtomically(session: MolangUiSession, item: Item, count: Int): Boolean {
|
||||
val stacks = session.player.inventory.items.filter { it.`is`(item) }
|
||||
if (stacks.sumOf(ItemStack::getCount) < count) return false
|
||||
var remaining = count
|
||||
stacks.forEach { stack ->
|
||||
if (remaining == 0) return@forEach
|
||||
val removed = minOf(stack.count, remaining)
|
||||
stack.shrink(removed)
|
||||
remaining -= removed
|
||||
}
|
||||
session.player.inventory.setChanged()
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1,317 +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.molangui
|
||||
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import net.minecraft.core.BlockPos
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.api.molangui.container.CollectionSource
|
||||
import com.cobblemon.mod.common.api.molangui.container.MolangContainerMenu
|
||||
import com.cobblemon.mod.common.api.molangui.container.ServerCollectionSetup
|
||||
import com.cobblemon.mod.common.net.messages.client.molangui.MolangUiClosePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.molangui.MolangUiOpenPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.molangui.MolangUiUpdatePacket
|
||||
import com.cobblemon.mod.common.util.asExpressionLike
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.world.Container
|
||||
import net.minecraft.world.MenuProvider
|
||||
import net.minecraft.world.SimpleContainer
|
||||
import net.minecraft.world.entity.player.Inventory
|
||||
import net.minecraft.world.entity.player.Player
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu
|
||||
import java.util.UUID
|
||||
|
||||
internal class MolangUiSession(
|
||||
override val sessionId: UUID,
|
||||
override val uiId: ResourceLocation,
|
||||
val player: ServerPlayer,
|
||||
val contract: MolangUiContract,
|
||||
initialParameters: Map<String, ParameterValue>,
|
||||
val blockPos: BlockPos?
|
||||
) : MolangUiSessionHandle {
|
||||
override var state: SessionState = SessionState.OPENING
|
||||
private set
|
||||
private val parameters = initialParameters.toMutableMap()
|
||||
internal var containerMenu: MolangContainerMenu? = null
|
||||
private var clientWasNotified = false
|
||||
|
||||
override fun updateParameters(parameters: Map<String, ParameterValue>): Boolean {
|
||||
assertServerThread()
|
||||
if (state != SessionState.ACTIVE || !validateParameterUpdate(parameters)) return false
|
||||
MolangUiUpdatePacket(sessionId, parameters.mapValues { it.value.asWireValue() }).sendToPlayer(player)
|
||||
this.parameters.putAll(parameters)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun updateVariables(variables: Map<String, Double>): Boolean {
|
||||
assertServerThread()
|
||||
if (state != SessionState.ACTIVE || variables.size > MolangUiPacketLimits.MAX_ACTION_FIELDS) return false
|
||||
try {
|
||||
MolangUiParameters.validateVariables(variables)
|
||||
} catch (error: IllegalArgumentException) {
|
||||
return false
|
||||
}
|
||||
MolangUiUpdatePacket(sessionId, emptyMap(), variables).sendToPlayer(player)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun close() = closeInternal(notifyClient = true, closeMenu = true)
|
||||
|
||||
internal fun closeFromClient() = closeInternal(notifyClient = false, closeMenu = true)
|
||||
internal fun closeFromMenu() = closeInternal(notifyClient = true, closeMenu = false)
|
||||
|
||||
internal fun activate() {
|
||||
assertServerThread()
|
||||
check(state == SessionState.OPENING)
|
||||
state = SessionState.ACTIVE
|
||||
}
|
||||
|
||||
internal fun notifyOpened(hasContainer: Boolean) {
|
||||
check(state == SessionState.OPENING)
|
||||
clientWasNotified = true
|
||||
MolangUiOpenPacket(
|
||||
sessionId, uiId, contract.contractVersion, contract.mode,
|
||||
parameters.mapValues { it.value.asWireValue() }, contract.exclusive,
|
||||
hasContainer, contract.collections.mapValues { it.value.layout }
|
||||
).sendToPlayer(player)
|
||||
}
|
||||
|
||||
internal fun getParameter(name: String): ParameterValue? = parameters[name]
|
||||
|
||||
private fun validateParameterUpdate(values: Map<String, ParameterValue>): Boolean =
|
||||
values.size <= MolangUiPacketLimits.MAX_ACTION_FIELDS && values.all { (name, value) ->
|
||||
contract.parameters[name]?.type == value.type && value.asWireValue().length <= MolangUiPacketLimits.MAX_VALUE_LENGTH
|
||||
}
|
||||
|
||||
private fun closeInternal(notifyClient: Boolean, closeMenu: Boolean) {
|
||||
assertServerThread()
|
||||
if (state == SessionState.CLOSING || state == SessionState.CLOSED) return
|
||||
state = SessionState.CLOSING
|
||||
val menu = containerMenu
|
||||
containerMenu = null
|
||||
try {
|
||||
cleanup("notify client") {
|
||||
if (notifyClient && clientWasNotified) MolangUiClosePacket(sessionId).sendToPlayer(player)
|
||||
}
|
||||
cleanup("close container") {
|
||||
if (closeMenu && menu != null && player.containerMenu === menu) player.closeContainer()
|
||||
}
|
||||
cleanup("release items") { menu?.releaseOwnedItemsOnce(player) }
|
||||
} finally {
|
||||
state = SessionState.CLOSED
|
||||
MolangUiService.remove(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun cleanup(operation: String, action: () -> Unit) {
|
||||
try {
|
||||
action()
|
||||
} catch (error: Exception) {
|
||||
Cobblemon.LOGGER.error("Failed to $operation while closing Molang UI session $sessionId", error)
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertServerThread() {
|
||||
check(player.server.isSameThread) { "Molang UI sessions are confined to the server thread" }
|
||||
}
|
||||
}
|
||||
|
||||
object MolangUiService {
|
||||
private const val MAX_OVERLAYS_PER_PLAYER = 8
|
||||
private val sessions = linkedMapOf<UUID, MolangUiSession>()
|
||||
private val disabled = mutableMapOf<UUID, Set<ResourceLocation>>()
|
||||
private val rateLimiters = mutableMapOf<UUID, MolangUiRateLimiter>()
|
||||
|
||||
fun open(player: ServerPlayer, request: MolangUiOpenRequest): MolangUiOpenResult {
|
||||
check(player.server.isSameThread) { "MolangUiService.open must run on the server thread" }
|
||||
val contract = MolangUiContractRegistry.getContract(request.uiId)
|
||||
?: return MolangUiOpenResult.Rejected(RejectionReason.UNKNOWN_UI, "Unknown Molang UI '${request.uiId}'")
|
||||
// Intentionally does not wait for the compatibility round-trip; the client re-validates on open.
|
||||
if (disabled[player.uuid]?.contains(request.uiId) == true) {
|
||||
return MolangUiOpenResult.Rejected(RejectionReason.INCOMPATIBLE_CLIENT, "Client view is missing or incompatible")
|
||||
}
|
||||
val parameters = resolveParameters(contract, request.parameters)
|
||||
?: return MolangUiOpenResult.Rejected(RejectionReason.INVALID_PARAMETERS, "Parameters do not match the contract")
|
||||
val playerSessions = sessions.values.filter { it.player.uuid == player.uuid && it.state != SessionState.CLOSED }
|
||||
if (contract.mode == GuiMode.OVERLAY && playerSessions.count { it.contract.mode == GuiMode.OVERLAY } >= MAX_OVERLAYS_PER_PLAYER) {
|
||||
return MolangUiOpenResult.Rejected(RejectionReason.SESSION_LIMIT, "At most $MAX_OVERLAYS_PER_PLAYER overlays may be active")
|
||||
}
|
||||
val collectionSetup = try {
|
||||
createCollections(player, contract, request.blockPos)
|
||||
?: return MolangUiOpenResult.Rejected(RejectionReason.INVALID_CONTAINER, "The bound block container is unavailable or invalid")
|
||||
} catch (error: Exception) {
|
||||
Cobblemon.LOGGER.error("Failed to prepare Molang UI '${request.uiId}'", error)
|
||||
return MolangUiOpenResult.Rejected(RejectionReason.INTERNAL_ERROR, error.message ?: "Unable to prepare UI")
|
||||
}
|
||||
val session = MolangUiSession(UUID.randomUUID(), request.uiId, player, contract, parameters, request.blockPos)
|
||||
sessions[session.sessionId] = session
|
||||
MolangUiDiagnostics.sessionOpened()
|
||||
return try {
|
||||
if (contract.mode == GuiMode.SCREEN) {
|
||||
playerSessions.filter { it.contract.mode == GuiMode.SCREEN }.forEach(MolangUiSession::close)
|
||||
}
|
||||
check(session.state == SessionState.OPENING) { "Molang UI closed while replacing its previous screen" }
|
||||
MolangUiActionRegistry.executeOnOpen(session)
|
||||
check(session.state == SessionState.OPENING) { "Molang UI closed during on_open" }
|
||||
val hasContainer = contract.collections.isNotEmpty()
|
||||
session.notifyOpened(hasContainer)
|
||||
check(session.state == SessionState.OPENING) { "Molang UI closed while notifying the client" }
|
||||
if (hasContainer) openContainer(session, collectionSetup)
|
||||
session.activate()
|
||||
MolangUiOpenResult.Opened(session)
|
||||
} catch (error: Exception) {
|
||||
Cobblemon.LOGGER.error("Failed to open Molang UI '${request.uiId}'", error)
|
||||
session.close()
|
||||
MolangUiOpenResult.Rejected(RejectionReason.INTERNAL_ERROR, error.message ?: "Unable to open UI")
|
||||
}
|
||||
}
|
||||
|
||||
fun handleAction(sessionId: UUID, player: ServerPlayer, actionRaw: String, raw: Map<String, String>) {
|
||||
check(player.server.isSameThread)
|
||||
val session = sessions[sessionId]
|
||||
if (session == null || session.player.uuid != player.uuid || session.state != SessionState.ACTIVE) {
|
||||
MolangUiDiagnostics.actionRejected()
|
||||
return
|
||||
}
|
||||
if (!rateLimiters.getOrPut(sessionId) { MolangUiRateLimiter() }.tryAcquire()) {
|
||||
MolangUiDiagnostics.actionRejected()
|
||||
return
|
||||
}
|
||||
val action = runCatching { ActionKey(actionRaw) }.getOrNull()
|
||||
val definition = action?.let(session.contract.actions::get)
|
||||
if (action == null || definition == null || raw.keys != definition.parameters.keys || raw.size > MolangUiPacketLimits.MAX_ACTION_FIELDS) {
|
||||
MolangUiDiagnostics.actionRejected()
|
||||
return
|
||||
}
|
||||
val typed = linkedMapOf<String, ParameterValue>()
|
||||
for ((name, type) in definition.parameters) {
|
||||
val value = raw[name]
|
||||
if (value == null || value.length > MolangUiPacketLimits.MAX_VALUE_LENGTH) {
|
||||
MolangUiDiagnostics.actionRejected(); return
|
||||
}
|
||||
typed[name] = ParameterValue.parse(type, value) ?: run { MolangUiDiagnostics.actionRejected(); return }
|
||||
}
|
||||
try {
|
||||
MolangUiActionRegistry.dispatch(session, action, typed)
|
||||
} catch (error: Exception) {
|
||||
MolangUiDiagnostics.actionRejected()
|
||||
Cobblemon.LOGGER.error("Molang UI action '${action.value}' failed in session $sessionId", error)
|
||||
}
|
||||
}
|
||||
|
||||
fun handleClosed(sessionId: UUID, player: ServerPlayer) {
|
||||
val session = sessions[sessionId] ?: return
|
||||
if (session.player.uuid == player.uuid) session.closeFromClient() else MolangUiDiagnostics.actionRejected()
|
||||
}
|
||||
|
||||
fun applyCompatibility(player: ServerPlayer, clientVersions: Map<ResourceLocation, String>) {
|
||||
val incompatible = MolangUiContractRegistry.versions().filter { (id, version) -> clientVersions[id] != version }.keys
|
||||
if (incompatible.isEmpty()) disabled.remove(player.uuid) else disabled[player.uuid] = incompatible
|
||||
MolangUiDiagnostics.compatibilityFailures(incompatible.size.toLong())
|
||||
sessions.values.filter { it.player.uuid == player.uuid && it.uiId in incompatible }.toList().forEach(MolangUiSession::close)
|
||||
}
|
||||
|
||||
fun requestCompatibility(player: ServerPlayer) = MolangUiContractRegistry.sync(player)
|
||||
|
||||
fun closeAllForPlayer(playerId: UUID) {
|
||||
sessions.values.filter { it.player.uuid == playerId }.toList().forEach(MolangUiSession::close)
|
||||
disabled.remove(playerId)
|
||||
}
|
||||
|
||||
fun closeAll() {
|
||||
sessions.values.toList().forEach(MolangUiSession::close)
|
||||
disabled.clear()
|
||||
}
|
||||
|
||||
fun getSession(sessionId: UUID): MolangUiSessionHandle? = sessions[sessionId]
|
||||
fun getSessionForPlayer(player: ServerPlayer, id: ResourceLocation): MolangUiSessionHandle? =
|
||||
sessions.values.firstOrNull { it.player.uuid == player.uuid && it.uiId == id && it.state == SessionState.ACTIVE }
|
||||
fun activeSessionCount(): Int = sessions.size
|
||||
|
||||
internal fun remove(sessionId: UUID) {
|
||||
if (sessions.remove(sessionId) != null) MolangUiDiagnostics.sessionClosed()
|
||||
rateLimiters.remove(sessionId)
|
||||
}
|
||||
|
||||
private fun resolveParameters(contract: MolangUiContract, supplied: Map<String, ParameterValue>): Map<String, ParameterValue>? {
|
||||
if (supplied.keys.any { it !in contract.parameters }) return null
|
||||
val values = linkedMapOf<String, ParameterValue>()
|
||||
for ((name, definition) in contract.parameters) {
|
||||
val suppliedValue = supplied[name]
|
||||
val value = suppliedValue ?: when (val default = definition.default) {
|
||||
is ParameterDefault.Literal -> default.value
|
||||
is ParameterDefault.Molang -> runCatching {
|
||||
val result = default.expression.asExpressionLike().resolveString(MoLangRuntime())
|
||||
ParameterValue.parse(definition.type, result)
|
||||
}.getOrNull()
|
||||
null -> null
|
||||
}
|
||||
if (value == null) {
|
||||
if (definition.required) return null else continue
|
||||
}
|
||||
if (value.type != definition.type || value.asWireValue().length > MolangUiPacketLimits.MAX_VALUE_LENGTH) return null
|
||||
values[name] = value
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
private fun createCollections(
|
||||
player: ServerPlayer,
|
||||
contract: MolangUiContract,
|
||||
blockPos: BlockPos?
|
||||
): List<ServerCollectionSetup>? {
|
||||
val setups = mutableListOf<ServerCollectionSetup>()
|
||||
for ((name, config) in contract.collections) {
|
||||
val container: Container = when (config.source) {
|
||||
CollectionSource.SESSION -> SimpleContainer(config.size)
|
||||
CollectionSource.BLOCK_ENTITY -> {
|
||||
val pos = blockPos ?: return null
|
||||
if (player.distanceToSqr(pos.x + .5, pos.y + .5, pos.z + .5) > 64.0 || !player.level().hasChunk(pos.x shr 4, pos.z shr 4)) return null
|
||||
val blockEntity = player.level().getBlockEntity(pos)
|
||||
if (blockEntity !is Container) return null
|
||||
if ((config.slots ?: (0 until config.size).toList()).any { it >= blockEntity.containerSize }) return null
|
||||
blockEntity
|
||||
}
|
||||
}
|
||||
setups += ServerCollectionSetup(name, config, container)
|
||||
}
|
||||
return setups
|
||||
}
|
||||
|
||||
private fun openContainer(session: MolangUiSession, setup: List<ServerCollectionSetup>) {
|
||||
val owned = setup.filter { it.config.source == CollectionSource.SESSION }.mapTo(mutableSetOf()) { it.name }
|
||||
val opened = session.player.openMenu(object : MenuProvider {
|
||||
override fun getDisplayName() = Component.empty()
|
||||
override fun createMenu(containerId: Int, inventory: Inventory, player: Player): AbstractContainerMenu =
|
||||
MolangContainerMenu(containerId, inventory).also { menu ->
|
||||
check(session.state == SessionState.OPENING) { "Molang UI closed before creating its container" }
|
||||
session.containerMenu = menu
|
||||
menu.initializeServer(
|
||||
setup, session.contract.shiftClickRules, owned, session.contract.closeItemsPolicy,
|
||||
owner = session.player, session = session, blockPos = session.blockPos
|
||||
)
|
||||
}
|
||||
})
|
||||
check(opened.isPresent) { "player rejected the Molang UI container menu" }
|
||||
}
|
||||
}
|
||||
|
||||
internal class MolangUiRateLimiter(private var lastNanos: Long = System.nanoTime()) {
|
||||
private var tokens = 40.0
|
||||
fun tryAcquire(now: Long = System.nanoTime()): Boolean {
|
||||
val elapsed = (now - lastNanos).coerceAtLeast(0) / 1_000_000_000.0
|
||||
tokens = minOf(40.0, tokens + elapsed * 20.0)
|
||||
lastNanos = now
|
||||
if (tokens < 1.0) return false
|
||||
tokens -= 1.0
|
||||
return true
|
||||
}
|
||||
}
|
||||
-94
@@ -1,94 +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.molangui.container
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries
|
||||
import net.minecraft.core.registries.Registries
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.tags.TagKey
|
||||
import net.minecraft.world.item.ItemStack
|
||||
|
||||
data class CollectionConfig(
|
||||
val size: Int,
|
||||
val allowedItems: List<ItemFilterEntry> = emptyList(),
|
||||
val takeOnly: Boolean = false,
|
||||
val source: CollectionSource = CollectionSource.SESSION,
|
||||
val slots: List<Int>? = null,
|
||||
val layout: SlotLayout
|
||||
) {
|
||||
init {
|
||||
require(size in 1..MAX_COLLECTION_SIZE) { "collection size must be in 1..$MAX_COLLECTION_SIZE" }
|
||||
require(layout.slotCount == size) { "collection size must match its grid dimensions" }
|
||||
require(slots == null || slots.size == size) { "block collection slot mapping must match collection size" }
|
||||
require(slots == null || slots.distinct().size == slots.size) { "block collection slot mapping contains duplicates" }
|
||||
require(slots == null || slots.all { it >= 0 }) { "block collection slot indices must be nonnegative" }
|
||||
require(source == CollectionSource.BLOCK_ENTITY || slots == null) { "slot mapping is only valid for block_entity sources" }
|
||||
}
|
||||
|
||||
fun isItemAllowed(stack: ItemStack): Boolean {
|
||||
return !takeOnly && matchesFilter(stack)
|
||||
}
|
||||
|
||||
fun matchesFilter(stack: ItemStack): Boolean {
|
||||
if (allowedItems.isEmpty()) return true
|
||||
return allowedItems.any { it.matches(stack) }
|
||||
}
|
||||
|
||||
companion object { const val MAX_COLLECTION_SIZE = 256 }
|
||||
}
|
||||
|
||||
enum class CollectionSource(val id: String) {
|
||||
SESSION("session"), BLOCK_ENTITY("block_entity");
|
||||
companion object { fun fromId(id: String) = entries.firstOrNull { it.id == id } }
|
||||
}
|
||||
|
||||
data class ShiftClickRule(
|
||||
val from: List<String>,
|
||||
val to: List<String>
|
||||
) {
|
||||
companion object {
|
||||
const val PLAYER_INVENTORY = "player_inventory"
|
||||
const val PLAYER_HOTBAR = "player_hotbar"
|
||||
val PLAYER_SIDE_NAMES = listOf(PLAYER_INVENTORY, PLAYER_HOTBAR)
|
||||
}
|
||||
}
|
||||
|
||||
sealed interface ItemFilterEntry {
|
||||
fun matches(stack: ItemStack): Boolean
|
||||
|
||||
data class Item(val id: ResourceLocation) : ItemFilterEntry {
|
||||
override fun matches(stack: ItemStack): Boolean {
|
||||
if (!BuiltInRegistries.ITEM.containsKey(id)) return false
|
||||
return stack.`is`(BuiltInRegistries.ITEM.get(id))
|
||||
}
|
||||
}
|
||||
|
||||
data class Tag(val id: ResourceLocation) : ItemFilterEntry {
|
||||
override fun matches(stack: ItemStack): Boolean = stack.`is`(TagKey.create(Registries.ITEM, id))
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun parse(value: String): ItemFilterEntry? {
|
||||
val trimmed = value.trim()
|
||||
val isTag = trimmed.startsWith('#')
|
||||
val id = ResourceLocation.tryParse(if (isTag) trimmed.substring(1) else trimmed) ?: return null
|
||||
return if (isTag) Tag(id) else Item(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum class CloseItemsPolicy(val id: String) {
|
||||
DROP("drop"),
|
||||
RETURN("return"),
|
||||
DESTROY("destroy");
|
||||
|
||||
companion object {
|
||||
fun fromId(id: String): CloseItemsPolicy? = entries.firstOrNull { it.id == id }
|
||||
}
|
||||
}
|
||||
-300
@@ -1,300 +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.molangui.container
|
||||
|
||||
import com.cobblemon.mod.common.CobblemonMenuType
|
||||
import com.cobblemon.mod.common.api.molangui.MolangUiSession
|
||||
import com.cobblemon.mod.common.api.molangui.SessionState
|
||||
import net.minecraft.core.BlockPos
|
||||
import net.minecraft.core.registries.BuiltInRegistries
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.world.Container
|
||||
import net.minecraft.world.SimpleContainer
|
||||
import net.minecraft.world.entity.player.Inventory
|
||||
import net.minecraft.world.entity.player.Player
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu
|
||||
import net.minecraft.world.inventory.Slot
|
||||
import net.minecraft.world.item.ItemStack
|
||||
|
||||
private data class CollectionSlotRange(
|
||||
val name: String,
|
||||
val startIndex: Int,
|
||||
val endIndex: Int
|
||||
)
|
||||
|
||||
class MolangContainerMenu(
|
||||
containerId: Int,
|
||||
private val playerInventory: Inventory
|
||||
) : AbstractContainerMenu(CobblemonMenuType.MOLANG_UI, containerId) {
|
||||
|
||||
private val collections: MutableMap<String, Container> = mutableMapOf()
|
||||
|
||||
private val collectionRanges: MutableList<CollectionSlotRange> = mutableListOf()
|
||||
private var playerInventoryStart: Int = 0
|
||||
private var playerHotbarStart: Int = 0
|
||||
private var playerHotbarEnd: Int = 0
|
||||
|
||||
private var shiftClickRules: List<ShiftClickRule> = emptyList()
|
||||
|
||||
private val collectionConfigs: MutableMap<String, CollectionConfig> = mutableMapOf()
|
||||
private val sessionOwnedCollections: MutableSet<String> = mutableSetOf()
|
||||
private var closeItemsPolicy: CloseItemsPolicy = CloseItemsPolicy.RETURN
|
||||
private var owner: ServerPlayer? = null
|
||||
private var owningSession: MolangUiSession? = null
|
||||
private var blockPos: BlockPos? = null
|
||||
private var originalBlockContainer: Container? = null
|
||||
private var ownedItemsReleased = false
|
||||
|
||||
internal fun initializeServer(
|
||||
collectionSetup: List<ServerCollectionSetup>,
|
||||
shiftClickRules: List<ShiftClickRule> = emptyList(),
|
||||
sessionOwned: Set<String> = emptySet(),
|
||||
closeItemsPolicy: CloseItemsPolicy = CloseItemsPolicy.RETURN,
|
||||
owner: ServerPlayer,
|
||||
session: MolangUiSession,
|
||||
blockPos: BlockPos? = null
|
||||
) {
|
||||
this.shiftClickRules = shiftClickRules
|
||||
this.sessionOwnedCollections.addAll(sessionOwned)
|
||||
this.closeItemsPolicy = closeItemsPolicy
|
||||
this.owner = owner
|
||||
this.owningSession = session
|
||||
this.blockPos = blockPos
|
||||
|
||||
for (setup in collectionSetup) {
|
||||
val (name, config, container) = setup
|
||||
collections[name] = container
|
||||
if (config.source == CollectionSource.BLOCK_ENTITY) originalBlockContainer = container
|
||||
collectionConfigs[name] = config
|
||||
|
||||
val startIndex = slots.size
|
||||
addCollectionSlots(name, config, container)
|
||||
val endIndex = slots.size
|
||||
collectionRanges.add(CollectionSlotRange(name, startIndex, endIndex))
|
||||
}
|
||||
|
||||
addPlayerSlots()
|
||||
}
|
||||
|
||||
fun initializeClient(
|
||||
collectionLayouts: Map<String, SlotLayout>
|
||||
) {
|
||||
SlotLayout.validateCollections(collectionLayouts)
|
||||
for ((name, layout) in collectionLayouts) {
|
||||
val config = CollectionConfig(size = layout.slotCount, layout = layout)
|
||||
val container = SimpleContainer(layout.slotCount)
|
||||
collections[name] = container
|
||||
collectionConfigs[name] = config
|
||||
|
||||
val startIndex = slots.size
|
||||
addCollectionSlots(name, config, container)
|
||||
val endIndex = slots.size
|
||||
collectionRanges.add(CollectionSlotRange(name, startIndex, endIndex))
|
||||
}
|
||||
|
||||
addPlayerSlots()
|
||||
}
|
||||
|
||||
private fun addCollectionSlots(
|
||||
name: String,
|
||||
config: CollectionConfig,
|
||||
container: Container
|
||||
) {
|
||||
val layout = config.layout
|
||||
var containerIndex = 0
|
||||
for (row in 0 until layout.rows) {
|
||||
for (col in 0 until layout.columns) {
|
||||
val x = layout.offsetX + col * (layout.slotWidth + layout.spacingX)
|
||||
val y = layout.offsetY + row * (layout.slotHeight + layout.spacingY)
|
||||
val mappedIndex = config.slots?.getOrNull(containerIndex) ?: containerIndex
|
||||
require(mappedIndex in 0 until container.containerSize) { "collection '$name' maps outside its container" }
|
||||
addSlot(MolangSlot(
|
||||
container = container,
|
||||
index = mappedIndex,
|
||||
x = x,
|
||||
y = y,
|
||||
collectionConfig = config
|
||||
))
|
||||
containerIndex++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addPlayerSlots() {
|
||||
playerInventoryStart = slots.size
|
||||
|
||||
for (row in 0 until 3) {
|
||||
for (col in 0 until 9) {
|
||||
val inventoryIndex = 9 + row * 9 + col
|
||||
val x = 8 + col * 18
|
||||
val y = 84 + row * 18
|
||||
addSlot(Slot(playerInventory, inventoryIndex, x, y))
|
||||
}
|
||||
}
|
||||
|
||||
playerHotbarStart = slots.size
|
||||
|
||||
for (col in 0 until 9) {
|
||||
addSlot(Slot(playerInventory, col, 8 + col * 18, 142))
|
||||
}
|
||||
|
||||
playerHotbarEnd = slots.size
|
||||
}
|
||||
|
||||
override fun quickMoveStack(player: Player, index: Int): ItemStack {
|
||||
val slot = slots.getOrNull(index) ?: return ItemStack.EMPTY
|
||||
if (!slot.hasItem() || !slot.mayPickup(player)) return ItemStack.EMPTY
|
||||
|
||||
val slotItem = slot.item
|
||||
val original = slotItem.copy()
|
||||
|
||||
val clickedCollection = collectionRanges.firstOrNull { index >= it.startIndex && index < it.endIndex }
|
||||
val isPlayerInventory = index >= playerInventoryStart && index < playerInventoryEnd()
|
||||
val isHotbar = index >= playerHotbarStart && index < playerHotbarEnd
|
||||
|
||||
val sourceName = clickedCollection?.name ?: when {
|
||||
isPlayerInventory -> ShiftClickRule.PLAYER_INVENTORY
|
||||
isHotbar -> ShiftClickRule.PLAYER_HOTBAR
|
||||
else -> return ItemStack.EMPTY
|
||||
}
|
||||
val destinations = findShiftClickRule(sourceName)?.to ?: if (clickedCollection != null) {
|
||||
ShiftClickRule.PLAYER_SIDE_NAMES
|
||||
} else {
|
||||
collectionRanges.map { it.name }
|
||||
}
|
||||
if (!tryMoveToCollections(slotItem, slot, destinations)) return ItemStack.EMPTY
|
||||
|
||||
if (slotItem.isEmpty) {
|
||||
slot.setByPlayer(ItemStack.EMPTY)
|
||||
} else {
|
||||
slot.setChanged()
|
||||
}
|
||||
|
||||
if (slotItem.count == original.count) return ItemStack.EMPTY
|
||||
|
||||
slot.onTake(player, slotItem)
|
||||
return original
|
||||
}
|
||||
|
||||
override fun stillValid(player: Player): Boolean {
|
||||
val expectedOwner = owner ?: return true // client menu
|
||||
if (player.uuid != expectedOwner.uuid || owningSession?.state != SessionState.ACTIVE) return false
|
||||
val pos = blockPos ?: return true
|
||||
if (player.distanceToSqr(pos.x + .5, pos.y + .5, pos.z + .5) > 64.0) return false
|
||||
return player.level().getBlockEntity(pos) === originalBlockContainer
|
||||
}
|
||||
|
||||
override fun removed(player: Player) {
|
||||
try {
|
||||
super.removed(player)
|
||||
} finally {
|
||||
try {
|
||||
releaseOwnedItemsOnce(player)
|
||||
} finally {
|
||||
owningSession?.closeFromMenu()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseOwnedItemsOnce(player: Player) {
|
||||
if (ownedItemsReleased) return
|
||||
ownedItemsReleased = true
|
||||
for (name in sessionOwnedCollections) {
|
||||
val container = collections[name] ?: continue
|
||||
when (closeItemsPolicy) {
|
||||
CloseItemsPolicy.DROP -> clearContainer(player, container)
|
||||
CloseItemsPolicy.RETURN -> returnItemsToPlayer(player, container)
|
||||
CloseItemsPolicy.DESTROY -> container.clearContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getStack(collection: String, index: Int): ItemStack? {
|
||||
return collectionSlot(collection, index)?.item
|
||||
}
|
||||
|
||||
fun replaceSlotAtomically(
|
||||
inputCollection: String,
|
||||
inputIndex: Int,
|
||||
consumeCount: Int,
|
||||
outputCollection: String,
|
||||
outputIndex: Int,
|
||||
outputItemId: String,
|
||||
outputCount: Int
|
||||
): Boolean {
|
||||
if (consumeCount <= 0 || outputCount <= 0) return false
|
||||
val input = collectionSlot(inputCollection, inputIndex) ?: return false
|
||||
val output = collectionSlot(outputCollection, outputIndex) ?: return false
|
||||
val id = ResourceLocation.tryParse(outputItemId)?.takeIf(BuiltInRegistries.ITEM::containsKey) ?: return false
|
||||
val produced = ItemStack(BuiltInRegistries.ITEM.get(id), outputCount)
|
||||
val outputConfig = collectionConfigs[outputCollection] ?: return false
|
||||
if (!outputConfig.matchesFilter(produced)) return false
|
||||
val source = input.item
|
||||
if (source.count < consumeCount) return false
|
||||
val remaining = source.copyWithCount(source.count - consumeCount)
|
||||
val sameSlot = input.container === output.container && input.containerSlot == output.containerSlot
|
||||
val existing = if (sameSlot) remaining else output.item
|
||||
if (!existing.isEmpty && !ItemStack.isSameItemSameComponents(existing, produced)) return false
|
||||
val limit = output.getMaxStackSize(produced)
|
||||
if (existing.count > limit || outputCount > limit - existing.count) return false
|
||||
val result = if (existing.isEmpty) produced else existing.copyWithCount(existing.count + outputCount)
|
||||
if (!sameSlot) input.set(remaining)
|
||||
output.set(result)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun playerInventoryEnd() = playerHotbarStart
|
||||
|
||||
private fun findShiftClickRule(fromCollection: String): ShiftClickRule? {
|
||||
return shiftClickRules.firstOrNull { rule ->
|
||||
rule.from.contains(fromCollection)
|
||||
}
|
||||
}
|
||||
|
||||
private fun collectionSlot(name: String, index: Int): Slot? {
|
||||
val range = collectionRanges.firstOrNull { it.name == name } ?: return null
|
||||
if (index !in 0 until range.endIndex - range.startIndex) return null
|
||||
return slots[range.startIndex + index]
|
||||
}
|
||||
|
||||
private fun tryMoveToCollections(stack: ItemStack, source: Slot, toNames: List<String>): Boolean {
|
||||
val originalCount = stack.count
|
||||
for (name in toNames) {
|
||||
val indices = when (name) {
|
||||
ShiftClickRule.PLAYER_INVENTORY -> playerInventoryStart until playerHotbarStart
|
||||
ShiftClickRule.PLAYER_HOTBAR -> playerHotbarStart until playerHotbarEnd
|
||||
else -> collectionRanges.firstOrNull { it.name == name }?.let { it.startIndex until it.endIndex } ?: continue
|
||||
}
|
||||
for (merge in listOf(true, false)) {
|
||||
for (index in indices) {
|
||||
if (stack.isEmpty) return true
|
||||
val destination = slots[index]
|
||||
if (destination.container === source.container && destination.containerSlot == source.containerSlot) continue
|
||||
if (destination.hasItem() != merge || destination.item.count >= destination.getMaxStackSize(stack)) continue
|
||||
destination.safeInsert(stack)
|
||||
}
|
||||
}
|
||||
}
|
||||
return stack.count < originalCount
|
||||
}
|
||||
|
||||
private fun returnItemsToPlayer(player: Player, container: Container) {
|
||||
val inventory = player.inventory
|
||||
for (i in 0 until container.containerSize) {
|
||||
val stack = container.getItem(i)
|
||||
if (!stack.isEmpty) {
|
||||
if (!inventory.add(stack)) {
|
||||
player.drop(stack, false)
|
||||
}
|
||||
container.setItem(i, ItemStack.EMPTY)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +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.molangui.container
|
||||
|
||||
import net.minecraft.world.Container
|
||||
import net.minecraft.world.inventory.Slot
|
||||
import net.minecraft.world.item.ItemStack
|
||||
|
||||
class MolangSlot(
|
||||
container: Container,
|
||||
index: Int,
|
||||
x: Int,
|
||||
y: Int,
|
||||
private val collectionConfig: CollectionConfig
|
||||
) : Slot(container, index, x, y) {
|
||||
|
||||
override fun mayPlace(stack: ItemStack): Boolean {
|
||||
return collectionConfig.isItemAllowed(stack) && container.canPlaceItem(containerSlot, stack)
|
||||
}
|
||||
|
||||
override fun getMaxStackSize(stack: ItemStack): Int = container.getMaxStackSize(stack)
|
||||
}
|
||||
@@ -1,56 +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.molangui.container
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.MolangUiPacketLimits
|
||||
import net.minecraft.world.entity.player.Inventory
|
||||
|
||||
data class SlotLayout(
|
||||
val offsetX: Int,
|
||||
val offsetY: Int,
|
||||
val columns: Int,
|
||||
val rows: Int,
|
||||
val slotWidth: Int = 18,
|
||||
val slotHeight: Int = 18,
|
||||
val spacingX: Int = 0,
|
||||
val spacingY: Int = 0
|
||||
) {
|
||||
init {
|
||||
require(columns in 1..MAX_GRID_DIMENSION && rows in 1..MAX_GRID_DIMENSION) { "slot grid dimensions must be in 1..$MAX_GRID_DIMENSION" }
|
||||
validateAxis(offsetX, columns, slotWidth, spacingX)
|
||||
validateAxis(offsetY, rows, slotHeight, spacingY)
|
||||
}
|
||||
|
||||
val slotCount: Int get() = columns * rows
|
||||
|
||||
private fun validateAxis(offset: Int, count: Int, size: Int, spacing: Int) {
|
||||
require(size > 0 && spacing >= 0) { "slot size must be positive and spacing nonnegative" }
|
||||
val stride = size.toLong() + spacing
|
||||
val lastSlotOffset = (count - 1) * stride
|
||||
require(stride <= Int.MAX_VALUE && lastSlotOffset <= Int.MAX_VALUE && offset + lastSlotOffset + size <= Int.MAX_VALUE) {
|
||||
"slot grid coordinates exceed the integer range"
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MAX_GRID_DIMENSION = 16
|
||||
|
||||
fun validateCollections(layouts: Map<String, SlotLayout>) {
|
||||
require(layouts.size <= MolangUiPacketLimits.MAX_CONTRACTS) { "too many container collections" }
|
||||
layouts.keys.forEach { name ->
|
||||
MolangUiPacketLimits.requireIdentifier(name, "collection name")
|
||||
require(name !in ShiftClickRule.PLAYER_SIDE_NAMES) { "collection name '$name' is reserved for player slots" }
|
||||
}
|
||||
// Native container packets encode slot indices as signed shorts.
|
||||
require(layouts.values.sumOf { it.slotCount.toLong() } + Inventory.INVENTORY_SIZE <= Short.MAX_VALUE + 1L) {
|
||||
"container slot indices exceed the native packet range"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-89
@@ -1,89 +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.molangui.event
|
||||
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import com.bedrockk.molang.runtime.struct.QueryStruct
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.api.molangui.MolangUiPacketLimits
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetDefinition
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetInstance
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetType
|
||||
import com.cobblemon.mod.common.net.messages.server.molangui.MolangUiActionPacket
|
||||
import com.cobblemon.mod.common.util.asExpressionLike
|
||||
import java.util.UUID
|
||||
|
||||
object ClientEventProcessor {
|
||||
|
||||
fun processEvent(
|
||||
event: WidgetEvent,
|
||||
widget: WidgetDefinition,
|
||||
runtime: MoLangRuntime,
|
||||
sessionId: UUID
|
||||
) {
|
||||
val context = QueryStruct(hashMapOf())
|
||||
event.data.forEach { (key, value) -> context.addFunction(key) { DoubleValue(value) } }
|
||||
context.addFunction("type") { StringValue(event.type.id) }
|
||||
context.addFunction("widget_id") { StringValue(event.widgetId) }
|
||||
val functions = runtime.environment.query.functions
|
||||
val previous = functions.remove("event")
|
||||
runtime.environment.query.addFunction("event") { context }
|
||||
try {
|
||||
widget.clientEvents[event.type.clientId]?.asExpressionLike()?.resolve(runtime)
|
||||
widget.events[event.type.id]?.let { serverHandler ->
|
||||
// Action arguments may depend on variables changed by the client handler.
|
||||
val parameters = serverHandler.parameters.mapValues { (_, property) -> property.resolveString(runtime) }
|
||||
require(parameters.size <= MolangUiPacketLimits.MAX_ACTION_FIELDS) { "too many action parameters" }
|
||||
parameters.forEach { (name, value) ->
|
||||
MolangUiPacketLimits.requireIdentifier(name, "action parameter")
|
||||
MolangUiPacketLimits.requireValue(value, name)
|
||||
}
|
||||
MolangUiActionPacket(sessionId, serverHandler.action.value, parameters).sendToServer()
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Cobblemon.LOGGER.warn("Failed UI event {} on widget {}: {}", event.type.id, event.widgetId, error.message)
|
||||
} finally {
|
||||
functions.remove("event")
|
||||
if (previous != null) functions["event"] = previous
|
||||
}
|
||||
}
|
||||
|
||||
fun hitTest(root: WidgetInstance, x: Float, y: Float): WidgetInstance? {
|
||||
if (!root.visible || !root.enabled) return null
|
||||
val isScrollPanel = root.definition.type == WidgetType.SCROLL_PANEL
|
||||
if (isScrollPanel && !root.containsPoint(x, y)) return null
|
||||
|
||||
for (child in root.children.asReversed()) {
|
||||
if (!child.visible) continue
|
||||
val testY = if (isScrollPanel) y - root.scrollOffset else y
|
||||
val hit = hitTest(child, x, testY)
|
||||
if (hit != null) return hit
|
||||
}
|
||||
return if (root.containsPoint(x, y)) root else null
|
||||
}
|
||||
}
|
||||
|
||||
enum class WidgetEventType(val id: String) {
|
||||
CLICK("on_click"),
|
||||
CHANGE("on_change"),
|
||||
HOVER_ENTER("on_hover_enter"),
|
||||
HOVER_EXIT("on_hover_exit"),
|
||||
SCROLL("on_scroll"),
|
||||
KEY("on_key");
|
||||
|
||||
val clientId: String get() = "${id}_client"
|
||||
}
|
||||
|
||||
data class WidgetEvent(
|
||||
val type: WidgetEventType,
|
||||
val widgetId: String,
|
||||
val data: Map<String, Double> = emptyMap()
|
||||
)
|
||||
@@ -1,151 +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.molangui.layout
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetInstance
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
|
||||
object LayoutEngine {
|
||||
|
||||
fun layout(root: WidgetInstance, screenWidth: Float, screenHeight: Float, runtime: MoLangRuntime): Unit = root.withItemContext(runtime) {
|
||||
require(screenWidth.isFinite() && screenHeight.isFinite() && screenWidth >= 0f && screenHeight >= 0f) {
|
||||
"invalid screen dimensions"
|
||||
}
|
||||
if (!root.visible) return@withItemContext
|
||||
root.computedWidth = root.widthExpr.resolve(screenWidth, runtime)
|
||||
root.computedHeight = root.heightExpr.resolve(screenHeight, runtime)
|
||||
val anchor = root.definition.getAnchor()
|
||||
val offsetX = root.offsetXExpr.resolve(screenWidth, runtime)
|
||||
val offsetY = root.offsetYExpr.resolve(screenHeight, runtime)
|
||||
root.absoluteX = (screenWidth - root.computedWidth) * anchor.xFactor + offsetX
|
||||
root.absoluteY = (screenHeight - root.computedHeight) * anchor.yFactor + offsetY
|
||||
validateBounds(root)
|
||||
layoutChildren(root, runtime)
|
||||
}
|
||||
|
||||
private fun layoutChildren(parent: WidgetInstance, runtime: MoLangRuntime): Unit = parent.withItemContext(runtime) {
|
||||
val layout = parent.definition.getStringProperty("layout")
|
||||
val spacing = parent.definition.getProperty("spacing")?.resolveFloat(runtime) ?: 0f
|
||||
require(spacing.isFinite()) { "non-finite spacing at '${parent.definition.id}'" }
|
||||
val padding = parent.paddingProperties.map { it.resolveFloat(runtime) }
|
||||
require(padding.size == 4 && padding.all { it.isFinite() && it >= 0f }) {
|
||||
"invalid padding at '${parent.definition.id}'"
|
||||
}
|
||||
val innerWidth = (parent.computedWidth - padding[3] - padding[1]).coerceAtLeast(0f)
|
||||
val innerHeight = (parent.computedHeight - padding[0] - padding[2]).coerceAtLeast(0f)
|
||||
val innerX = parent.absoluteX + padding[3]
|
||||
val innerY = parent.absoluteY + padding[0]
|
||||
|
||||
for (child in parent.children) {
|
||||
if (!child.visible) continue
|
||||
child.computedWidth = child.withItemContext(runtime) { child.widthExpr.resolve(innerWidth, runtime) }
|
||||
child.computedHeight = child.withItemContext(runtime) { child.heightExpr.resolve(innerHeight, runtime) }
|
||||
}
|
||||
|
||||
when (layout) {
|
||||
"stack_vertical" -> layoutStackVertical(parent, innerX, innerY, innerWidth, innerHeight, spacing, runtime)
|
||||
"stack_horizontal" -> layoutStackHorizontal(parent, innerX, innerY, innerWidth, innerHeight, spacing, runtime)
|
||||
"grid" -> layoutGrid(parent, innerX, innerY, innerWidth, spacing, runtime)
|
||||
else -> layoutAnchored(parent, innerX, innerY, innerWidth, innerHeight, runtime)
|
||||
}
|
||||
|
||||
for (child in parent.children) {
|
||||
if (!child.visible) continue
|
||||
validateBounds(child)
|
||||
layoutChildren(child, runtime)
|
||||
}
|
||||
}
|
||||
|
||||
private fun layoutAnchored(parent: WidgetInstance, innerX: Float, innerY: Float, innerWidth: Float, innerHeight: Float, runtime: MoLangRuntime) {
|
||||
for (child in parent.children) {
|
||||
if (!child.visible) continue
|
||||
val anchor = child.definition.getAnchor()
|
||||
val offsetX = child.withItemContext(runtime) { child.offsetXExpr.resolve(innerWidth, runtime) }
|
||||
val offsetY = child.withItemContext(runtime) { child.offsetYExpr.resolve(innerHeight, runtime) }
|
||||
child.absoluteX = innerX + (innerWidth - child.computedWidth) * anchor.xFactor + offsetX
|
||||
child.absoluteY = innerY + (innerHeight - child.computedHeight) * anchor.yFactor + offsetY
|
||||
}
|
||||
}
|
||||
|
||||
private fun layoutStackVertical(parent: WidgetInstance, innerX: Float, innerY: Float, innerWidth: Float, innerHeight: Float, spacing: Float, runtime: MoLangRuntime) {
|
||||
val visibleChildren = parent.children.filter { it.visible }
|
||||
resolveFillSizes(visibleChildren, innerHeight, spacing, isVertical = true)
|
||||
var currentY = innerY
|
||||
for (child in visibleChildren) {
|
||||
child.absoluteX = innerX + child.withItemContext(runtime) { child.offsetXExpr.resolve(innerWidth, runtime) }
|
||||
child.absoluteY = currentY + child.withItemContext(runtime) { child.offsetYExpr.resolve(innerHeight, runtime) }
|
||||
currentY += child.computedHeight + spacing
|
||||
}
|
||||
}
|
||||
|
||||
private fun layoutStackHorizontal(parent: WidgetInstance, innerX: Float, innerY: Float, innerWidth: Float, innerHeight: Float, spacing: Float, runtime: MoLangRuntime) {
|
||||
val visibleChildren = parent.children.filter { it.visible }
|
||||
resolveFillSizes(visibleChildren, innerWidth, spacing, isVertical = false)
|
||||
var currentX = innerX
|
||||
for (child in visibleChildren) {
|
||||
child.absoluteX = currentX + child.withItemContext(runtime) { child.offsetXExpr.resolve(innerWidth, runtime) }
|
||||
child.absoluteY = innerY + child.withItemContext(runtime) { child.offsetYExpr.resolve(innerHeight, runtime) }
|
||||
currentX += child.computedWidth + spacing
|
||||
}
|
||||
}
|
||||
|
||||
private fun layoutGrid(parent: WidgetInstance, innerX: Float, innerY: Float, innerWidth: Float, spacing: Float, runtime: MoLangRuntime) {
|
||||
val columns = (parent.definition.getProperty("columns")?.resolveInt(runtime) ?: 1).coerceIn(1, 256)
|
||||
val visibleChildren = parent.children.filter { it.visible }
|
||||
val cellWidth = ((innerWidth - spacing * (columns - 1)) / columns).coerceAtLeast(0f)
|
||||
var col = 0
|
||||
var currentY = innerY
|
||||
var rowHeight = 0f
|
||||
for (child in visibleChildren) {
|
||||
if (child.widthExpr is SizeExpression.Fill) child.computedWidth = cellWidth
|
||||
child.absoluteX = innerX + col * (cellWidth + spacing)
|
||||
child.absoluteY = currentY
|
||||
rowHeight = maxOf(rowHeight, child.computedHeight)
|
||||
col++
|
||||
if (col >= columns) {
|
||||
col = 0
|
||||
currentY += rowHeight + spacing
|
||||
rowHeight = 0f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveFillSizes(children: List<WidgetInstance>, totalSpace: Float, spacing: Float, isVertical: Boolean) {
|
||||
val totalSpacing = spacing * (children.size - 1).coerceAtLeast(0)
|
||||
var usedSpace = totalSpacing
|
||||
var fillCount = 0
|
||||
for (child in children) {
|
||||
val expr = if (isVertical) child.heightExpr else child.widthExpr
|
||||
if (expr is SizeExpression.Fill) {
|
||||
fillCount++
|
||||
} else {
|
||||
usedSpace += if (isVertical) child.computedHeight else child.computedWidth
|
||||
}
|
||||
}
|
||||
if (fillCount > 0) {
|
||||
val fillSize = ((totalSpace - usedSpace) / fillCount).coerceAtLeast(0f)
|
||||
for (child in children) {
|
||||
val expr = if (isVertical) child.heightExpr else child.widthExpr
|
||||
if (expr is SizeExpression.Fill) {
|
||||
if (isVertical) child.computedHeight = fillSize else child.computedWidth = fillSize
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun validateBounds(widget: WidgetInstance) {
|
||||
fun validAxis(position: Float, size: Float): Boolean =
|
||||
position.isFinite() && size.isFinite() && size >= 0f && size.toDouble() <= Int.MAX_VALUE &&
|
||||
position.toDouble() >= Int.MIN_VALUE && position.toDouble() + size.toDouble() <= Int.MAX_VALUE
|
||||
|
||||
require(validAxis(widget.absoluteX, widget.computedWidth) && validAxis(widget.absoluteY, widget.computedHeight)) {
|
||||
"widget '${widget.definition.id}' has invalid or overflowing bounds"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,75 +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.molangui.layout
|
||||
|
||||
import com.cobblemon.mod.common.api.molang.ExpressionLike
|
||||
import com.cobblemon.mod.common.util.asExpressionLike
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetExpression
|
||||
|
||||
sealed class SizeExpression {
|
||||
abstract fun resolve(parentSize: Float, runtime: MoLangRuntime): Float
|
||||
|
||||
data class Pixels(val value: Float) : SizeExpression() {
|
||||
init { require(value.isFinite()) { "pixel size must be finite" } }
|
||||
override fun resolve(parentSize: Float, runtime: MoLangRuntime) = value
|
||||
}
|
||||
|
||||
data class Percent(val fraction: Float) : SizeExpression() {
|
||||
init { require(fraction.isFinite()) { "percentage must be finite" } }
|
||||
override fun resolve(parentSize: Float, runtime: MoLangRuntime) = parentSize * fraction
|
||||
}
|
||||
|
||||
data class PercentWithOffset(val fraction: Float, val offset: Float) : SizeExpression() {
|
||||
init { require(fraction.isFinite() && offset.isFinite()) { "percentage and offset must be finite" } }
|
||||
override fun resolve(parentSize: Float, runtime: MoLangRuntime) = parentSize * fraction + offset
|
||||
}
|
||||
|
||||
data object Fill : SizeExpression() {
|
||||
override fun resolve(parentSize: Float, runtime: MoLangRuntime) = parentSize
|
||||
}
|
||||
|
||||
data class MolangSize(val expression: ExpressionLike) : SizeExpression() {
|
||||
override fun resolve(parentSize: Float, runtime: MoLangRuntime) = expression.resolveFloat(runtime)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val PERCENT_PATTERN = Regex("""^(\d+(?:\.\d+)?)%$""")
|
||||
private val PERCENT_OFFSET_PATTERN = Regex("""^(\d+(?:\.\d+)?)%\s*([+-])\s*(\d+(?:\.\d+)?)$""")
|
||||
|
||||
fun parse(value: Any): SizeExpression {
|
||||
return when (value) {
|
||||
is Number -> Pixels(value.toFloat())
|
||||
is String -> parseString(value)
|
||||
is WidgetExpression -> MolangSize(value.source.asExpressionLike())
|
||||
else -> throw IllegalArgumentException("size must be a number, percentage, fill, or explicit Molang expression")
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseString(value: String): SizeExpression {
|
||||
val trimmed = value.trim()
|
||||
return when {
|
||||
trimmed == "fill" -> Fill
|
||||
trimmed.toFloatOrNull() != null -> Pixels(trimmed.toFloat())
|
||||
PERCENT_PATTERN.matches(trimmed) -> {
|
||||
val pct = PERCENT_PATTERN.matchEntire(trimmed)!!.groupValues[1].toFloat()
|
||||
Percent(pct / 100f)
|
||||
}
|
||||
PERCENT_OFFSET_PATTERN.matches(trimmed) -> {
|
||||
val match = PERCENT_OFFSET_PATTERN.matchEntire(trimmed)!!
|
||||
val pct = match.groupValues[1].toFloat() / 100f
|
||||
val sign = if (match.groupValues[2] == "+") 1f else -1f
|
||||
val offset = match.groupValues[3].toFloat() * sign
|
||||
PercentWithOffset(pct, offset)
|
||||
}
|
||||
else -> throw IllegalArgumentException("invalid size '$value'; Molang requires an explicit expression object")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-114
@@ -1,114 +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.molangui.template
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonElement
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.server.packs.resources.ResourceManager
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
|
||||
|
||||
object TemplateLibraryRegistry {
|
||||
private val gson = Gson()
|
||||
private val libraries: MutableMap<ResourceLocation, Map<String, TemplateDefinition>> = mutableMapOf()
|
||||
|
||||
private const val DIRECTORY = "molang_ui/templates"
|
||||
|
||||
fun reload(manager: ResourceManager) {
|
||||
val next = mutableMapOf<ResourceLocation, Map<String, TemplateDefinition>>()
|
||||
val resources = manager.listResources(DIRECTORY) { it.path.endsWith(".json") }
|
||||
for ((location, resource) in resources) {
|
||||
try {
|
||||
val json = resource.openAsReader().use { gson.fromJson(it, JsonObject::class.java) }
|
||||
val namespace = location.namespace
|
||||
val name = location.path.removePrefix("$DIRECTORY/").removeSuffix(".json")
|
||||
val libraryId = ResourceLocation.fromNamespaceAndPath(namespace, name)
|
||||
val templates = parseTemplates(json, namespace)
|
||||
next[libraryId] = templates
|
||||
} catch (e: Exception) {
|
||||
Cobblemon.LOGGER.error("Rejected Molang UI template library '$location': ${e.message}")
|
||||
}
|
||||
}
|
||||
libraries.clear()
|
||||
libraries.putAll(next)
|
||||
}
|
||||
|
||||
fun getTemplate(qualifiedName: String): TemplateDefinition? {
|
||||
val dotIndex = qualifiedName.lastIndexOf('.')
|
||||
if (dotIndex == -1) return null
|
||||
val libraryName = qualifiedName.substring(0, dotIndex)
|
||||
val templateName = qualifiedName.substring(dotIndex + 1)
|
||||
val library = if (':' in libraryName) {
|
||||
ResourceLocation.tryParse(libraryName)?.let(libraries::get)
|
||||
} else {
|
||||
libraries.entries.singleOrNull { it.key.path == libraryName }?.value
|
||||
}
|
||||
return library?.get(templateName)
|
||||
}
|
||||
|
||||
private fun parseTemplates(json: JsonObject, namespace: String): Map<String, TemplateDefinition> {
|
||||
val result = mutableMapOf<String, TemplateDefinition>()
|
||||
val templatesObj = json.getAsJsonObject("templates") ?: return result
|
||||
for ((name, element) in templatesObj.entrySet()) {
|
||||
val templateJson = element.asJsonObject
|
||||
val inputs = mutableMapOf<String, TemplateInput>()
|
||||
templateJson.getAsJsonObject("inputs")?.let { inputsObj ->
|
||||
for ((inputName, inputEl) in inputsObj.entrySet()) {
|
||||
val inputObj = inputEl.asJsonObject
|
||||
val type = TemplateInputType.fromId(inputObj.get("type")?.asString ?: "string")
|
||||
?: throw IllegalArgumentException("unknown template input type for '$inputName'")
|
||||
val default = inputObj.get("default")
|
||||
require(default == null || type.accepts(default)) { "invalid template default at '$name.$inputName'" }
|
||||
inputs[inputName] = TemplateInput(type, default)
|
||||
}
|
||||
}
|
||||
val extends = templateJson.get("extends")?.asString
|
||||
result[name] = TemplateDefinition(
|
||||
name = name,
|
||||
namespace = namespace,
|
||||
inputs = inputs,
|
||||
extends = extends,
|
||||
body = templateJson
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
data class TemplateDefinition(
|
||||
val name: String,
|
||||
val namespace: String,
|
||||
val inputs: Map<String, TemplateInput> = emptyMap(),
|
||||
val extends: String? = null,
|
||||
val body: JsonObject
|
||||
)
|
||||
|
||||
data class TemplateInput(
|
||||
val type: TemplateInputType = TemplateInputType.STRING,
|
||||
val default: JsonElement? = null
|
||||
)
|
||||
|
||||
enum class TemplateInputType(val id: String) {
|
||||
STRING("string"), NUMBER("number"), BOOLEAN("boolean"), EXPRESSION("expression"), OBJECT("object"), ARRAY("array");
|
||||
|
||||
fun accepts(value: JsonElement): Boolean = when (this) {
|
||||
STRING -> value.isJsonPrimitive && value.asJsonPrimitive.isString
|
||||
NUMBER -> value.isJsonPrimitive && value.asJsonPrimitive.isNumber && value.asDouble.isFinite()
|
||||
BOOLEAN -> value.isJsonPrimitive && value.asJsonPrimitive.isBoolean
|
||||
EXPRESSION -> value.isJsonObject && value.asJsonObject.size() == 1 && value.asJsonObject.get("molang")?.let {
|
||||
it.isJsonPrimitive && it.asJsonPrimitive.isString
|
||||
} == true
|
||||
OBJECT -> value.isJsonObject
|
||||
ARRAY -> value.isJsonArray
|
||||
}
|
||||
|
||||
companion object { fun fromId(id: String) = entries.firstOrNull { it.id == id } }
|
||||
}
|
||||
-135
@@ -1,135 +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.molangui.template
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.widget.WidgetTree
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.JsonElement
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonPrimitive
|
||||
|
||||
object TemplateResolver {
|
||||
fun resolve(root: JsonObject, localTemplates: Map<String, TemplateDefinition>): JsonObject =
|
||||
Resolution(localTemplates).resolveNode(root, emptyList(), 1)
|
||||
|
||||
private class Resolution(private val localTemplates: Map<String, TemplateDefinition>) {
|
||||
private var nodes = 0
|
||||
private var values = 0
|
||||
|
||||
fun resolveNode(node: JsonObject, chain: List<String>, depth: Int): JsonObject {
|
||||
require(depth <= WidgetTree.MAX_DEPTH) { "template expansion exceeds maximum widget depth ${WidgetTree.MAX_DEPTH}" }
|
||||
require(++nodes <= WidgetTree.MAX_NODES) { "template expansion exceeds maximum widget count ${WidgetTree.MAX_NODES}" }
|
||||
val result = JsonObject()
|
||||
node.entrySet().filter { it.key != "controls" && it.key != "item_template" }.forEach { (key, value) ->
|
||||
result.add(key, copy(value))
|
||||
}
|
||||
node.getAsJsonArray("controls")?.let { controls ->
|
||||
val resolvedControls = JsonArray()
|
||||
controls.forEach { element ->
|
||||
val wrapper = element.takeIf(JsonElement::isJsonObject)?.asJsonObject
|
||||
?: throw IllegalArgumentException("control entries must be objects")
|
||||
require(wrapper.size() == 1) { "control entries must contain exactly one widget" }
|
||||
val (key, value) = wrapper.entrySet().single()
|
||||
val output = JsonObject()
|
||||
require(value.isJsonObject) { "widget '$key' must be an object" }
|
||||
output.add(key.substringBefore('@'), resolveWidgetEntry(key, value.asJsonObject, chain, depth + 1))
|
||||
resolvedControls.add(output)
|
||||
}
|
||||
result.add("controls", resolvedControls)
|
||||
}
|
||||
node.getAsJsonObject("item_template")?.let {
|
||||
result.add("item_template", resolveNode(it, chain, depth + 1))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun resolveWidgetEntry(
|
||||
key: String,
|
||||
overrides: JsonObject,
|
||||
chain: List<String>,
|
||||
depth: Int
|
||||
): JsonObject {
|
||||
if ('@' !in key) return resolveNode(overrides, chain, depth)
|
||||
val templateRef = key.substringAfter('@')
|
||||
require(templateRef !in chain) { "template expansion cycle: ${(chain + templateRef).joinToString(" -> ")}" }
|
||||
require(depth <= WidgetTree.MAX_DEPTH) { "template expansion exceeds maximum widget depth ${WidgetTree.MAX_DEPTH}" }
|
||||
val template = findTemplate(templateRef)
|
||||
?: throw IllegalArgumentException("missing template '$templateRef'")
|
||||
val inherited = resolveTemplateChain(templateRef, template, emptyList())
|
||||
val inputs = inherited.inputs.mapValues { (name, input) ->
|
||||
val supplied = overrides.get(name)
|
||||
val value = supplied ?: input.default
|
||||
?: throw IllegalArgumentException("missing required template input '$name' for '$templateRef'")
|
||||
require(input.type.accepts(value)) {
|
||||
"template input '$name' for '$templateRef' must be ${input.type.id}"
|
||||
}
|
||||
value
|
||||
}
|
||||
val substituted = copy(inherited.body, inputs).asJsonObject
|
||||
val nonInputs = JsonObject().also { obj ->
|
||||
overrides.entrySet().filter { it.key !in inherited.inputs }.forEach { (name, value) -> obj.add(name, value) }
|
||||
}
|
||||
return resolveNode(mergeJson(substituted, nonInputs), chain + templateRef, depth)
|
||||
}
|
||||
|
||||
private fun resolveTemplateChain(
|
||||
ref: String,
|
||||
template: TemplateDefinition,
|
||||
chain: List<String>
|
||||
): TemplateDefinition {
|
||||
require(ref !in chain) { "template inheritance cycle: ${(chain + ref).joinToString(" -> ")}" }
|
||||
require(chain.size < WidgetTree.MAX_DEPTH) { "template inheritance exceeds maximum depth ${WidgetTree.MAX_DEPTH}" }
|
||||
val nextChain = chain + ref
|
||||
val body = JsonObject().also { obj ->
|
||||
template.body.entrySet().filter { it.key != "inputs" && it.key != "extends" }
|
||||
.forEach { (name, value) -> obj.add(name, value) }
|
||||
}
|
||||
val parentRef = template.extends ?: return template.copy(body = body)
|
||||
val parent = findTemplate(parentRef)
|
||||
?: throw IllegalArgumentException("missing parent template '$parentRef' referenced by '$ref'")
|
||||
val inherited = resolveTemplateChain(parentRef, parent, nextChain)
|
||||
return template.copy(inputs = inherited.inputs + template.inputs, body = mergeJson(inherited.body, body))
|
||||
}
|
||||
|
||||
private fun findTemplate(ref: String) =
|
||||
localTemplates[ref] ?: TemplateLibraryRegistry.getTemplate(ref)
|
||||
|
||||
private fun copy(element: JsonElement, inputs: Map<String, JsonElement>? = null, depth: Int = 0): JsonElement {
|
||||
require(depth <= 128) { "template JSON exceeds maximum depth 128" }
|
||||
require(++values <= 1_048_576) { "template expansion exceeds maximum JSON work" }
|
||||
if (inputs != null && element.isJsonPrimitive && element.asJsonPrimitive.isString) {
|
||||
val text = element.asString
|
||||
if (text.startsWith('$') && text.length > 1 && text.indexOf('$', 1) == -1) {
|
||||
val supplied = inputs[text.substring(1)]
|
||||
?: throw IllegalArgumentException("unknown template input reference '$text'")
|
||||
return copy(supplied, depth = depth + 1)
|
||||
}
|
||||
return JsonPrimitive(text)
|
||||
}
|
||||
if (element.isJsonArray) return JsonArray().also { out -> element.asJsonArray.forEach { out.add(copy(it, inputs, depth + 1)) } }
|
||||
if (element.isJsonObject) return JsonObject().also { out ->
|
||||
element.asJsonObject.entrySet().forEach { (key, value) ->
|
||||
out.add(key, copy(value, inputs, depth + 1))
|
||||
}
|
||||
}
|
||||
return element.deepCopy()
|
||||
}
|
||||
|
||||
private fun mergeJson(base: JsonObject, overlay: JsonObject): JsonObject {
|
||||
val result = copy(base).asJsonObject
|
||||
overlay.entrySet().forEach { (key, value) ->
|
||||
val existing = result.get(key)
|
||||
result.add(key, if (value.isJsonObject && existing?.isJsonObject == true) {
|
||||
mergeJson(existing.asJsonObject, value.asJsonObject)
|
||||
} else copy(value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
-68
@@ -1,68 +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.molangui.widget
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.ActionKey
|
||||
|
||||
data class WidgetDefinition(
|
||||
val id: String,
|
||||
val type: WidgetType,
|
||||
val properties: Map<String, WidgetProperty> = emptyMap(),
|
||||
val children: List<WidgetDefinition> = emptyList(),
|
||||
val events: Map<String, ServerWidgetEvent> = emptyMap(),
|
||||
val clientEvents: Map<String, String> = emptyMap(),
|
||||
val hoverOverrides: Map<String, WidgetProperty> = emptyMap(),
|
||||
val itemTemplate: WidgetDefinition? = null
|
||||
) {
|
||||
fun getProperty(name: String): WidgetProperty? = properties[name]
|
||||
fun getStringProperty(name: String): String? = (properties[name]?.raw as? String)
|
||||
fun getAnchor(): Anchor = Anchor.fromId(getStringProperty("anchor") ?: "top_left")
|
||||
}
|
||||
|
||||
data class ServerWidgetEvent(
|
||||
val action: ActionKey,
|
||||
val parameters: Map<String, WidgetProperty> = emptyMap()
|
||||
)
|
||||
|
||||
enum class WidgetType(val id: String) {
|
||||
PANEL("panel"),
|
||||
LABEL("label"),
|
||||
IMAGE("image"),
|
||||
FILL("fill"),
|
||||
BUTTON("button"),
|
||||
LIST("list"),
|
||||
PROGRESS_BAR("progress_bar"),
|
||||
SCROLL_PANEL("scroll_panel"),
|
||||
POKEMON_RENDER("pokemon_render"),
|
||||
NUMBER_INPUT("number_input"),
|
||||
ITEM_SLOT("item_slot"),
|
||||
SLOT_GRID("slot_grid");
|
||||
|
||||
companion object {
|
||||
private val BY_ID = entries.associateBy { it.id }
|
||||
fun fromId(id: String): WidgetType? = BY_ID[id]
|
||||
}
|
||||
}
|
||||
|
||||
enum class Anchor(val id: String, val xFactor: Float, val yFactor: Float) {
|
||||
TOP_LEFT("top_left", 0f, 0f),
|
||||
TOP_CENTER("top_center", 0.5f, 0f),
|
||||
TOP_RIGHT("top_right", 1f, 0f),
|
||||
CENTER_LEFT("center_left", 0f, 0.5f),
|
||||
CENTER("center", 0.5f, 0.5f),
|
||||
CENTER_RIGHT("center_right", 1f, 0.5f),
|
||||
BOTTOM_LEFT("bottom_left", 0f, 1f),
|
||||
BOTTOM_CENTER("bottom_center", 0.5f, 1f),
|
||||
BOTTOM_RIGHT("bottom_right", 1f, 1f);
|
||||
|
||||
companion object {
|
||||
private val BY_ID = entries.associateBy { it.id }
|
||||
fun fromId(id: String): Anchor = BY_ID[id] ?: TOP_LEFT
|
||||
}
|
||||
}
|
||||
-92
@@ -1,92 +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.molangui.widget
|
||||
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import com.bedrockk.molang.runtime.struct.QueryStruct
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.bedrockk.molang.runtime.value.MoValue
|
||||
import com.bedrockk.molang.runtime.value.StringValue
|
||||
import com.cobblemon.mod.common.api.molangui.MolangUiPacketLimits
|
||||
import com.cobblemon.mod.common.api.molangui.layout.SizeExpression
|
||||
import com.google.gson.JsonElement
|
||||
import com.google.gson.JsonParser
|
||||
|
||||
internal object WidgetExpansion {
|
||||
private data class Node(val definition: WidgetDefinition, val context: QueryStruct?, val children: List<Node>)
|
||||
|
||||
fun refresh(definition: WidgetDefinition, runtime: MoLangRuntime, previous: WidgetInstance? = null): WidgetInstance {
|
||||
var count = 0
|
||||
fun plan(def: WidgetDefinition, context: QueryStruct?, depth: Int): Node = withItemContext(runtime, context) {
|
||||
require(depth <= WidgetTree.MAX_DEPTH && ++count <= WidgetTree.MAX_NODES) {
|
||||
"expanded widget tree exceeds ${WidgetTree.MAX_NODES} widgets or depth ${WidgetTree.MAX_DEPTH}"
|
||||
}
|
||||
val children = if (def.type == WidgetType.LIST) {
|
||||
val template = requireNotNull(def.itemTemplate) { "list '${def.id}' requires item_template" }
|
||||
items(def, runtime).mapIndexed { index, values ->
|
||||
val item = QueryStruct(hashMapOf())
|
||||
values.forEach { (key, value) -> item.addFunction(key) { value } }
|
||||
item.addFunction("index") { DoubleValue(index.toDouble()) }
|
||||
plan(template.copy(id = "${template.id}[$index]"), item, depth + 1)
|
||||
}
|
||||
} else def.children.map { plan(it, context, depth + 1) }
|
||||
Node(def, context, children)
|
||||
}
|
||||
val planned = plan(definition, null, 1)
|
||||
fun apply(node: Node, old: WidgetInstance?, parent: WidgetInstance?): WidgetInstance {
|
||||
val widget = old?.takeIf { it.definition == node.definition } ?: WidgetInstance(node.definition, parent).apply {
|
||||
val size = node.definition.getProperty("size")?.raw as? List<*>
|
||||
if (size?.size == 2) {
|
||||
widthExpr = SizeExpression.parse(size[0] ?: 0)
|
||||
heightExpr = SizeExpression.parse(size[1] ?: 0)
|
||||
}
|
||||
val offset = node.definition.getProperty("offset")?.raw as? List<*>
|
||||
if (offset?.size == 2) {
|
||||
offsetXExpr = SizeExpression.parse(offset[0] ?: 0)
|
||||
offsetYExpr = SizeExpression.parse(offset[1] ?: 0)
|
||||
}
|
||||
}
|
||||
widget.itemContext = node.context
|
||||
val children = node.children.mapIndexed { index, child -> apply(child, widget.children.getOrNull(index), widget) }
|
||||
widget.children.clear()
|
||||
widget.children.addAll(children)
|
||||
return widget
|
||||
}
|
||||
return apply(planned, previous, null)
|
||||
}
|
||||
|
||||
private fun items(definition: WidgetDefinition, runtime: MoLangRuntime): List<Map<String, MoValue>> =
|
||||
when (definition.getStringProperty("source_type") ?: "data") {
|
||||
"count" -> {
|
||||
val count = definition.getProperty("source")?.resolveDouble(runtime) ?: 0.0
|
||||
require(count.isFinite() && count in 0.0..WidgetTree.MAX_NODES.toDouble() && count % 1.0 == 0.0) {
|
||||
"list '${definition.id}' requires a whole count between 0 and ${WidgetTree.MAX_NODES}"
|
||||
}
|
||||
List(count.toInt()) { emptyMap() }
|
||||
}
|
||||
"data" -> {
|
||||
val source = definition.getProperty("source")?.resolveString(runtime) ?: "[]"
|
||||
require(source.length <= MolangUiPacketLimits.MAX_VALUE_LENGTH) { "list '${definition.id}' source is too large" }
|
||||
val array = JsonParser.parseString(source).asJsonArray
|
||||
require(array.size() <= WidgetTree.MAX_NODES) { "list '${definition.id}' has too many items" }
|
||||
array.map { element -> element.asJsonObject.entrySet().associate { (key, item) -> key to value(item) } }
|
||||
}
|
||||
else -> throw IllegalArgumentException("unsupported list source_type at '${definition.id}'")
|
||||
}
|
||||
|
||||
private fun value(element: JsonElement): MoValue {
|
||||
if (!element.isJsonPrimitive) return StringValue(element.toString())
|
||||
val primitive = element.asJsonPrimitive
|
||||
return when {
|
||||
primitive.isBoolean -> DoubleValue(primitive.asBoolean)
|
||||
primitive.isNumber -> DoubleValue(primitive.asDouble.also { require(it.isFinite()) { "non-finite list item value" } })
|
||||
else -> StringValue(primitive.asString)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,67 +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.molangui.widget
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.layout.SizeExpression
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
import com.bedrockk.molang.runtime.struct.QueryStruct
|
||||
|
||||
class WidgetInstance(
|
||||
val definition: WidgetDefinition,
|
||||
val parent: WidgetInstance? = null
|
||||
) {
|
||||
var absoluteX: Float = 0f
|
||||
var absoluteY: Float = 0f
|
||||
var computedWidth: Float = 0f
|
||||
var computedHeight: Float = 0f
|
||||
|
||||
var widthExpr: SizeExpression = SizeExpression.Pixels(0f)
|
||||
var heightExpr: SizeExpression = SizeExpression.Pixels(0f)
|
||||
var offsetXExpr: SizeExpression = SizeExpression.Pixels(0f)
|
||||
var offsetYExpr: SizeExpression = SizeExpression.Pixels(0f)
|
||||
|
||||
internal val paddingProperties: List<WidgetProperty> =
|
||||
(definition.getProperty("padding")?.raw as? List<*>)?.map {
|
||||
when (it) {
|
||||
is Number -> WidgetProperty.literal(it)
|
||||
is WidgetExpression -> WidgetProperty.molang(it.source)
|
||||
else -> throw IllegalArgumentException("invalid padding at '${definition.id}'")
|
||||
}
|
||||
} ?: List(4) { WidgetProperty.literal(0) }
|
||||
|
||||
val children: MutableList<WidgetInstance> = mutableListOf()
|
||||
|
||||
var visible: Boolean = true
|
||||
var enabled: Boolean = true
|
||||
var hovered: Boolean = false
|
||||
|
||||
var scrollOffset: Float = 0f
|
||||
var rendererState: Any? = null
|
||||
var itemContext: QueryStruct? = null
|
||||
|
||||
inline fun <T> withItemContext(runtime: MoLangRuntime, action: () -> T): T =
|
||||
withItemContext(runtime, itemContext, action)
|
||||
|
||||
fun containsPoint(x: Float, y: Float): Boolean {
|
||||
return x >= absoluteX && x <= absoluteX + computedWidth &&
|
||||
y >= absoluteY && y <= absoluteY + computedHeight
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <T> withItemContext(runtime: MoLangRuntime, context: QueryStruct?, action: () -> T): T {
|
||||
val functions = runtime.environment.query.functions
|
||||
val previous = functions.remove("item")
|
||||
if (context != null) runtime.environment.query.addFunction("item") { context }
|
||||
try {
|
||||
return action()
|
||||
} finally {
|
||||
functions.remove("item")
|
||||
if (previous != null) functions["item"] = previous
|
||||
}
|
||||
}
|
||||
@@ -1,63 +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.molangui.widget
|
||||
|
||||
import com.cobblemon.mod.common.api.molang.ExpressionLike
|
||||
import com.cobblemon.mod.common.util.asExpressionLike
|
||||
import com.bedrockk.molang.runtime.MoLangRuntime
|
||||
|
||||
class WidgetProperty private constructor(val raw: Any, expressionSource: String?) {
|
||||
val expression: ExpressionLike? = expressionSource?.asExpressionLike()
|
||||
|
||||
fun resolveDouble(runtime: MoLangRuntime): Double {
|
||||
return expression?.resolveDouble(runtime) ?: when (raw) {
|
||||
is Number -> raw.toDouble()
|
||||
is String -> parseNumericString(raw)
|
||||
is Boolean -> if (raw) 1.0 else 0.0
|
||||
else -> 0.0
|
||||
}
|
||||
}
|
||||
|
||||
fun resolveString(runtime: MoLangRuntime): String {
|
||||
return expression?.resolveString(runtime) ?: raw.toString()
|
||||
}
|
||||
|
||||
fun resolveBoolean(runtime: MoLangRuntime): Boolean {
|
||||
return expression?.resolveBoolean(runtime) ?: when (raw) {
|
||||
is Boolean -> raw
|
||||
is Number -> raw.toDouble() != 0.0
|
||||
is String -> raw.toBooleanStrictOrNull() ?: (raw.isNotEmpty())
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
fun resolveInt(runtime: MoLangRuntime): Int {
|
||||
if (expression == null && raw is String && raw.startsWith("0x", ignoreCase = true)) {
|
||||
return raw.substring(2).toLongOrNull(16)?.toInt() ?: 0
|
||||
}
|
||||
return resolveDouble(runtime).toInt()
|
||||
}
|
||||
|
||||
fun resolveFloat(runtime: MoLangRuntime): Float = resolveDouble(runtime).toFloat()
|
||||
|
||||
companion object {
|
||||
fun literal(value: Any): WidgetProperty = WidgetProperty(value, null)
|
||||
fun molang(source: String): WidgetProperty = WidgetProperty(source, source)
|
||||
|
||||
private fun parseNumericString(value: String): Double {
|
||||
value.toDoubleOrNull()?.let { return it }
|
||||
if (value.startsWith("0x", ignoreCase = true)) {
|
||||
value.substring(2).toLongOrNull(16)?.let { return it.toDouble() }
|
||||
}
|
||||
return 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class WidgetExpression(val source: String)
|
||||
@@ -1,195 +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.molangui.widget
|
||||
|
||||
import com.cobblemon.mod.common.api.molangui.layout.SizeExpression
|
||||
import com.cobblemon.mod.common.api.molangui.ActionKey
|
||||
import com.cobblemon.mod.common.api.molangui.requireUiString
|
||||
import com.cobblemon.mod.common.api.molangui.template.TemplateDefinition
|
||||
import com.cobblemon.mod.common.api.molangui.template.TemplateInput
|
||||
import com.cobblemon.mod.common.api.molangui.template.TemplateInputType
|
||||
import com.cobblemon.mod.common.api.molangui.template.TemplateResolver
|
||||
import com.google.gson.JsonElement
|
||||
import com.google.gson.JsonObject
|
||||
|
||||
object WidgetTree {
|
||||
const val MAX_DEPTH = 32
|
||||
const val MAX_NODES = 2048
|
||||
private val UNSUPPORTED_PROPERTIES = setOf(
|
||||
"transition", "enter", "exit", "static", "on_submit", "on_submit_client", "on_slot_change", "on_slot_change_client"
|
||||
)
|
||||
private val EVENT_NAMES = setOf(
|
||||
"on_click", "on_change", "on_hover_enter", "on_hover_exit", "on_scroll", "on_key"
|
||||
)
|
||||
|
||||
fun parse(guiJson: JsonObject): WidgetDefinition {
|
||||
val localTemplates = parseLocalTemplates(guiJson)
|
||||
val rootJson = guiJson.getAsJsonObject("root")
|
||||
?: throw IllegalArgumentException("UI definition is missing 'root'")
|
||||
val resolved = TemplateResolver.resolve(rootJson, localTemplates)
|
||||
val ids = mutableSetOf<String>()
|
||||
val count = intArrayOf(0)
|
||||
return parseWidget("root", resolved, ids, 1, count)
|
||||
}
|
||||
|
||||
fun parseWidget(id: String, json: JsonObject): WidgetDefinition =
|
||||
parseWidget(id, json, mutableSetOf(), 1, intArrayOf(0))
|
||||
|
||||
private fun parseWidget(
|
||||
id: String,
|
||||
json: JsonObject,
|
||||
ids: MutableSet<String>,
|
||||
depth: Int,
|
||||
count: IntArray
|
||||
): WidgetDefinition {
|
||||
require(id.isNotBlank() && id.length <= 128) { "invalid widget id '$id'" }
|
||||
require(ids.add(id)) { "duplicate widget id '$id'" }
|
||||
require(depth <= MAX_DEPTH) { "widget tree exceeds maximum depth $MAX_DEPTH at '$id'" }
|
||||
count[0]++
|
||||
require(count[0] <= MAX_NODES) { "widget tree exceeds maximum node count $MAX_NODES" }
|
||||
|
||||
val typeName = json.get("type")?.asString ?: "panel"
|
||||
val type = WidgetType.fromId(typeName)
|
||||
?: throw IllegalArgumentException("unsupported widget renderer '$typeName' at '$id'")
|
||||
val properties = linkedMapOf<String, WidgetProperty>()
|
||||
val events = linkedMapOf<String, ServerWidgetEvent>()
|
||||
val clientEvents = linkedMapOf<String, String>()
|
||||
var hoverOverrides = emptyMap<String, WidgetProperty>()
|
||||
val reserved = setOf("type", "controls", "item_template", "hover", "inputs", "extends")
|
||||
json.entrySet().forEach { (key, value) ->
|
||||
require(key !in UNSUPPORTED_PROPERTIES) { "unsupported widget property '$id.$key'" }
|
||||
when {
|
||||
key.endsWith("_client") && key.removeSuffix("_client") in EVENT_NAMES ->
|
||||
clientEvents[key] = readExpression(value, "$id.$key")
|
||||
key in EVENT_NAMES -> {
|
||||
events[key] = parseServerEvent(value, "$id.$key")
|
||||
}
|
||||
key == "hover" && value.isJsonObject -> hoverOverrides = parsePropertyMap(value.asJsonObject, "$id.hover")
|
||||
key !in reserved -> properties[key] = parseProperty(value, "$id.$key")
|
||||
}
|
||||
}
|
||||
|
||||
val children = mutableListOf<WidgetDefinition>()
|
||||
json.getAsJsonArray("controls")?.forEach { element ->
|
||||
require(element.isJsonObject && element.asJsonObject.size() == 1) { "controls under '$id' must be single-entry objects" }
|
||||
val (childId, childValue) = element.asJsonObject.entrySet().single()
|
||||
require(childValue.isJsonObject) { "widget '$childId' must be an object" }
|
||||
children += parseWidget(childId, childValue.asJsonObject, ids, depth + 1, count)
|
||||
}
|
||||
|
||||
val itemTemplate = json.getAsJsonObject("item_template")?.let { template ->
|
||||
parseWidget("$id#item_template", template, ids, depth + 1, count)
|
||||
}
|
||||
validateGeometry(id, type, properties)
|
||||
return WidgetDefinition(
|
||||
id, type, properties.toMap(), children.toList(), events.toMap(), clientEvents.toMap(),
|
||||
hoverOverrides.toMap(), itemTemplate
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseLocalTemplates(guiJson: JsonObject): Map<String, TemplateDefinition> {
|
||||
val result = linkedMapOf<String, TemplateDefinition>()
|
||||
guiJson.getAsJsonObject("templates")?.entrySet()?.forEach { (name, element) ->
|
||||
val body = element.asJsonObject
|
||||
val inputs = linkedMapOf<String, TemplateInput>()
|
||||
body.getAsJsonObject("inputs")?.entrySet()?.forEach { (inputName, inputElement) ->
|
||||
val input = inputElement.asJsonObject
|
||||
val type = TemplateInputType.fromId(input.get("type")?.asString ?: "string")
|
||||
?: throw IllegalArgumentException("unknown template input type at '$name.$inputName'")
|
||||
val default = input.get("default")
|
||||
require(default == null || type.accepts(default)) { "invalid template default at '$name.$inputName'" }
|
||||
inputs[inputName] = TemplateInput(type, default)
|
||||
}
|
||||
result[name] = TemplateDefinition(name, "", inputs.toMap(), body.get("extends")?.asString, body)
|
||||
}
|
||||
return result.toMap()
|
||||
}
|
||||
|
||||
private fun parsePropertyMap(json: JsonObject, path: String) = json.entrySet().associate { (key, value) ->
|
||||
key to parseProperty(value, "$path.$key")
|
||||
}
|
||||
|
||||
private fun parseProperty(value: JsonElement, path: String): WidgetProperty {
|
||||
if (value.isJsonObject && value.asJsonObject.has("molang")) {
|
||||
require(value.asJsonObject.size() == 1) {
|
||||
"expression '$path' must contain only a string 'molang' field"
|
||||
}
|
||||
return WidgetProperty.molang(value.asJsonObject.get("molang").requireUiString("$path.molang"))
|
||||
}
|
||||
return WidgetProperty.literal(jsonToLiteral(value, path))
|
||||
}
|
||||
|
||||
private fun jsonToLiteral(element: JsonElement, path: String): Any = when {
|
||||
element.isJsonPrimitive -> element.asJsonPrimitive.let { when {
|
||||
it.isNumber -> it.asDouble.also { number -> require(number.isFinite()) { "non-finite number at '$path'" } }
|
||||
it.isBoolean -> it.asBoolean
|
||||
else -> it.asString
|
||||
} }
|
||||
element.isJsonArray -> element.asJsonArray.mapIndexed { index, item ->
|
||||
if (item.isJsonObject && item.asJsonObject.has("molang")) {
|
||||
require(item.asJsonObject.size() == 1) { "expression '$path[$index]' contains unknown fields" }
|
||||
WidgetExpression(item.asJsonObject.get("molang").requireUiString("$path[$index].molang"))
|
||||
} else jsonToLiteral(item, "$path[$index]")
|
||||
}.toList()
|
||||
element.isJsonObject -> element.asJsonObject.entrySet().associate { (key, item) -> key to jsonToLiteral(item, "$path.$key") }.toMap()
|
||||
else -> throw IllegalArgumentException("null is not a supported widget value at '$path'")
|
||||
}
|
||||
|
||||
private fun readExpression(element: JsonElement, path: String): String {
|
||||
require(element.isJsonObject && element.asJsonObject.size() == 1) { "client event '$path' must be an explicit molang object" }
|
||||
return element.asJsonObject.get("molang").requireUiString("$path.molang").also {
|
||||
require(!it.contains("send_action")) { "client event '$path' may not dispatch server actions" }
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseServerEvent(element: JsonElement, path: String): ServerWidgetEvent {
|
||||
if (element.isJsonPrimitive && element.asJsonPrimitive.isString) {
|
||||
val action = element.asString
|
||||
require(action.startsWith("action@") && action.length > 7) { "server event '$path' must declare exactly one action" }
|
||||
return ServerWidgetEvent(ActionKey(action.substringAfter("action@")))
|
||||
}
|
||||
require(element.isJsonObject) { "server event '$path' must be an object" }
|
||||
val obj = element.asJsonObject
|
||||
val action = ActionKey(obj.get("action")?.asString
|
||||
?: throw IllegalArgumentException("server event '$path' is missing action"))
|
||||
val parameters = obj.getAsJsonObject("parameters")?.entrySet()?.associate { (name, value) ->
|
||||
name to parseProperty(value, "$path.parameters.$name")
|
||||
}?.toMap() ?: emptyMap()
|
||||
require(obj.keySet().all { it == "action" || it == "parameters" }) { "server event '$path' contains unknown fields" }
|
||||
return ServerWidgetEvent(action, parameters)
|
||||
}
|
||||
|
||||
private fun validateGeometry(id: String, type: WidgetType, properties: Map<String, WidgetProperty>) {
|
||||
listOf("size", "offset", "grid_dimensions", "slot_size", "slot_spacing").forEach { key ->
|
||||
val raw = properties[key]?.raw ?: return@forEach
|
||||
require(raw is List<*> && raw.size == 2) { "'$id.$key' must contain exactly two values" }
|
||||
raw.filterIsInstance<Double>().forEach { require(it.isFinite()) { "non-finite geometry at '$id.$key'" } }
|
||||
}
|
||||
listOf("size", "offset").forEach { key ->
|
||||
(properties[key]?.raw as? List<*>)?.forEach { SizeExpression.parse(requireNotNull(it)) }
|
||||
}
|
||||
properties["padding"]?.raw?.let { padding ->
|
||||
require(padding is List<*> && padding.size == 4 && padding.all { it is Number || it is WidgetExpression }) {
|
||||
"'$id.padding' must contain four numbers or explicit Molang expressions"
|
||||
}
|
||||
padding.filterIsInstance<Number>().forEach {
|
||||
require(it.toFloat().isFinite() && it.toFloat() >= 0f) { "invalid padding at '$id'" }
|
||||
}
|
||||
}
|
||||
if (type == WidgetType.SLOT_GRID) {
|
||||
val dimensions = properties["grid_dimensions"]?.raw as? List<*>
|
||||
?: throw IllegalArgumentException("slot grid '$id' is missing grid_dimensions")
|
||||
require(dimensions.all { it is Double && it in 1.0..16.0 && it == it.toInt().toDouble() }) {
|
||||
"slot grid '$id' must have integer dimensions in 1..16"
|
||||
}
|
||||
val collectionName = properties["collection_name"]?.raw
|
||||
require(collectionName is String && collectionName.isNotBlank()) { "slot grid '$id' is missing collection_name" }
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user