mirror of
https://gitlab.com/cable-mc/cobblemon.git
synced 2026-11-21 07:38:54 -05:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cb1cdceb6 | ||
|
|
603db456b0 | ||
|
|
6fb19ccd0b | ||
|
|
aebe2bb2d9 | ||
|
|
c11f2b15d9 | ||
|
|
50eefd5307 | ||
|
|
9fa3cd86af | ||
|
|
27494bb654 | ||
|
|
3aa7e72839 | ||
|
|
4be4da58c0 | ||
|
|
5b60a822ef | ||
|
|
7457827f27 | ||
|
|
39030fa18d | ||
|
|
01f720e274 |
No files matched your search
@@ -25,7 +25,6 @@ object CobblemonCommands {
|
||||
ChangeWalkSpeed.register(dispatcher)
|
||||
ChangeJointScaleCommand.register(dispatcher)
|
||||
TestCommand.register(dispatcher)
|
||||
ReloadShowdownCommand.register(dispatcher)
|
||||
ClickTextCommand.register(dispatcher)
|
||||
PokemonEditCommand.register(dispatcher)
|
||||
TeachCommand.register(dispatcher)
|
||||
@@ -68,4 +67,4 @@ object CobblemonCommands {
|
||||
CobblemonInfoCommand.register(dispatcher)
|
||||
CalculateSeatPositionCommand.register(dispatcher)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import com.cobblemon.mod.common.client.net.callback.party.OpenPartyCallbackHandl
|
||||
import com.cobblemon.mod.common.client.net.callback.partymove.OpenPartyMoveCallbackHandler
|
||||
import com.cobblemon.mod.common.client.net.data.DataRegistrySyncPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.data.UnlockReloadPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.debug.showdown.ShowdownRefreshInfoHandler
|
||||
import com.cobblemon.mod.common.client.net.dialogue.DialogueClosedHandler
|
||||
import com.cobblemon.mod.common.client.net.dialogue.DialogueOpenedHandler
|
||||
import com.cobblemon.mod.common.client.net.effect.RunPosableMoLangHandler
|
||||
@@ -48,14 +49,7 @@ import com.cobblemon.mod.common.client.net.storage.party.SetPartyPokemonHandler
|
||||
import com.cobblemon.mod.common.client.net.storage.party.SetPartyReferenceHandler
|
||||
import com.cobblemon.mod.common.client.net.storage.pc.*
|
||||
import com.cobblemon.mod.common.client.net.toast.ToastPacketHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeAcceptanceChangedHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeCancelledHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeCompletedHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeOfferExpiredHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeOfferNotificationHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeProcessStartedHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeStartedHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.TradeUpdatedHandler
|
||||
import com.cobblemon.mod.common.client.net.trade.*
|
||||
import com.cobblemon.mod.common.net.PacketRegisterInfo
|
||||
import com.cobblemon.mod.common.net.messages.client.CalculateSeatPositionsPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.PlayerInteractOptionsPacket
|
||||
@@ -66,6 +60,7 @@ import com.cobblemon.mod.common.net.messages.client.callback.OpenMoveCallbackPac
|
||||
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyCallbackPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyMoveCallbackPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.data.*
|
||||
import com.cobblemon.mod.common.net.messages.client.debug.showdown.ShowdownRefreshInfoPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueClosedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueOpenedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.effect.RunPosableMoLangPacket
|
||||
@@ -96,42 +91,18 @@ import com.cobblemon.mod.common.net.messages.client.storage.party.InitializePart
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.party.MoveClientPartyPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.party.SetPartyPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.party.SetPartyReferencePacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.ClosePCPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.InitializePCPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.MoveClientPCPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.OpenPCPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.RenamePCBoxPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.SetPCBoxPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.SetPCPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.*
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.wallpaper.ChangePCBoxWallpaperPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.wallpaper.RequestPCBoxWallpapersPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.wallpaper.SetPCBoxWallpapersPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.storage.pc.wallpaper.UnlockPCBoxWallpaperPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.toast.ToastPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeAcceptanceChangedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeCancelledPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeCompletedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeOfferExpiredPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeOfferNotificationPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeProcessStartedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeStartedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.TradeUpdatedPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.trade.*
|
||||
import com.cobblemon.mod.common.net.messages.client.ui.InteractPokemonUIPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.ui.PokedexUIPacket
|
||||
import com.cobblemon.mod.common.net.messages.client.ui.SummaryUIPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.BattleChallengePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.BattleChallengeResponsePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.BenchMovePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.RequestMoveSwapPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.RequestPlayerInteractionsPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.SelectStarterPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.SendOutPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.battle.BattleSelectActionsPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.battle.BattleTeamLeavePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.battle.BattleTeamRequestPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.battle.BattleTeamResponsePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.battle.RemoveSpectatorPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.battle.SpectateBattlePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.*
|
||||
import com.cobblemon.mod.common.net.messages.server.battle.*
|
||||
import com.cobblemon.mod.common.net.messages.server.block.AdjustBlockEntityViewerCountPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectCancelledPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectedPacket
|
||||
@@ -139,6 +110,9 @@ import com.cobblemon.mod.common.net.messages.server.callback.party.PartyPokemonS
|
||||
import com.cobblemon.mod.common.net.messages.server.callback.party.PartySelectCancelledPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.callback.partymove.PartyMoveSelectCancelledPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.callback.partymove.PartyPokemonMoveSelectedPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.RequestShowdownInfoPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.ShowdownActionPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.ShowdownInputPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.dialogue.EscapeDialoguePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.dialogue.InputToDialoguePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.npc.SaveNPCPacket
|
||||
@@ -158,21 +132,11 @@ import com.cobblemon.mod.common.net.messages.server.storage.party.MovePartyPokem
|
||||
import com.cobblemon.mod.common.net.messages.server.storage.party.ReleasePartyPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.storage.party.SwapPartyPokemonPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.storage.pc.*
|
||||
import com.cobblemon.mod.common.net.messages.server.trade.AcceptTradeRequestPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.trade.CancelTradePacket
|
||||
import com.cobblemon.mod.common.net.messages.server.trade.ChangeTradeAcceptancePacket
|
||||
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.messages.server.trade.*
|
||||
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.battle.BattleSelectActionsHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.RemoveSpectatorHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.SpectateBattleHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.TeamLeaveHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.TeamRequestHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.TeamRequestResponseHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.battle.*
|
||||
import com.cobblemon.mod.common.net.serverhandling.block.AdjustBlockEntityViewerCountHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectCancelledHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectedHandler
|
||||
@@ -180,6 +144,9 @@ import com.cobblemon.mod.common.net.serverhandling.callback.party.PartyPokemonSe
|
||||
import com.cobblemon.mod.common.net.serverhandling.callback.party.PartySelectCancelledHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.callback.partymove.PartyMoveSelectCancelledHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.callback.partymove.PartyPokemonMoveSelectedHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.debug.showdown.RequestShowdownInfoHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.debug.showdown.ShowdownActionHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.debug.showdown.ShowdownInputHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.dialogue.EscapeDialogueHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.dialogue.InputToDialogueHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.evolution.AcceptEvolutionHandler
|
||||
@@ -203,12 +170,7 @@ import com.cobblemon.mod.common.net.serverhandling.storage.party.MovePartyPokemo
|
||||
import com.cobblemon.mod.common.net.serverhandling.storage.party.ReleasePCPokemonHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.storage.party.SwapPartyPokemonHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.storage.pc.*
|
||||
import com.cobblemon.mod.common.net.serverhandling.trade.AcceptTradeRequestHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.trade.CancelTradeHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.trade.ChangeTradeAcceptanceHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.trade.OfferTradeHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.trade.PerformTradeHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.trade.UpdateTradeOfferHandler
|
||||
import com.cobblemon.mod.common.net.serverhandling.trade.*
|
||||
import com.cobblemon.mod.common.util.server
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
@@ -412,6 +374,7 @@ object CobblemonNetwork {
|
||||
|
||||
// Debug / cheats
|
||||
list.add(PacketRegisterInfo(CalculateSeatPositionsPacket.ID, CalculateSeatPositionsPacket::decode, CalculateSeatPositionsHandler))
|
||||
list.add(PacketRegisterInfo(ShowdownRefreshInfoPacket.ID, ShowdownRefreshInfoPacket::decode, ShowdownRefreshInfoHandler))
|
||||
|
||||
return list
|
||||
}
|
||||
@@ -511,6 +474,11 @@ object CobblemonNetwork {
|
||||
// Orientation packet(s)
|
||||
list.add(PacketRegisterInfo(C2SUpdateOrientationPacket.ID, C2SUpdateOrientationPacket::decode, OrientationPacketHandler))
|
||||
|
||||
// Debug / cheats
|
||||
list.add(PacketRegisterInfo(RequestShowdownInfoPacket.ID, RequestShowdownInfoPacket::decode, RequestShowdownInfoHandler))
|
||||
list.add(PacketRegisterInfo(ShowdownInputPacket.ID, ShowdownInputPacket::decode, ShowdownInputHandler))
|
||||
list.add(PacketRegisterInfo(ShowdownActionPacket.ID, ShowdownActionPacket::decode, ShowdownActionHandler))
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ object Abilities : DataRegistry {
|
||||
PotentialAbility.types.add(CommonAbilityType)
|
||||
PotentialAbility.types.add(HiddenAbilityType)
|
||||
this.abilityMap.clear()
|
||||
val abilitiesJson = ShowdownService.service.getAbilityIds()
|
||||
val abilitiesJson = ShowdownService.get().getAbilityIds()
|
||||
for (i in 0 until abilitiesJson.size()) {
|
||||
val id = abilitiesJson[i].asString
|
||||
val ability = AbilityTemplate(id)
|
||||
@@ -67,4 +67,4 @@ object Abilities : DataRegistry {
|
||||
abilities.forEach { ability -> this.register(ability) }
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -15,10 +15,7 @@ import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.Cobblemon.LOGGER
|
||||
import com.cobblemon.mod.common.CobblemonNetwork
|
||||
import com.cobblemon.mod.common.api.battles.interpreter.BattleMessage
|
||||
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.battles.model.actor.FleeableBattleActor
|
||||
import com.cobblemon.mod.common.api.battles.model.actor.*
|
||||
import com.cobblemon.mod.common.api.events.CobblemonEvents
|
||||
import com.cobblemon.mod.common.api.events.battles.BattleFledEvent
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
|
||||
@@ -74,7 +71,9 @@ import net.minecraft.world.item.ItemStack
|
||||
open class PokemonBattle(
|
||||
val format: BattleFormat,
|
||||
val side1: BattleSide,
|
||||
val side2: BattleSide
|
||||
val side2: BattleSide,
|
||||
val service: ShowdownService = ShowdownService.get(),
|
||||
val battleId: UUID = UUID.randomUUID()
|
||||
) {
|
||||
/** Whether logging will be silenced for this battle. */
|
||||
var mute = true
|
||||
@@ -109,8 +108,6 @@ open class PokemonBattle(
|
||||
val players = playerUUIDs.mapNotNull { it.getPlayer() }
|
||||
val spectators = mutableSetOf<UUID>()
|
||||
|
||||
val battleId = UUID.randomUUID()
|
||||
|
||||
val showdownMessages = mutableListOf<String>()
|
||||
val battleLog = mutableListOf<String>()
|
||||
val chatLog = mutableListOf<Component>()
|
||||
@@ -225,7 +222,7 @@ open class PokemonBattle(
|
||||
|
||||
fun writeShowdownAction(vararg messages: String) {
|
||||
log(messages.joinToString("\n"))
|
||||
ShowdownService.service.send(battleId, messages.toList().toTypedArray())
|
||||
service.send(battleId, messages.toList().toTypedArray())
|
||||
}
|
||||
|
||||
fun turn(newTurnNumber: Int) {
|
||||
@@ -378,7 +375,6 @@ open class PokemonBattle(
|
||||
|
||||
fun dispatch(dispatcher: () -> DispatchResult) {
|
||||
dispatches.add(BattleDispatch { dispatcher() })
|
||||
|
||||
}
|
||||
|
||||
fun dispatchToFront(dispatcher: () -> DispatchResult) {
|
||||
@@ -502,6 +498,7 @@ open class PokemonBattle(
|
||||
}
|
||||
|
||||
fun checkForInputDispatch() {
|
||||
actors.filter { it is UnionBattleActor }.forEach { it.mustChoose = false }
|
||||
if (checkForfeit()) return // ignore actors that are still choosing, their choices don't matter anymore
|
||||
val readyToInput = (actors.any { !it.mustChoose && it.responses.isNotEmpty() } && actors.none { it.mustChoose })
|
||||
if (readyToInput && captureActions.isEmpty()) {
|
||||
@@ -558,4 +555,4 @@ open class PokemonBattle(
|
||||
queryStruct.addFunction("has_rule") { params -> DoubleValue(params.getString(0) in format.ruleSet) }
|
||||
return queryStruct
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -42,4 +42,4 @@ abstract class AIBattleActor(
|
||||
setActionResponses(request!!.iterate(this.activePokemon) { _, _, _ -> PassActionResponse })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -73,7 +73,7 @@ abstract class BattleActor(
|
||||
open fun isForPlayer(serverPlayerEntity: ServerPlayer) = serverPlayerEntity.uuid in getPlayerUUIDs()
|
||||
open fun isForPokemon(pokemonEntity: PokemonEntity) = activePokemon.any { it.battlePokemon?.effectedPokemon?.entity == pokemonEntity }
|
||||
|
||||
fun turn() {
|
||||
open fun turn() {
|
||||
val request = request ?: return
|
||||
responses.clear()
|
||||
if(activePokemon.any { it.isAlive() }) {
|
||||
@@ -90,7 +90,7 @@ abstract class BattleActor(
|
||||
}
|
||||
}
|
||||
|
||||
fun upkeep() {
|
||||
open fun upkeep() {
|
||||
val request = request ?: return
|
||||
val forceSwitchPokemon = request.forceSwitch.mapIndexedNotNull { index, b -> if (b) activePokemon[index] else null }
|
||||
if (forceSwitchPokemon.isEmpty()) {
|
||||
@@ -125,7 +125,7 @@ abstract class BattleActor(
|
||||
battle.checkForInputDispatch()
|
||||
}
|
||||
|
||||
fun writeShowdownResponse() {
|
||||
open fun writeShowdownResponse() {
|
||||
val showdownMessages = mutableListOf<String>()
|
||||
var index = 0
|
||||
request!!.iterate(activePokemon) { activeBattlePokemon, showdownMoveSet, forceSwitch ->
|
||||
@@ -159,4 +159,4 @@ abstract class BattleActor(
|
||||
|
||||
open fun win(otherWinners: List<BattleActor>, losers: List<BattleActor>) {}
|
||||
open fun lose(winners: List<BattleActor>, otherLosers: List<BattleActor>) {}
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.cobblemon.mod.common.api.battles.model.actor
|
||||
|
||||
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
|
||||
import com.cobblemon.mod.common.entity.npc.NPCBattleActor
|
||||
import com.cobblemon.mod.common.entity.npc.NPCEntity
|
||||
|
||||
class UnionBattleActor(npc: NPCEntity, pokemonList: List<BattlePokemon>) : NPCBattleActor(npc, pokemonList.toMutableList(), 1) {
|
||||
|
||||
override fun writeShowdownResponse() {}
|
||||
|
||||
override fun onChoiceRequested() {
|
||||
this.mustChoose = false
|
||||
}
|
||||
|
||||
override fun turn() {
|
||||
super.turn()
|
||||
this.mustChoose = false
|
||||
}
|
||||
|
||||
override fun upkeep() {
|
||||
super.upkeep()
|
||||
this.mustChoose = false
|
||||
}
|
||||
|
||||
}
|
||||
@@ -41,7 +41,6 @@ import com.cobblemon.mod.common.api.pokemon.PokemonProperties
|
||||
import com.cobblemon.mod.common.api.pokemon.evolution.Evolution
|
||||
import com.cobblemon.mod.common.api.pokemon.stats.Stats
|
||||
import com.cobblemon.mod.common.api.riding.RidingStyle
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.RidingAltPose
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
|
||||
import com.cobblemon.mod.common.api.spawning.context.SpawningContext
|
||||
@@ -509,7 +508,6 @@ object MoLangFunctions {
|
||||
map.put("world") { _ -> entity.level().worldRegistry.wrapAsHolder(entity.level()).asWorldMoLangValue() }
|
||||
map.put("biome") { _ -> entity.level().getBiome(entity.blockPosition()).asBiomeMoLangValue() }
|
||||
map.put("is_passenger") { DoubleValue(entity.isPassenger) }
|
||||
map.put("has_passenger") { DoubleValue(entity.passengers.size > 0) }
|
||||
map.put("find_nearby_block") { params ->
|
||||
val type = params.getString(0).asIdentifierDefaultingNamespace(namespace = "minecraft")
|
||||
val isTag = type.path.startsWith("#")
|
||||
@@ -790,17 +788,7 @@ object MoLangFunctions {
|
||||
map.put("in_battle") { DoubleValue(pokemonEntity.isBattling) }
|
||||
map.put("is_moving") { DoubleValue((pokemonEntity.moveControl as? PokemonMoveControl)?.hasWanted() == true) }
|
||||
map.put("is_flying") { DoubleValue(pokemonEntity.getBehaviourFlag(PokemonBehaviourFlag.FLYING)) }
|
||||
map.put("riding_alt_pose") { params ->
|
||||
val poseName = params.getString(0).uppercase()
|
||||
val targetPose = RidingAltPose.fromString(poseName)
|
||||
if (targetPose == null) {
|
||||
//Invalid pose name
|
||||
DoubleValue(0.0)
|
||||
} else {
|
||||
val currentPose = pokemonEntity.getActiveRidingAltPose()
|
||||
DoubleValue(if (currentPose == targetPose) 1.0 else 0.0)
|
||||
}
|
||||
}
|
||||
map.put("is_gliding") { DoubleValue(pokemonEntity.useRidingAltPose()) }
|
||||
map.put("has_aspect") { DoubleValue(it.getString(0) in pokemonEntity.aspects) }
|
||||
map.put("is_pokemon") { DoubleValue.ONE }
|
||||
map.put("is_holding_item") { DoubleValue(!pokemonEntity.entityData.get(PokemonEntity.SHOWN_HELD_ITEM).isEmpty) }
|
||||
|
||||
@@ -40,7 +40,7 @@ object Moves : DataRegistry {
|
||||
override fun reload(manager: ResourceManager) {
|
||||
this.allMoves.clear()
|
||||
this.idMapping.clear()
|
||||
val movesJson = ShowdownService.service.getMoves()
|
||||
val movesJson = ShowdownService.get().getMoves()
|
||||
for (i in 0 until movesJson.size()) {
|
||||
val jsMove = movesJson[i].asJsonObject
|
||||
val id = jsMove.get("id").asString
|
||||
@@ -116,4 +116,4 @@ object Moves : DataRegistry {
|
||||
this.idMapping[move.num] = move
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -13,17 +13,13 @@ import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.RidingAltPose
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.api.riding.util.Vec3Spring
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.util.toProperties
|
||||
import com.cobblemon.mod.common.util.withQueryValue
|
||||
import com.mojang.authlib.minecraft.client.MinecraftClient
|
||||
import net.minecraft.ChatFormatting
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.util.Mth
|
||||
import net.minecraft.util.SmoothDouble
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.player.Player
|
||||
@@ -36,16 +32,6 @@ data class RidingManager(val entity: PokemonEntity) {
|
||||
var lastSpeed = 0F
|
||||
var states: MutableMap<ResourceLocation, RidingState> = mutableMapOf()
|
||||
var deltaRotation = Vec2.ZERO
|
||||
var deltaRotationPerSec = Vec2.ZERO
|
||||
|
||||
//Riding animation data
|
||||
var prevRotation = Vec3.ZERO
|
||||
var rotSpring = Vec3Spring()
|
||||
var rotDeltaSpring = Vec3Spring()
|
||||
var velSpring = Vec3Spring()
|
||||
val stiffness = 90.0
|
||||
val damping = 19.0
|
||||
|
||||
|
||||
val runtime: MoLangRuntime by lazy {
|
||||
MoLangRuntime()
|
||||
@@ -91,28 +77,12 @@ data class RidingManager(val entity: PokemonEntity) {
|
||||
|
||||
val pose = controller.pose(entity)
|
||||
entity.entityData.set(PokemonEntity.POSE_TYPE, pose)
|
||||
|
||||
// maybe here I do the required updates for riding animation stuff.
|
||||
val rollable = driver as? Rollable ?: return
|
||||
|
||||
val r = this.shouldRoll(entity)
|
||||
val currYaw = if(r) rollable.yaw else entity.yRot
|
||||
val currPitch = if(r) rollable.pitch else entity.xRot
|
||||
val currRoll = rollable.roll
|
||||
|
||||
|
||||
val angDelta = Vec3(
|
||||
Mth.degreesDifference(currPitch.toFloat(), prevRotation.x.toFloat()).toDouble(),
|
||||
Mth.degreesDifference(currYaw.toFloat(), prevRotation.y.toFloat()).toDouble(),
|
||||
Mth.degreesDifference(currRoll.toFloat(), prevRotation.z.toFloat()).toDouble()
|
||||
)
|
||||
|
||||
rotSpring.update(Vec3(currPitch.toDouble(), currYaw.toDouble(), currRoll.toDouble()), stiffness, damping)
|
||||
|
||||
rotDeltaSpring.update( angDelta, stiffness, damping)
|
||||
|
||||
prevRotation = Vec3(currPitch.toDouble(), currYaw .toDouble(), currRoll.toDouble())
|
||||
|
||||
//val speedPlayer = driver.deltaMovement.horizontalDistance()
|
||||
//driver.displayClientMessage(Component.literal("Speed player: ").withStyle { it.withColor(ChatFormatting.GREEN) }.append(Component.literal("$speedPlayer b/t")), true)
|
||||
//val speedEntity = entity.deltaMovement.length() //* 20 * 60 * 60) / ( 1000 )
|
||||
//println(speedEntity)
|
||||
//driver.displayClientMessage(Component.literal("Speed: ").withStyle { it.withColor(ChatFormatting.GREEN) }.append(Component.literal("${String.format("%.2f", speedEntity)} km/h")), true)
|
||||
|
||||
}
|
||||
|
||||
fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
@@ -126,8 +96,6 @@ data class RidingManager(val entity: PokemonEntity) {
|
||||
val previousRotation = entity.rotationVector
|
||||
val rotation = controller.rotation(entity, driver)
|
||||
this.deltaRotation = Vec2(rotation.x - previousRotation.x, rotation.y - previousRotation.y)
|
||||
|
||||
this.deltaRotationPerSec = deltaRotation.scale(20.0f)
|
||||
return rotation
|
||||
}
|
||||
|
||||
@@ -143,8 +111,6 @@ data class RidingManager(val entity: PokemonEntity) {
|
||||
|
||||
fun velocity(entity: PokemonEntity, driver: Player, input: Vec3): Vec3 {
|
||||
val controller = getController(entity) ?: return Vec3.ZERO
|
||||
|
||||
this.velSpring.update(entity.deltaMovement, stiffness, damping)
|
||||
return controller.velocity(entity, driver, input)
|
||||
}
|
||||
|
||||
@@ -168,9 +134,9 @@ data class RidingManager(val entity: PokemonEntity) {
|
||||
return controller.jumpForce(entity, driver, jumpStrength)
|
||||
}
|
||||
|
||||
fun getActiveRidingAltPose(entity: PokemonEntity, driver: Player): RidingAltPose {
|
||||
val controller = getController(entity) ?: return RidingAltPose.NONE
|
||||
return controller.getActiveRidingAltPose(entity, driver)
|
||||
fun useRidingAltPose(entity: PokemonEntity, driver: Player): Boolean {
|
||||
val controller = getController(entity) ?: return false
|
||||
return controller.useRidingAltPose(entity, driver)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
|
||||
package com.cobblemon.mod.common.api.riding
|
||||
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
/**
|
||||
* Honestly having a base interface is probably unnecessary I'm just considering whether there's going to be some
|
||||
* kind of shared state later.
|
||||
@@ -17,7 +15,4 @@ import net.minecraft.world.phys.Vec3
|
||||
* @author Hiroku
|
||||
* @since October 6th, 2024
|
||||
*/
|
||||
interface RidingState {
|
||||
var rideVel: Vec3
|
||||
var stamina: Float
|
||||
}
|
||||
interface RidingState
|
||||
+1
-13
@@ -8,18 +8,14 @@
|
||||
|
||||
package com.cobblemon.mod.common.api.riding.controller
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.net.Decodable
|
||||
import com.cobblemon.mod.common.api.net.Encodable
|
||||
import com.cobblemon.mod.common.api.riding.RidingState
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.RidingAltPose
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.util.asExpression
|
||||
import com.cobblemon.mod.common.util.writeIdentifier
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
@@ -58,14 +54,6 @@ interface RideController : Encodable, Decodable {
|
||||
*/
|
||||
val condition: (PokemonEntity) -> Boolean
|
||||
|
||||
|
||||
/**
|
||||
* Returns the evaluation of the current stat when mapped to the given molang expression
|
||||
* that the controller implements. For composite controllers the active controller will
|
||||
* be determined rather than it evaluating its own expression.
|
||||
*/
|
||||
fun getStat(entity: PokemonEntity, stat: RidingStat): Double
|
||||
|
||||
/**
|
||||
* Specifies the pose the ridden mount should be positioned in. This queries the pose provider using
|
||||
* the entity as a means of determining the conditions the entity is currently under. This allows for
|
||||
@@ -123,7 +111,7 @@ interface RideController : Encodable, Decodable {
|
||||
|
||||
fun useAngVelSmoothing(entity: PokemonEntity): Boolean = false
|
||||
|
||||
fun getActiveRidingAltPose(entity: PokemonEntity, driver: Player): RidingAltPose = RidingAltPose.NONE
|
||||
fun useRidingAltPose(entity: PokemonEntity, driver: Player): Boolean = false
|
||||
|
||||
//If function is not overwritten by controllers then just perform the defualt
|
||||
//rolling function which is roll on mousex and pitch on mousey
|
||||
|
||||
-29
@@ -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.riding.controller.posing
|
||||
|
||||
/**
|
||||
* The pose that will be used to determine if an alternate pose should be used while riding.
|
||||
*
|
||||
* @author Jackowes
|
||||
* @since March 23rd, 2025
|
||||
*/
|
||||
enum class RidingAltPose {
|
||||
NONE,
|
||||
GLIDING,
|
||||
SPRINTING,
|
||||
BRAKING,
|
||||
JUMPING;
|
||||
|
||||
companion object {
|
||||
fun fromString(name: String): RidingAltPose? {
|
||||
return entries.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.riding.util
|
||||
|
||||
import net.minecraft.world.phys.Vec3
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* A spring-based smoother for Vec3 values, designed for applying damped spring motion to riding data.
|
||||
* Stores the previous and current values, along with a history buffer for lookback-based interpolation.
|
||||
*
|
||||
* @author Jackowes
|
||||
* @since March 27th, 2025
|
||||
*/
|
||||
|
||||
|
||||
class Vec3Spring(
|
||||
var value: Vec3 = Vec3.ZERO,
|
||||
var velocity: Vec3 = Vec3.ZERO
|
||||
) {
|
||||
val history = ArrayDeque<Vec3>()
|
||||
//Hold up to a seconds worth of values
|
||||
val lookBackSize = 20
|
||||
|
||||
fun update(target: Vec3, stiffness: Double, damping: Double) {
|
||||
|
||||
//Hooke's Law f = kx where:
|
||||
//f is force
|
||||
//k is the spring constant or stiffness of this spring
|
||||
//x is the distance from rest and in this case the difference between the most recent
|
||||
//rotation delta ( the target ) and the springs current value for delta rot
|
||||
val force = target.subtract(value).scale(stiffness)
|
||||
|
||||
//Now calculate acceleration and apply damping
|
||||
val accel = force.subtract(velocity.scale(damping))
|
||||
|
||||
velocity = velocity.add(accel.scale(1.0/20.0))
|
||||
value = value.add(velocity.scale(1.0/20.0))
|
||||
|
||||
history.addFirst(value)
|
||||
//Adding one since if we want to check max look back point it needs something to interp with.
|
||||
if( history.size > lookBackSize + 1) {
|
||||
history.removeLast()
|
||||
}
|
||||
}
|
||||
|
||||
fun getInterpolated(partialTick: Double, lookBackTick: Int): Vec3 {
|
||||
if (history.size < 2) {
|
||||
return value.scale(20.0) // or Vec3.ZERO if you prefer
|
||||
}
|
||||
|
||||
val tick = min(lookBackTick, history.size - 2)
|
||||
val sprev = history.get(tick + 1).scale(20.0)
|
||||
val svalue = history.get(tick).scale(20.0)
|
||||
return sprev.add(svalue.subtract(sprev).scale(partialTick))
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import com.cobblemon.mod.common.api.storage.party.PlayerPartyStore
|
||||
import com.cobblemon.mod.common.battles.actor.PlayerBattleActor
|
||||
import com.cobblemon.mod.common.battles.actor.PokemonBattleActor
|
||||
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.entity.npc.NPCBattleActor
|
||||
import com.cobblemon.mod.common.entity.npc.NPCEntity
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
@@ -59,7 +60,9 @@ object BattleBuilder {
|
||||
battleFormat: BattleFormat = BattleFormat.GEN_9_SINGLES,
|
||||
cloneParties: Boolean = false,
|
||||
healFirst: Boolean = false,
|
||||
partyAccessor: (ServerPlayer) -> PartyStore = { it.party() }
|
||||
partyAccessor: (ServerPlayer) -> PartyStore = { it.party() },
|
||||
service: ShowdownService = ShowdownService.get(),
|
||||
battleId: UUID = UUID.randomUUID()
|
||||
): BattleStartResult {
|
||||
|
||||
val adjustLevel = battleFormat.adjustLevel
|
||||
@@ -116,7 +119,9 @@ object BattleBuilder {
|
||||
BattleRegistry.startBattle(
|
||||
battleFormat = battleFormat,
|
||||
side1 = BattleSide(player1Actor),
|
||||
side2 = BattleSide(player2Actor)
|
||||
side2 = BattleSide(player2Actor),
|
||||
service = service,
|
||||
battleId = battleId
|
||||
).ifSuccessful {
|
||||
it.battlePartyStores.addAll(battlePartyStores)
|
||||
}
|
||||
@@ -132,7 +137,9 @@ object BattleBuilder {
|
||||
battleFormat: BattleFormat = BattleFormat.GEN_9_MULTI,
|
||||
cloneParties: Boolean = false,
|
||||
healFirst: Boolean = false,
|
||||
partyAccessor: (ServerPlayer) -> PartyStore = { it.party() }
|
||||
partyAccessor: (ServerPlayer) -> PartyStore = { it.party() },
|
||||
service: ShowdownService = ShowdownService.get(),
|
||||
battleId: UUID = UUID.randomUUID()
|
||||
): BattleStartResult {
|
||||
val adjustLevel = battleFormat.adjustLevel
|
||||
val teams = players.mapIndexed { index, it ->
|
||||
@@ -213,7 +220,9 @@ object BattleBuilder {
|
||||
BattleRegistry.startBattle(
|
||||
battleFormat = battleFormat,
|
||||
side1 = BattleSide(playerActors[0], playerActors[1]),
|
||||
side2 = BattleSide(playerActors[2], playerActors[3])
|
||||
side2 = BattleSide(playerActors[2], playerActors[3]),
|
||||
service = service,
|
||||
battleId = battleId
|
||||
).ifSuccessful {
|
||||
it.battlePartyStores.addAll(battlePartyStores)
|
||||
}
|
||||
@@ -245,7 +254,9 @@ object BattleBuilder {
|
||||
cloneParties: Boolean = false,
|
||||
healFirst: Boolean = false,
|
||||
fleeDistance: Float = Cobblemon.config.defaultFleeDistance,
|
||||
party: PartyStore = player.party()
|
||||
party: PartyStore = player.party(),
|
||||
service: ShowdownService = ShowdownService.get(),
|
||||
battleId: UUID = UUID.randomUUID()
|
||||
): BattleStartResult {
|
||||
val playerTeam = party.toBattleTeam(clone = cloneParties, healPokemon = healFirst, leadingPokemon = leadingPokemon).sortedBy { it.health <= 0 }
|
||||
val playerActor = PlayerBattleActor(player.uuid, playerTeam)
|
||||
@@ -286,7 +297,9 @@ object BattleBuilder {
|
||||
BattleRegistry.startBattle(
|
||||
battleFormat = battleFormat,
|
||||
side1 = BattleSide(playerActor),
|
||||
side2 = BattleSide(wildActor)
|
||||
side2 = BattleSide(wildActor),
|
||||
service = service,
|
||||
battleId = battleId
|
||||
).ifSuccessful {
|
||||
if (!cloneParties) {
|
||||
pokemonEntity.battleId = it.battleId
|
||||
@@ -316,7 +329,9 @@ object BattleBuilder {
|
||||
battleFormat: BattleFormat = BattleFormat.GEN_9_SINGLES,
|
||||
cloneParties: Boolean = false,
|
||||
healFirst: Boolean = false,
|
||||
party: PartyStore = player.party()
|
||||
party: PartyStore = player.party(),
|
||||
service: ShowdownService = ShowdownService.get(),
|
||||
battleId: UUID = UUID.randomUUID()
|
||||
): BattleStartResult {
|
||||
val playerTeam = party.toBattleTeam(clone = cloneParties, healPokemon = healFirst, leadingPokemon = leadingPokemon)
|
||||
val playerActor = PlayerBattleActor(player.uuid, playerTeam)
|
||||
@@ -363,7 +378,9 @@ object BattleBuilder {
|
||||
BattleRegistry.startBattle(
|
||||
battleFormat = battleFormat,
|
||||
side1 = BattleSide(playerActor),
|
||||
side2 = BattleSide(npcActor)
|
||||
side2 = BattleSide(npcActor),
|
||||
service = service,
|
||||
battleId = battleId
|
||||
).ifSuccessful { battle ->
|
||||
npcEntity.entityData.update(NPCEntity.BATTLE_IDS) { it + battle.battleId }
|
||||
}
|
||||
@@ -537,4 +554,4 @@ open class ErroredBattleStart(
|
||||
|
||||
val errors: Iterable<BattleStartError>
|
||||
get() = generalErrors + participantErrors.flatMap { it.value }
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ object BattleRegistry {
|
||||
return team.joinToString("]")
|
||||
}
|
||||
|
||||
private fun startShowdown(battle: PokemonBattle) {
|
||||
private fun startShowdown(battle: PokemonBattle, sendMessages: Boolean = true) {
|
||||
|
||||
// Build request message
|
||||
val messages = mutableListOf<String>()
|
||||
@@ -176,7 +176,9 @@ object BattleRegistry {
|
||||
}
|
||||
|
||||
// Compiles the request and sends it off
|
||||
ShowdownService.service.startBattle(battle, messages.toTypedArray())
|
||||
if (sendMessages) {
|
||||
battle.service.startBattle(battle, messages.toTypedArray())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,6 +188,7 @@ object BattleRegistry {
|
||||
* @param side1 The first side for the battle.
|
||||
* @param side2 The second side for the battle.
|
||||
* @param canPreempt Whether the battle can be blocked by subscribers to [CobblemonEvents.BATTLE_STARTED_PRE].
|
||||
* @param service The showdown service to use for the battle.
|
||||
*
|
||||
* NOTE: this does NOT validate the [battleFormat] or sides before launching Showdown.
|
||||
* This creates the battle and hands it off to Showdown - YOU WILL GET ISSUES IF THE BATTLE IS INVALID!
|
||||
@@ -195,12 +198,15 @@ object BattleRegistry {
|
||||
battleFormat: BattleFormat,
|
||||
side1: BattleSide,
|
||||
side2: BattleSide,
|
||||
canPreempt: Boolean = true
|
||||
canPreempt: Boolean = true,
|
||||
service: ShowdownService = ShowdownService.get(),
|
||||
battleId: UUID = UUID.randomUUID(),
|
||||
sendMessages: Boolean = true
|
||||
): BattleStartResult {
|
||||
val battle = PokemonBattle(battleFormat, side1, side2)
|
||||
val battle = PokemonBattle(battleFormat, side1, side2, service, battleId)
|
||||
val start: () -> Unit = {
|
||||
battleMap[battle.battleId] = battle
|
||||
startShowdown(battle)
|
||||
startShowdown(battle, sendMessages)
|
||||
}
|
||||
|
||||
if (!canPreempt) start().also { return SuccessfulBattleStart(battle) }
|
||||
@@ -234,4 +240,4 @@ object BattleRegistry {
|
||||
fun tick() {
|
||||
battleMap.forEachValue(Long.MAX_VALUE) { it.tick() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,13 +23,13 @@ class ShowdownThread : Thread("Cobblemon Showdown") {
|
||||
this.start()
|
||||
this.latch.await()
|
||||
for (action in whenReady) {
|
||||
action(ShowdownService.service)
|
||||
action(ShowdownService.get())
|
||||
}
|
||||
}
|
||||
|
||||
fun queue(action: (ShowdownService) -> Unit) {
|
||||
if (this.latch.count == 0L) {
|
||||
action(ShowdownService.service)
|
||||
action(ShowdownService.get())
|
||||
} else {
|
||||
this.whenReady.add(action)
|
||||
}
|
||||
@@ -37,8 +37,8 @@ class ShowdownThread : Thread("Cobblemon Showdown") {
|
||||
|
||||
override fun run() {
|
||||
LOGGER.info("Starting showdown service...")
|
||||
ShowdownService.service.openConnection()
|
||||
ShowdownService.get().openConnection()
|
||||
LOGGER.info("Showdown has been started!")
|
||||
this.latch.countDown()
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -49,4 +49,4 @@ class RequestInstruction(val battleActor: BattleActor, val message: BattleMessag
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.cobblemon.mod.common.battles.runner
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
|
||||
/**
|
||||
* Class responsible for logging debug messages for the showdown service.
|
||||
*
|
||||
* @author landonjw
|
||||
*/
|
||||
class ShowdownDebugLog {
|
||||
val log = mutableListOf<LogMessage>()
|
||||
|
||||
/**
|
||||
* Adds a log message to the debug log.
|
||||
*
|
||||
* @param source The source of the log message.
|
||||
* @param message The log message.
|
||||
*/
|
||||
fun add(source: String, message: String) {
|
||||
if (!Cobblemon.config.enableDebugKeys) return
|
||||
val now = Date()
|
||||
val timestamp = SimpleDateFormat("HH:mm:ss").format(now)
|
||||
log.add(LogMessage("[$source][${timestamp}]> $message", now))
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all log messages from the debug log.
|
||||
*/
|
||||
fun clear() {
|
||||
log.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves log messages after a specified date.
|
||||
*
|
||||
* @param after The date after which to retrieve log messages. If null, retrieves the last 250 messages.
|
||||
* @return A list of log messages.
|
||||
*/
|
||||
fun get(after: Date?): List<String> {
|
||||
if (after == null) return log.take(250).map { it.message }
|
||||
return log.filter { it.time.after(after) }.map { it.message }
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the provided messages are the start of the log.
|
||||
*
|
||||
* @param messages The messages to check.
|
||||
* @return True if the messages are the start of the log, false otherwise.
|
||||
*/
|
||||
fun isStartOfLog(messages: List<String>): Boolean {
|
||||
if (messages.isEmpty() && log.isEmpty()) return true
|
||||
return messages.size == log.size && messages.first() == log.first().message
|
||||
}
|
||||
|
||||
/**
|
||||
* Data class representing a log message.
|
||||
*
|
||||
* @property message The log message.
|
||||
* @property time The time the log message was created.
|
||||
*/
|
||||
data class LogMessage(val message: String, val time: Date)
|
||||
}
|
||||
@@ -10,32 +10,154 @@ package com.cobblemon.mod.common.battles.runner
|
||||
|
||||
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
|
||||
import com.cobblemon.mod.common.battles.runner.graal.GraalShowdownService
|
||||
import com.cobblemon.mod.common.battles.runner.remote.UnionShowdownService
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.google.gson.JsonArray
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Mediator service for communicating between the Cobblemon Minecraft mod and Cobblemon showdown service.
|
||||
*
|
||||
* All outgoing calls to showdown should be done through this layer to decouple the mod from a specific implementation.
|
||||
* To get an instance of the service, use the singleton provided via `ShowdownService.get()`
|
||||
* To get an instance of the service, use the singleton provided via `ShowdownService.get()`.
|
||||
*
|
||||
* @since February 27th, 2023
|
||||
* @author landonjw
|
||||
*/
|
||||
interface ShowdownService {
|
||||
/**
|
||||
* The unique identifier for this showdown service.
|
||||
*/
|
||||
val id: ResourceLocation
|
||||
|
||||
/**
|
||||
* The current status of the showdown service.
|
||||
*/
|
||||
val status: ShowdownStatus
|
||||
|
||||
/**
|
||||
* The log of messages from the showdown service.
|
||||
* This is accessed for use in [ShowdownDebugGUI]. It is not intended for general use
|
||||
* and will be empty in production environments.
|
||||
*/
|
||||
val log: ShowdownDebugLog
|
||||
|
||||
/**
|
||||
* Opens a connection to the showdown service.
|
||||
*/
|
||||
fun openConnection()
|
||||
|
||||
/**
|
||||
* Closes the connection to the showdown service.
|
||||
*/
|
||||
fun closeConnection()
|
||||
|
||||
/**
|
||||
* Restarts the connection to the showdown service.
|
||||
*/
|
||||
fun restartConnection()
|
||||
|
||||
/**
|
||||
* Starts a battle in the showdown service.
|
||||
*
|
||||
* @param battle The battle to start.
|
||||
* @param messages The initial messages for the battle.
|
||||
*/
|
||||
fun startBattle(battle: PokemonBattle, messages: Array<String>)
|
||||
|
||||
/**
|
||||
* Sends messages to a specific battle in the showdown service.
|
||||
*
|
||||
* @param battleId The unique identifier of the battle.
|
||||
* @param messages The messages to send.
|
||||
*/
|
||||
fun send(battleId: UUID, messages: Array<String>)
|
||||
|
||||
/**
|
||||
* Sends a message to the showdown service.
|
||||
*
|
||||
* @param message The message to send.
|
||||
*/
|
||||
fun send(message: String)
|
||||
|
||||
/**
|
||||
* Retrieves the ability IDs from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of ability IDs.
|
||||
*/
|
||||
fun getAbilityIds(): JsonArray
|
||||
|
||||
/**
|
||||
* Retrieves the moves from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of moves.
|
||||
*/
|
||||
fun getMoves(): JsonArray
|
||||
|
||||
/**
|
||||
* Retrieves the item IDs from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of item IDs.
|
||||
*/
|
||||
fun getItemIds(): JsonArray
|
||||
|
||||
/**
|
||||
* Registers species in the showdown service.
|
||||
*/
|
||||
fun registerSpecies()
|
||||
|
||||
/**
|
||||
* Registers bag items in the showdown service.
|
||||
*/
|
||||
fun registerBagItems()
|
||||
|
||||
/**
|
||||
* Indicates that species have been initialized in the showdown service.
|
||||
*/
|
||||
fun indicateSpeciesInitialized() {}
|
||||
|
||||
|
||||
companion object {
|
||||
val service: ShowdownService by lazy { GraalShowdownService() }
|
||||
private val services = mutableMapOf<ResourceLocation, ShowdownService>(
|
||||
cobblemonResource("embedded") to GraalShowdownService(cobblemonResource("embedded")),
|
||||
cobblemonResource("union") to UnionShowdownService(cobblemonResource("union"))
|
||||
)
|
||||
|
||||
/**
|
||||
* Retrieves the showdown service for the specified path.
|
||||
*
|
||||
* @param path The resource location of the showdown service.
|
||||
* @return The showdown service.
|
||||
* @throws IllegalStateException if no showdown service is found for the specified path.
|
||||
*/
|
||||
fun get(path: ResourceLocation = cobblemonResource("embedded")): ShowdownService {
|
||||
return services[path] ?: error("No showdown service found for path $path")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a showdown service exists for the specified path.
|
||||
*
|
||||
* @param path The resource location of the showdown service.
|
||||
* @return `true` if the showdown service exists, `false` otherwise.
|
||||
*/
|
||||
fun contains(path: ResourceLocation): Boolean {
|
||||
return services.containsKey(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all available showdown services.
|
||||
*
|
||||
* @return A list of all showdown services.
|
||||
*/
|
||||
fun all(): List<ShowdownService> {
|
||||
return services.values.toList()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enum representing the status of the showdown service.
|
||||
*/
|
||||
enum class ShowdownStatus {
|
||||
CONNECTED, DISCONNECTED, RESTARTING
|
||||
}
|
||||
+152
-4
@@ -13,9 +13,12 @@ import com.cobblemon.mod.common.api.battles.model.PokemonBattle
|
||||
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
|
||||
import com.cobblemon.mod.common.battles.BagItems
|
||||
import com.cobblemon.mod.common.battles.ShowdownInterpreter
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownDebugLog
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownStatus
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonArray
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.URI
|
||||
@@ -38,12 +41,20 @@ import org.graalvm.polyglot.io.FileSystem
|
||||
* Mediator service for communicating between the Cobblemon Minecraft mod and Cobblemon showdown service via
|
||||
* GraalVM. This directly invokes JavaScript functions provided within the showdown service.
|
||||
*
|
||||
* @property id The unique identifier for this showdown service.
|
||||
* @property context The GraalVM context for executing JavaScript.
|
||||
* @property sendBattleMessageFunction The JavaScript function for sending battle messages.
|
||||
* @property unbundler The unbundler for extracting necessary showdown files.
|
||||
* @property gson The Gson instance for JSON operations.
|
||||
* @property log The debug log for the showdown service.
|
||||
* @property status The current status of the showdown service.
|
||||
*
|
||||
* @see {@code cobbled-exports/cobbled-index.js} within cobbledmon-showdown repository
|
||||
* @see <a href="https://www.graalvm.org/">
|
||||
* @since February 27, 2023
|
||||
* @author Hiroku, landonjw
|
||||
*/
|
||||
class GraalShowdownService : ShowdownService {
|
||||
class GraalShowdownService(override val id: ResourceLocation) : ShowdownService {
|
||||
|
||||
@Transient
|
||||
lateinit var context: Context
|
||||
@@ -54,12 +65,35 @@ class GraalShowdownService : ShowdownService {
|
||||
@Transient
|
||||
val gson = Gson()
|
||||
|
||||
override fun openConnection() {
|
||||
override val log = ShowdownDebugLog()
|
||||
|
||||
override var status: ShowdownStatus = ShowdownStatus.DISCONNECTED
|
||||
private set
|
||||
|
||||
/**
|
||||
* Opens a connection to the showdown service.
|
||||
*/
|
||||
override fun openConnection() = openConnection(false)
|
||||
|
||||
/**
|
||||
* Opens a connection to the showdown service.
|
||||
*
|
||||
* @param silent If true, suppresses changing the status of the connection process.
|
||||
*/
|
||||
private fun openConnection(silent: Boolean) {
|
||||
log.clear()
|
||||
log.add(source = "Minecraft", message = "Opening showdown connection")
|
||||
unbundler.attemptUnbundle()
|
||||
createContext()
|
||||
boot()
|
||||
if (!silent) {
|
||||
status = ShowdownStatus.CONNECTED
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the GraalVM context for executing JavaScript.
|
||||
*/
|
||||
private fun createContext() {
|
||||
val wd = Paths.get("./showdown")
|
||||
val access = HostAccess.newBuilder(HostAccess.EXPLICIT)
|
||||
@@ -116,42 +150,126 @@ class GraalShowdownService : ShowdownService {
|
||||
""".trimIndent())
|
||||
}
|
||||
|
||||
override fun closeConnection() {
|
||||
/**
|
||||
* Closes the connection to the showdown service.
|
||||
*/
|
||||
override fun closeConnection() = closeConnection(false)
|
||||
|
||||
/**
|
||||
* Closes the connection to the showdown service.
|
||||
*
|
||||
* @param silent If true, suppresses changing the status of the connection process.
|
||||
*/
|
||||
private fun closeConnection(silent: Boolean) {
|
||||
log.add(source = "Minecraft", message = "Closing showdown connection")
|
||||
context.close()
|
||||
if (!silent) {
|
||||
this.status = ShowdownStatus.DISCONNECTED
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts the connection to the showdown service.
|
||||
*/
|
||||
override fun restartConnection() {
|
||||
this.status = ShowdownStatus.RESTARTING
|
||||
try {
|
||||
closeConnection(true)
|
||||
openConnection(true)
|
||||
this.status = ShowdownStatus.CONNECTED
|
||||
} catch (e: Exception) {
|
||||
Cobblemon.LOGGER.error("Failed to restart showdown connection", e)
|
||||
this.status = ShowdownStatus.DISCONNECTED
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Boots the showdown service by evaluating the JavaScript entry point.
|
||||
*/
|
||||
private fun boot() {
|
||||
log.add(source = "Minecraft", message = "Booting showdown")
|
||||
context.eval("js", File("showdown/index.js").readText())
|
||||
sendBattleMessageFunction = context.getBindings("js").getMember("sendBattleMessage")
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a battle in the showdown service.
|
||||
*
|
||||
* @param battle The battle to start.
|
||||
* @param messages The initial messages for the battle.
|
||||
*/
|
||||
override fun startBattle(battle: PokemonBattle, messages: Array<String>) {
|
||||
val startBattleFunction = context.getBindings("js").getMember("startBattle")
|
||||
log.add(source = "Minecraft", message = "Starting battle ${battle.battleId}")
|
||||
messages.forEach { message ->
|
||||
log.add(source = "Minecraft", message = "(${battle.battleId}) $message")
|
||||
}
|
||||
startBattleFunction.execute(this, battle.battleId.toString(), messages)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends messages to a specific battle in the showdown service.
|
||||
*
|
||||
* @param battleId The unique identifier of the battle.
|
||||
* @param messages The messages to send.
|
||||
*/
|
||||
override fun send(battleId: UUID, messages: Array<String>) {
|
||||
sendToShowdown(battleId, messages)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the showdown service.
|
||||
*
|
||||
* @param message The message to send.
|
||||
*/
|
||||
override fun send(message: String) {
|
||||
log.add("Minecraft", message)
|
||||
val regex = Regex("^\\(([^()]*)\\)")
|
||||
val match = regex.find(message)
|
||||
val battleId = match?.groups?.get(1)?.value ?: return
|
||||
val endIndex = match.groups[1]!!.range.last + 1
|
||||
sendToShowdown(UUID.fromString(battleId), arrayOf(message.substring(endIndex)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the ability IDs from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of ability IDs.
|
||||
*/
|
||||
override fun getAbilityIds(): JsonArray {
|
||||
val getCobbledAbilityIdsFn = context.getBindings("js").getMember("getCobbledAbilityIds")
|
||||
val arrayResult = getCobbledAbilityIdsFn.execute().asString()
|
||||
log.add(source = "Minecraft", message = "Getting ability ids")
|
||||
return gson.fromJson(arrayResult, JsonArray::class.java)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the moves from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of moves.
|
||||
*/
|
||||
override fun getMoves(): JsonArray {
|
||||
val getCobbledMovesFn = context.getBindings("js").getMember("getCobbledMoves")
|
||||
log.add(source = "Minecraft", message = "Getting moves")
|
||||
val arrayResult = getCobbledMovesFn.execute().asString()
|
||||
return gson.fromJson(arrayResult, JsonArray::class.java)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the item IDs from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of item IDs.
|
||||
*/
|
||||
override fun getItemIds(): JsonArray {
|
||||
val getCobbledItemIdsFn = context.getBindings("js").getMember("getCobbledItemIds")
|
||||
log.add(source = "Minecraft", message = "Getting item ids")
|
||||
val arrayResult = getCobbledItemIdsFn.execute().asString()
|
||||
return gson.fromJson(arrayResult, JsonArray::class.java)
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers species in the showdown service.
|
||||
*/
|
||||
override fun registerSpecies() {
|
||||
val receiveSpeciesDataFn = this.context.getBindings("js").getMember("receiveSpeciesData")
|
||||
val jsArray = this.context.eval("js", "new Array();")
|
||||
@@ -164,32 +282,62 @@ class GraalShowdownService : ShowdownService {
|
||||
}
|
||||
}
|
||||
}
|
||||
log.add(source = "Minecraft", message = "Registering species")
|
||||
receiveSpeciesDataFn.execute(jsArray)
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates that species have been initialized to the showdown service.
|
||||
*/
|
||||
override fun indicateSpeciesInitialized() {
|
||||
val afterCobbledSpeciesInitFn = this.context.getBindings("js").getMember("afterCobbledSpeciesInit")
|
||||
log.add(source = "Minecraft", message = "Indicating species initialized")
|
||||
afterCobbledSpeciesInitFn.execute()
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers bag items in the showdown service.
|
||||
*/
|
||||
override fun registerBagItems() {
|
||||
val receiveBagItemDataFn = this.context.getBindings("js").getMember("receiveBagItemData")
|
||||
for ((itemId, js) in BagItems.bagItemsScripts) {
|
||||
log.add(source = "Minecraft", message = "Registering bag item $itemId")
|
||||
receiveBagItemDataFn.execute(itemId, js.replace("\n", " "))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends messages to the showdown service.
|
||||
*
|
||||
* @param battleId The unique identifier of the battle.
|
||||
* @param messages The messages to send.
|
||||
*/
|
||||
private fun sendToShowdown(battleId: UUID, messages: Array<String>) {
|
||||
messages.forEach { message ->
|
||||
log.add(source = "Minecraft", message = "($battleId) $message")
|
||||
}
|
||||
sendBattleMessageFunction.execute(battleId.toString(), messages)
|
||||
}
|
||||
|
||||
/**
|
||||
* Receives messages from the showdown service.
|
||||
*
|
||||
* @param battleId The unique identifier of the battle.
|
||||
* @param message The message received.
|
||||
*/
|
||||
@Export
|
||||
fun sendFromShowdown(battleId: String, message: String) {
|
||||
log.add(source = "Showdown", message = "($battleId) $message")
|
||||
ShowdownInterpreter.interpretMessage(UUID.fromString(battleId), message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs messages from the showdown service.
|
||||
*
|
||||
* @param message The message to log.
|
||||
*/
|
||||
@Export
|
||||
fun log(message: String) {
|
||||
Cobblemon.LOGGER.info(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
package com.cobblemon.mod.common.battles.runner.remote
|
||||
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
|
||||
import com.cobblemon.mod.common.api.battles.model.actor.UnionBattleActor
|
||||
import com.cobblemon.mod.common.api.npc.NPCClasses
|
||||
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
|
||||
import com.cobblemon.mod.common.api.storage.party.PartyStore
|
||||
import com.cobblemon.mod.common.api.text.text
|
||||
import com.cobblemon.mod.common.battles.*
|
||||
import com.cobblemon.mod.common.battles.actor.PlayerBattleActor
|
||||
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownDebugLog
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownStatus
|
||||
import com.cobblemon.mod.common.entity.npc.NPCEntity
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.util.HttpService
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.server
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.JsonParser
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.world.entity.schedule.Activity
|
||||
import java.net.URI
|
||||
import java.net.http.HttpClient
|
||||
import java.net.http.WebSocket
|
||||
import java.util.*
|
||||
import java.util.concurrent.CompletionStage
|
||||
|
||||
/**
|
||||
* Implementation of the ShowdownService interface for use with the Union Block.
|
||||
*
|
||||
* This wraps around a WebSocket connection to a remote showdown service.
|
||||
*
|
||||
* @property id The unique identifier for this showdown service.
|
||||
* @property host The host address of the showdown service.
|
||||
* @property httpPort The port for HTTP communication with the showdown service.
|
||||
* @property socketPort The port for WebSocket communication with the showdown service.
|
||||
*
|
||||
* @author landonjw
|
||||
*/
|
||||
class UnionShowdownService(
|
||||
override val id: ResourceLocation,
|
||||
val host: String = "localhost",
|
||||
val httpPort: Int = 8003,
|
||||
val socketPort: Int = 8002
|
||||
) : ShowdownService {
|
||||
|
||||
override var status: ShowdownStatus = ShowdownStatus.DISCONNECTED
|
||||
private set
|
||||
|
||||
override val log = ShowdownDebugLog()
|
||||
|
||||
private lateinit var webSocket: WebSocket
|
||||
|
||||
/**
|
||||
* Opens a connection to the showdown service.
|
||||
*/
|
||||
override fun openConnection() = openConnection(false)
|
||||
|
||||
/**
|
||||
* Opens a connection to the showdown service.
|
||||
*
|
||||
* @param silent If true, suppresses changing the status of the connection process.
|
||||
*/
|
||||
private fun openConnection(silent: Boolean) {
|
||||
log.clear()
|
||||
log.add(source = "Minecraft", message = "Opening showdown connection")
|
||||
try {
|
||||
webSocket = HttpClient.newHttpClient()
|
||||
.newWebSocketBuilder()
|
||||
.buildAsync(URI.create("ws://$host:$socketPort"), WebSocketListener(this))
|
||||
.join()
|
||||
// TODO: See if this is needed
|
||||
registerSpecies()
|
||||
indicateSpeciesInitialized()
|
||||
registerBagItems()
|
||||
if (!silent) {
|
||||
this.status = ShowdownStatus.CONNECTED
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Cobblemon.LOGGER.warn("Failed to open showdown connection to $host:$socketPort", e)
|
||||
log.add(source = "Minecraft", message = "Failed to open showdown connection with error: ${e.message}")
|
||||
if (!silent) {
|
||||
this.status = ShowdownStatus.DISCONNECTED
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection to the showdown service.
|
||||
*/
|
||||
override fun closeConnection() = closeConnection(false)
|
||||
|
||||
/**
|
||||
* Closes the connection to the showdown service.
|
||||
*
|
||||
* @param silent If true, suppresses changing the status of the disconnection process.
|
||||
*/
|
||||
private fun closeConnection(silent: Boolean) {
|
||||
log.add(source = "Minecraft", message = "Closing showdown connection")
|
||||
try {
|
||||
webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "Goodbye!").join()
|
||||
} catch (e: Exception) {
|
||||
Cobblemon.LOGGER.warn("Failed to close showdown connection to $host:$socketPort", e)
|
||||
log.add(source = "Minecraft", message = "Failed to close showdown connection to $host:$socketPort with error: ${e.message}")
|
||||
}
|
||||
finally {
|
||||
if (!silent) {
|
||||
this.status = ShowdownStatus.DISCONNECTED
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts the connection to the showdown service.
|
||||
*/
|
||||
override fun restartConnection() {
|
||||
this.status = ShowdownStatus.RESTARTING
|
||||
closeConnection(true)
|
||||
openConnection(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a battle in the showdown service.
|
||||
*
|
||||
* @param battle The battle to start.
|
||||
* @param messages The initial messages for the battle.
|
||||
*/
|
||||
override fun startBattle(battle: PokemonBattle, messages: Array<String>) {
|
||||
send("[${battle.battleId}]>start-battle")
|
||||
send(battle.battleId, messages)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends messages to a specific battle in the showdown service.
|
||||
*
|
||||
* @param battleId The unique identifier of the battle.
|
||||
* @param messages The messages to send.
|
||||
*/
|
||||
override fun send(battleId: UUID, messages: Array<String>) {
|
||||
messages.forEach { send("[$battleId]$it") }
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the showdown service.
|
||||
*
|
||||
* @param message The message to send.
|
||||
*/
|
||||
override fun send(message: String) {
|
||||
webSocket.sendText(message, true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the ability IDs from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of ability IDs.
|
||||
*/
|
||||
override fun getAbilityIds(): JsonArray {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the moves from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of moves.
|
||||
*/
|
||||
override fun getMoves(): JsonArray {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the item IDs from the showdown service.
|
||||
*
|
||||
* @return A `JsonArray` of item IDs.
|
||||
*/
|
||||
override fun getItemIds(): JsonArray {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers species in the showdown service.
|
||||
*/
|
||||
override fun registerSpecies() {
|
||||
HttpService.post<Unit>(
|
||||
url = "http://$host:$httpPort/Species",
|
||||
body = PokemonSpecies.species.map { PokemonSpecies.ShowdownSpecies(it, null) }
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers bag items in the showdown service.
|
||||
*/
|
||||
override fun registerBagItems() {
|
||||
HttpService.post<Unit>(
|
||||
url = "http://$host:$httpPort/BagItems",
|
||||
body = BagItems.bagItemsScripts.map { BagItem(it.key, it.value) }.toList()
|
||||
)
|
||||
}
|
||||
|
||||
override fun indicateSpeciesInitialized() {
|
||||
HttpService.post<Unit>(url = "http://$host:$httpPort/InitializeDex")
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket listener for handling events from the showdown service.
|
||||
*
|
||||
* @property service The UnionShowdownService instance.
|
||||
*/
|
||||
class WebSocketListener(val service: UnionShowdownService) : WebSocket.Listener {
|
||||
val builder = StringBuilder()
|
||||
|
||||
override fun onOpen(webSocket: WebSocket) {
|
||||
service.log.add(source = "Showdown", message = "Connected to server at ${service.host}:${service.socketPort}")
|
||||
super.onOpen(webSocket)
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a battle based on the received instruction.
|
||||
*
|
||||
* @param instruction The instruction to start the battle.
|
||||
*/
|
||||
fun startBattle(instruction: String) {
|
||||
val arguments = instruction.replace("|start-battle|", "").split("|")
|
||||
if (arguments.size != 7) return
|
||||
val battleId = UUID.fromString(arguments[0])
|
||||
val playerIdA = UUID.fromString(arguments[1])
|
||||
val playerNameA = arguments[2]
|
||||
val playerIdB = UUID.fromString(arguments[3])
|
||||
val playerNameB = arguments[4]
|
||||
val teamA = JsonParser.parseString(arguments[5]).asJsonObject
|
||||
val teamB = JsonParser.parseString(arguments[6]).asJsonObject
|
||||
val playerA = server()?.playerList?.getPlayer(playerIdA)
|
||||
val playerB = server()?.playerList?.getPlayer(playerIdB)
|
||||
|
||||
println(arguments[5])
|
||||
println(arguments[6])
|
||||
|
||||
if (playerA == null && playerB == null) {
|
||||
Cobblemon.LOGGER.warn("Tried to start battle with no players present on server")
|
||||
return
|
||||
}
|
||||
|
||||
val registryAccess = server()?.registryAccess() ?: return
|
||||
|
||||
val playerAParty = PartyStore(UUID.randomUUID()).loadFromJSON(teamA, registryAccess)
|
||||
val playerBParty = PartyStore(UUID.randomUUID()).loadFromJSON(teamB, registryAccess)
|
||||
val playerATeam = toShowdownBattleTeam(playerAParty.toList()).onEach {
|
||||
it.effectedPokemon.level = 100
|
||||
it.effectedPokemon.heal()
|
||||
}
|
||||
val playerBTeam = toShowdownBattleTeam(playerBParty.toList()).onEach {
|
||||
it.effectedPokemon.level = 100
|
||||
it.effectedPokemon.heal()
|
||||
}
|
||||
|
||||
if (playerA != null && playerB != null) {
|
||||
val playerActorA = PlayerBattleActor(playerIdA, playerATeam)
|
||||
val playerActorB = PlayerBattleActor(playerIdB, playerBTeam)
|
||||
BattleRegistry.startBattle(
|
||||
battleId = battleId,
|
||||
battleFormat = BattleFormat.GEN_9_SINGLES,
|
||||
side1 = BattleSide(playerActorA),
|
||||
side2 = BattleSide(playerActorB),
|
||||
sendMessages = false,
|
||||
service = service
|
||||
)
|
||||
}
|
||||
else if (playerA != null && playerB == null) {
|
||||
val playerActorA = PlayerBattleActor(playerIdA, playerATeam)
|
||||
val npc = NPCEntity(playerA.level())
|
||||
npc.moveTo(playerA.x + 5, playerA.y, playerA.z, playerA.yRot, (playerA.xRot + 180f) % 360f)
|
||||
npc.npc = NPCClasses.getByIdentifier(cobblemonResource("standard"))!!
|
||||
npc.loadTextureFromGameProfileName(playerNameB)
|
||||
npc.initialize(1)
|
||||
npc.config.setDirectly("yaw", DoubleValue((playerA.xRot + 90f) % 360f))
|
||||
npc.uuid = playerIdB
|
||||
npc.customName = playerNameB.text()
|
||||
npc.isInvulnerable = true
|
||||
npc.isMovable = false
|
||||
playerA.level().addFreshEntity(npc)
|
||||
val playerActorB = UnionBattleActor(npc, playerBTeam)
|
||||
BattleRegistry.startBattle(
|
||||
battleId = battleId,
|
||||
battleFormat = BattleFormat.GEN_9_SINGLES,
|
||||
side1 = BattleSide(playerActorA),
|
||||
side2 = BattleSide(playerActorB),
|
||||
sendMessages = false,
|
||||
service = service
|
||||
)
|
||||
}
|
||||
else {
|
||||
val npc = NPCEntity(playerB!!.level())
|
||||
npc.moveTo(playerB.x + 5, playerB.y, playerB.z, playerB.yRot, (playerB.xRot + 180f) % 360f)
|
||||
npc.npc = NPCClasses.getByIdentifier(cobblemonResource("standard"))!!
|
||||
npc.loadTextureFromGameProfileName(playerNameA)
|
||||
npc.initialize(1)
|
||||
npc.uuid = playerIdA
|
||||
npc.customName = playerNameA.text()
|
||||
npc.isInvulnerable = true
|
||||
npc.isMovable = false
|
||||
npc.config.setDirectly("yaw", DoubleValue((playerB.xRot + 90f) % 360f))
|
||||
playerB.level().addFreshEntity(npc)
|
||||
val playerActorA = UnionBattleActor(npc, playerATeam)
|
||||
val playerActorB = PlayerBattleActor(playerIdB, playerBTeam)
|
||||
BattleRegistry.startBattle(
|
||||
battleId = battleId,
|
||||
battleFormat = BattleFormat.GEN_9_SINGLES,
|
||||
side1 = BattleSide(playerActorA),
|
||||
side2 = BattleSide(playerActorB),
|
||||
sendMessages = false,
|
||||
service = service
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a list of Pokemon to a list of BattlePokemon for the showdown service.
|
||||
*
|
||||
* @param team The list of Pokemon to convert.
|
||||
* @return A list of BattlePokemon.
|
||||
*/
|
||||
fun toShowdownBattleTeam(team: List<Pokemon>): List<BattlePokemon> {
|
||||
return team.map { pokemon ->
|
||||
BattlePokemon(
|
||||
originalPokemon = pokemon,
|
||||
effectedPokemon = pokemon.clone(newUUID = false),
|
||||
postBattleEntityOperation = { entity -> entity.discard() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onText(webSocket: WebSocket, data: CharSequence, last: Boolean): CompletionStage<*>? {
|
||||
if (last) {
|
||||
builder.append(data)
|
||||
val message = builder.toString()
|
||||
service.log.add(source = "Showdown", message = message)
|
||||
|
||||
if (data.startsWith("|start-battle|")) {
|
||||
startBattle(data.toString())
|
||||
}
|
||||
else {
|
||||
val battleIdRegex = Regex("^\\[([^]]+)]")
|
||||
val match = battleIdRegex.find(message) ?: return null
|
||||
|
||||
val battleId = match.groupValues[1]
|
||||
val instruction = message.replace("[$battleId]", "")
|
||||
ShowdownInterpreter.interpretMessage(UUID.fromString(battleId), instruction)
|
||||
}
|
||||
|
||||
builder.clear()
|
||||
}
|
||||
else {
|
||||
builder.append(data)
|
||||
}
|
||||
return super.onText(webSocket, data, last)
|
||||
}
|
||||
|
||||
override fun onError(webSocket: WebSocket, error: Throwable) {
|
||||
service.log.add(source = "Showdown", message = "Error: ${error.message}")
|
||||
Cobblemon.LOGGER.warn("Error in showdown service ${service.id} websocket", error)
|
||||
super.onError(webSocket, error)
|
||||
}
|
||||
|
||||
override fun onClose(webSocket: WebSocket, statusCode: Int, reason: String): CompletionStage<*>? {
|
||||
service.log.add(source = "Showdown", message = "Closed connection with status $statusCode and reason $reason")
|
||||
return super.onClose(webSocket, statusCode, reason)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Data class representing a bag item. We use this for serialization to the showdown service.
|
||||
*
|
||||
* @property id The unique identifier of the bag item.
|
||||
* @property script The script associated with the bag item.
|
||||
*/
|
||||
private data class BagItem(val id: String, val script: String)
|
||||
|
||||
}
|
||||
-169
@@ -1,169 +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.battles.runner.socket
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
|
||||
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
|
||||
import com.cobblemon.mod.common.battles.BagItems
|
||||
import com.cobblemon.mod.common.battles.ShowdownInterpreter
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.pokemon.FormData
|
||||
import com.cobblemon.mod.common.pokemon.Species
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonArray
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.InetAddress
|
||||
import java.net.Socket
|
||||
import java.nio.charset.Charset
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Mediator service for communicating between the Cobblemon Minecraft mod and Cobblemon showdown service via
|
||||
* a socket client.
|
||||
*
|
||||
* This is primarily used for debugging purposes, but could be extended in the future to provide
|
||||
* a means of connecting to a remote Showdown server. This does not provide any fault handling in the
|
||||
* event that the server goes down.
|
||||
*
|
||||
* When messages are sent to showdown, this will await a response from showdown.
|
||||
* The protocol for messages sent from showdown is <length of characters in payload><payload>,
|
||||
* and a payload length of 0 indicates that there is no response.
|
||||
*
|
||||
* @see {@code sim/cobbled-debug-server.ts} within cobblemon-showdown repository
|
||||
* @since February 27, 2023
|
||||
* @author landonjw
|
||||
*/
|
||||
class SocketShowdownService(val host: String = "localhost", val port: Int = 18468, val localPort: Int = 0) : ShowdownService {
|
||||
|
||||
private lateinit var socket: Socket
|
||||
private lateinit var writer: OutputStreamWriter
|
||||
private lateinit var reader: BufferedReader
|
||||
val gson = Gson()
|
||||
|
||||
override fun openConnection() {
|
||||
socket = Socket(InetAddress.getLocalHost(), port, InetAddress.getLocalHost(), localPort)
|
||||
writer = socket.getOutputStream().writer(charset = Charset.forName("ascii"))
|
||||
reader = BufferedReader(InputStreamReader(socket.getInputStream()))
|
||||
}
|
||||
|
||||
override fun closeConnection() {
|
||||
socket.close()
|
||||
}
|
||||
|
||||
override fun startBattle(battle: PokemonBattle, messages: Array<String>) {
|
||||
writer.write(">startbattle ${battle.battleId}\n")
|
||||
acknowledge { Cobblemon.LOGGER.error("Failed to start battle!") }
|
||||
send(battle.battleId, messages)
|
||||
}
|
||||
|
||||
override fun send(battleId: UUID, messages: Array<String>) {
|
||||
for (message in messages) {
|
||||
writer.write("$battleId~$message\n")
|
||||
writer.flush()
|
||||
readBattleInput().forEach { interpretMessage(battleId, it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun read(reader: BufferedReader, size: Int): String {
|
||||
val buffer = CharArray(size)
|
||||
while (true) {
|
||||
if(reader.read(buffer) == 0) continue
|
||||
return String(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
private fun readMessage(): String {
|
||||
val payloadSize = read(reader, 8).toInt()
|
||||
val payload = read(reader, payloadSize)
|
||||
return payload
|
||||
}
|
||||
|
||||
private fun readBattleInput(): List<String> {
|
||||
val lines = mutableListOf<String>()
|
||||
val numLines = read(reader, 8).toInt()
|
||||
if (numLines != 0) {
|
||||
for (i in 0 until numLines) {
|
||||
lines.add(readMessage())
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
private fun interpretMessage(battleId: UUID, message: String) {
|
||||
ShowdownInterpreter.interpretMessage(battleId, message)
|
||||
}
|
||||
|
||||
override fun getAbilityIds(): JsonArray {
|
||||
writer.write(">getCobbledAbilityIds")
|
||||
writer.flush()
|
||||
val response = readMessage()
|
||||
return gson.fromJson(response, JsonArray::class.java)
|
||||
}
|
||||
|
||||
override fun getMoves(): JsonArray {
|
||||
writer.write(">getCobbledMoves\n")
|
||||
writer.flush()
|
||||
val response = readMessage()
|
||||
return gson.fromJson(response, JsonArray::class.java)
|
||||
}
|
||||
|
||||
override fun getItemIds(): JsonArray {
|
||||
writer.write(">getCobbledItemIds")
|
||||
writer.flush()
|
||||
val response = readMessage()
|
||||
return gson.fromJson(response, JsonArray::class.java)
|
||||
}
|
||||
|
||||
private fun sendSpeciesData(species: Species, form: FormData?) {
|
||||
writer.write(">receiveSpeciesData ${gson.toJson(PokemonSpecies.ShowdownSpecies(species, form))}\n")
|
||||
acknowledge()
|
||||
}
|
||||
|
||||
private fun sendBagItem(itemId: String, js: String) {
|
||||
writer.write(">receiveBagItemData $itemId $js")
|
||||
acknowledge { Cobblemon.LOGGER.error("Failed to send bag item to Showdown: $itemId") }
|
||||
}
|
||||
|
||||
override fun registerSpecies() {
|
||||
writer.write(">resetSpeciesData\n")
|
||||
acknowledge()
|
||||
PokemonSpecies.species.forEach { species ->
|
||||
sendSpeciesData(species, null)
|
||||
species.forms.forEach { form ->
|
||||
if (form != species.standardForm) {
|
||||
sendSpeciesData(species, form)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun acknowledge(ifFails: () -> Unit = {}) {
|
||||
writer.flush()
|
||||
val ack = CharArray(3)
|
||||
reader.read(ack)
|
||||
if (String(ack) != "ACK") {
|
||||
ifFails()
|
||||
}
|
||||
}
|
||||
|
||||
override fun registerBagItems() {
|
||||
for ((itemId, js) in BagItems.bagItemsScripts) {
|
||||
sendBagItem(itemId, js.replace("\n", " "))
|
||||
}
|
||||
}
|
||||
|
||||
override fun indicateSpeciesInitialized() {
|
||||
writer.write(">afterCobbledSpeciesInit")
|
||||
acknowledge()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.cobblemon.mod.common.client.gui.debug
|
||||
|
||||
import com.cobblemon.mod.common.CobblemonNetwork
|
||||
import com.cobblemon.mod.common.api.text.text
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownStatus
|
||||
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
|
||||
import com.cobblemon.mod.common.client.gui.debug.ShowdownDebugGUI.Companion.activeShowdownService
|
||||
import com.cobblemon.mod.common.client.render.drawScaledText
|
||||
import com.cobblemon.mod.common.net.messages.client.debug.showdown.ShowdownRefreshInfoPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.RequestShowdownInfoPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.ShowdownActionPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.ShowdownInputPacket
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.lang
|
||||
import com.mojang.blaze3d.platform.ClipboardManager
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.client.gui.GuiGraphics
|
||||
import net.minecraft.client.gui.components.Button
|
||||
import net.minecraft.client.gui.components.EditBox
|
||||
import net.minecraft.client.gui.components.ObjectSelectionList
|
||||
import net.minecraft.client.gui.components.ObjectSelectionList.Entry
|
||||
import net.minecraft.client.gui.screens.Screen
|
||||
import net.minecraft.locale.Language
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.util.FormattedCharSequence
|
||||
import java.awt.Color
|
||||
import java.util.*
|
||||
|
||||
/**
|
||||
* GUI screen for debugging the Showdown service in the Cobblemon mod.
|
||||
* This screen allows users to view and interact with the Showdown service logs and status.
|
||||
*
|
||||
* @property status The current status of the showdown service.
|
||||
* @property service The resource location of the showdown service.
|
||||
* @property messages A list of messages from the active showdown service currently being refreshed.
|
||||
* @property availableServices A list of available showdown services. This allows the client to switch which server they are viewing.
|
||||
* @property requestProcessedAt The date and time when the request was processed.
|
||||
* @property includesStartOfLog Indicates if the messages include the start of the log.
|
||||
*
|
||||
* @author landonjw
|
||||
*/
|
||||
class ShowdownDebugGUI : Screen(lang("ui.debug.showdown")), CobblemonRenderable {
|
||||
|
||||
companion object {
|
||||
var activeShowdownService = cobblemonResource("embedded")
|
||||
private set
|
||||
}
|
||||
|
||||
private var showdownStatus: ShowdownStatus? = null
|
||||
val log = mutableListOf<String>()
|
||||
var availableServices = listOf(cobblemonResource("embedded"))
|
||||
var lastProcessedLogTime: Date? = null
|
||||
|
||||
val outputWindow = addRenderableWidget(ShowdownOutputList())
|
||||
val serviceButton = addRenderableWidget(
|
||||
Button.builder(Component.literal("Service: $activeShowdownService")) {
|
||||
cycleActiveService()
|
||||
}.bounds(10, 10, 200, 20).build()
|
||||
)
|
||||
|
||||
val startButton = addRenderableWidget(
|
||||
Button.builder(Component.literal("Start")) { button ->
|
||||
CobblemonNetwork.sendToServer(ShowdownActionPacket(
|
||||
service = activeShowdownService,
|
||||
action = ShowdownActionPacket.Action.START
|
||||
))
|
||||
}.bounds(10, 40, 50, 20).build()
|
||||
)
|
||||
|
||||
val stopButton = addRenderableWidget(
|
||||
Button.builder(Component.literal("Stop")) { button ->
|
||||
CobblemonNetwork.sendToServer(ShowdownActionPacket(
|
||||
service = activeShowdownService,
|
||||
action = ShowdownActionPacket.Action.STOP
|
||||
))
|
||||
}.bounds(70, 40, 50, 20).build()
|
||||
)
|
||||
|
||||
val restartButton = addRenderableWidget(
|
||||
Button.builder(Component.literal("Restart")) { button ->
|
||||
this.showdownStatus = ShowdownStatus.RESTARTING
|
||||
CobblemonNetwork.sendToServer(ShowdownActionPacket(
|
||||
service = activeShowdownService,
|
||||
action = ShowdownActionPacket.Action.RESTART
|
||||
))
|
||||
}.bounds(130, 40, 50, 20).build()
|
||||
)
|
||||
|
||||
val startNPCBattleButton = addRenderableWidget(
|
||||
Button.builder(Component.literal("Queue")) { button ->
|
||||
CobblemonNetwork.sendToServer(ShowdownActionPacket(
|
||||
service = activeShowdownService,
|
||||
action = ShowdownActionPacket.Action.QUEUE
|
||||
))
|
||||
}.bounds(10, 70, 100, 20).build()
|
||||
)
|
||||
|
||||
val clipboardManager = ClipboardManager()
|
||||
var timer = Timer()
|
||||
|
||||
init {
|
||||
addRenderableWidget(
|
||||
Button.builder(Component.literal("Copy to Clipboard")) Clipboard@{
|
||||
if (log.isEmpty()) return@Clipboard
|
||||
clipboardManager.setClipboard(Minecraft.getInstance().window.window, log.joinToString("\n"))
|
||||
}.bounds(170, Minecraft.getInstance().window.guiScaledHeight - 40, 100, 30).build()
|
||||
)
|
||||
|
||||
addRenderableWidget(ShowdownInputWidget(this))
|
||||
startTimer()
|
||||
}
|
||||
|
||||
/**
|
||||
* Cycles through the available showdown services.
|
||||
*/
|
||||
fun cycleActiveService() {
|
||||
if (availableServices.size == 1) return
|
||||
val currentIndex = availableServices.indexOf(activeShowdownService)
|
||||
activeShowdownService = availableServices[(currentIndex + 1) % availableServices.size]
|
||||
serviceButton.message = Component.literal("Service: $activeShowdownService")
|
||||
outputWindow.reset()
|
||||
log.clear()
|
||||
lastProcessedLogTime = null
|
||||
startTimer()
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the timer for periodically refreshing the showdown info.
|
||||
*/
|
||||
fun startTimer() {
|
||||
timer.cancel()
|
||||
timer = Timer()
|
||||
timer.schedule(object : TimerTask() {
|
||||
override fun run() {
|
||||
CobblemonNetwork.sendToServer(RequestShowdownInfoPacket(activeShowdownService, lastProcessedLogTime))
|
||||
}
|
||||
}, 0, 500)
|
||||
}
|
||||
|
||||
override fun onClose() {
|
||||
timer.cancel()
|
||||
super.onClose()
|
||||
}
|
||||
|
||||
override fun render(guiGraphics: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
|
||||
guiGraphics.fill(0, 0, width, height, Color(0, 0, 0, 100).rgb)
|
||||
super.render(guiGraphics, mouseX, mouseY, partialTick)
|
||||
if (showdownStatus != null) {
|
||||
guiGraphics.fill(
|
||||
190,
|
||||
45,
|
||||
200,
|
||||
55,
|
||||
when (showdownStatus!!) {
|
||||
ShowdownStatus.DISCONNECTED -> Color(255, 0, 0, 255).rgb
|
||||
ShowdownStatus.RESTARTING -> Color(255, 255, 0, 255).rgb
|
||||
ShowdownStatus.CONNECTED -> Color(0, 255, 0, 255).rgb
|
||||
}
|
||||
)
|
||||
drawScaledText(
|
||||
context = guiGraphics,
|
||||
text = Component.literal(showdownStatus!!.name.replaceFirstChar {
|
||||
if (it.isLowerCase()) it.titlecase(
|
||||
Locale.getDefault()
|
||||
) else it.toString()
|
||||
}),
|
||||
x = 205,
|
||||
y = 47
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes the showdown info with the data from the given packet.
|
||||
*
|
||||
* @param packet The packet containing the refreshed showdown info.
|
||||
*/
|
||||
fun refreshShowdownInfo(packet: ShowdownRefreshInfoPacket) {
|
||||
// Prevent false positives from old packets
|
||||
if (activeShowdownService != packet.service) return
|
||||
if (packet.includesStartOfLog) {
|
||||
log.clear()
|
||||
outputWindow.reset()
|
||||
}
|
||||
packet.messages.forEach {
|
||||
log.add(it)
|
||||
outputWindow.addNewEntry(it.text())
|
||||
}
|
||||
lastProcessedLogTime = packet.requestProcessedAt
|
||||
showdownStatus = packet.status
|
||||
when (showdownStatus) {
|
||||
ShowdownStatus.CONNECTED -> {
|
||||
startButton.active = false
|
||||
stopButton.active = true
|
||||
restartButton.active = true
|
||||
startNPCBattleButton.active = true
|
||||
}
|
||||
ShowdownStatus.DISCONNECTED -> {
|
||||
startButton.active = true
|
||||
stopButton.active = false
|
||||
restartButton.active = false
|
||||
startNPCBattleButton.active = false
|
||||
}
|
||||
ShowdownStatus.RESTARTING -> {
|
||||
startButton.active = false
|
||||
stopButton.active = false
|
||||
restartButton.active = false
|
||||
startNPCBattleButton.active = false
|
||||
}
|
||||
else -> {
|
||||
startButton.active = false
|
||||
stopButton.active = false
|
||||
restartButton.active = false
|
||||
startNPCBattleButton.active = false
|
||||
}
|
||||
}
|
||||
this.availableServices = packet.availableServices
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* List widget for displaying the output log of the Showdown service.
|
||||
*/
|
||||
class ShowdownOutputList : ObjectSelectionList<OutputEntry>(
|
||||
Minecraft.getInstance(),
|
||||
Minecraft.getInstance().window.guiScaledWidth - 280 - 10,
|
||||
Minecraft.getInstance().window.guiScaledHeight - 10 - 40,
|
||||
10,
|
||||
14
|
||||
) {
|
||||
/**
|
||||
* Adds a new entry to the output list.
|
||||
*
|
||||
* @param text The text to add as a new entry.
|
||||
*/
|
||||
fun addNewEntry(text: Component) {
|
||||
val line = text.copy()
|
||||
val textRenderer = Minecraft.getInstance().font
|
||||
val lines = Language.getInstance().getVisualOrder(textRenderer.splitter.splitLines(line, rowWidth, line.style))
|
||||
val fullyScrolledDown = maxScroll - scrollAmount < 10
|
||||
lines.forEach { addEntry(OutputEntry(it)) }
|
||||
if (fullyScrolledDown) {
|
||||
scrollAmount = maxScroll.toDouble()
|
||||
}
|
||||
}
|
||||
|
||||
override fun getSelected(): OutputEntry? = null
|
||||
|
||||
override fun getRowWidth(): Int {
|
||||
return Minecraft.getInstance().window.guiScaledWidth - 280 - 10 - 10
|
||||
}
|
||||
|
||||
override fun getScrollbarPosition(): Int {
|
||||
return this.x + rowWidth + 5
|
||||
}
|
||||
|
||||
override fun renderWidget(guiGraphics: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
|
||||
setRectangle(
|
||||
Minecraft.getInstance().window.guiScaledWidth - 280 - 10,
|
||||
Minecraft.getInstance().window.guiScaledHeight - 10 - 10 - 40,
|
||||
280,
|
||||
10
|
||||
)
|
||||
this.x = 280
|
||||
super.renderWidget(guiGraphics, mouseX, mouseY, partialTick)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the output list by clearing all entries.
|
||||
*/
|
||||
fun reset() {
|
||||
super.clearEntries()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry for the output list, representing a single line of text.
|
||||
*
|
||||
* @param line The formatted line of text to display.
|
||||
*/
|
||||
class OutputEntry(val line: FormattedCharSequence) : Entry<OutputEntry>() {
|
||||
override fun getNarration() = "".text()
|
||||
override fun render(
|
||||
context: GuiGraphics,
|
||||
index: Int,
|
||||
rowTop: Int,
|
||||
rowLeft: Int,
|
||||
rowWidth: Int,
|
||||
rowHeight: Int,
|
||||
mouseX: Int,
|
||||
mouseY: Int,
|
||||
isHovered: Boolean,
|
||||
partialTicks: Float
|
||||
) {
|
||||
drawScaledText(
|
||||
context,
|
||||
line,
|
||||
rowLeft,
|
||||
rowTop - 2
|
||||
)
|
||||
}
|
||||
|
||||
override fun isFocused() = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Input widget for entering commands to the Showdown service.
|
||||
*/
|
||||
class ShowdownInputWidget(val gui: ShowdownDebugGUI) : EditBox(
|
||||
Minecraft.getInstance().font,
|
||||
280,
|
||||
Minecraft.getInstance().window.guiScaledHeight - 40,
|
||||
Minecraft.getInstance().window.guiScaledWidth - 280 - 10,
|
||||
30,
|
||||
Component.literal("Enter command")
|
||||
) {
|
||||
override fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int): Boolean {
|
||||
val result = super.keyPressed(keyCode, scanCode, modifiers)
|
||||
if (keyCode == 257 && this.value.isNotEmpty()) {
|
||||
CobblemonNetwork.sendToServer(ShowdownInputPacket(
|
||||
service = activeShowdownService,
|
||||
input = this.value
|
||||
))
|
||||
deleteCharsToPos(0)
|
||||
CobblemonNetwork.sendToServer(RequestShowdownInfoPacket(activeShowdownService, gui.lastProcessedLogTime))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
+16
-2
@@ -10,6 +10,7 @@ package com.cobblemon.mod.common.client.keybind.keybinds
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.client.CobblemonClient
|
||||
import com.cobblemon.mod.common.client.gui.debug.ShowdownDebugGUI
|
||||
import com.cobblemon.mod.common.client.keybind.CobblemonKeyBinding
|
||||
import com.cobblemon.mod.common.client.keybind.KeybindCategories
|
||||
import com.cobblemon.mod.common.client.render.models.blockbench.FloatingState
|
||||
@@ -26,8 +27,10 @@ object DebugKeybindings {
|
||||
TranslateRightKeybinding(),
|
||||
TranslateUpKeybinding(),
|
||||
TranslateDownKeybinding(),
|
||||
PrintModelSettingsKeybinding()
|
||||
PrintModelSettingsKeybinding(),
|
||||
ToggleShowdownDebugGUIKeybinding()
|
||||
)
|
||||
|
||||
class ScaleUpKeybinding: CobblemonKeyBinding(
|
||||
"key.cobblemon.scaleportraitup",
|
||||
InputConstants.Type.KEYSYM,
|
||||
@@ -145,4 +148,15 @@ object DebugKeybindings {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ToggleShowdownDebugGUIKeybinding : CobblemonKeyBinding(
|
||||
"key.cobblemon.toggleshowdowndebuggui",
|
||||
InputConstants.Type.KEYSYM,
|
||||
InputConstants.KEY_APOSTROPHE,
|
||||
KeybindCategories.COBBLEMON_DEBUG_CATEGORY
|
||||
) {
|
||||
override fun onPress() {
|
||||
Minecraft.getInstance().setScreen(ShowdownDebugGUI())
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.cobblemon.mod.common.client.net.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
|
||||
import com.cobblemon.mod.common.client.gui.debug.ShowdownDebugGUI
|
||||
import com.cobblemon.mod.common.net.messages.client.debug.showdown.ShowdownRefreshInfoPacket
|
||||
import net.minecraft.client.Minecraft
|
||||
|
||||
/**
|
||||
* Handles the reception of a [ShowdownRefreshInfoPacket] on the client side.
|
||||
* This handler updates the Showdown Debug GUI with the latest showdown information.
|
||||
* @author landonjw
|
||||
*/
|
||||
object ShowdownRefreshInfoHandler : ClientNetworkPacketHandler<ShowdownRefreshInfoPacket> {
|
||||
/**
|
||||
* Handles the received [ShowdownRefreshInfoPacket] by refreshing the showdown information
|
||||
* in the [ShowdownDebugGUI] if it is currently open.
|
||||
*
|
||||
* @param packet The received packet containing the showdown information.
|
||||
* @param client The Minecraft client instance.
|
||||
*/
|
||||
override fun handle(packet: ShowdownRefreshInfoPacket, client: Minecraft) {
|
||||
if (client.screen is ShowdownDebugGUI) {
|
||||
(client.screen as ShowdownDebugGUI).refreshShowdownInfo(packet)
|
||||
}
|
||||
}
|
||||
}
|
||||
-93
@@ -19,7 +19,6 @@ import com.cobblemon.mod.common.Cobblemon.LOGGER
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addFunctions
|
||||
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
|
||||
import com.cobblemon.mod.common.api.molang.ObjectValue
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.api.scheduling.Schedulable
|
||||
import com.cobblemon.mod.common.client.ClientMoLangFunctions.setupClient
|
||||
import com.cobblemon.mod.common.client.particle.BedrockParticleOptionsRepository
|
||||
@@ -36,7 +35,6 @@ import com.cobblemon.mod.common.client.render.models.blockbench.quirk.ModelQuirk
|
||||
import com.cobblemon.mod.common.client.render.models.blockbench.quirk.QuirkData
|
||||
import com.cobblemon.mod.common.entity.PosableEntity
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
|
||||
import com.mojang.brigadier.StringReader
|
||||
import net.minecraft.client.Minecraft
|
||||
@@ -140,97 +138,6 @@ abstract class PosableState : Schedulable {
|
||||
reusableAnimTime.value = animationSeconds.toDouble()
|
||||
reusableAnimTime
|
||||
}
|
||||
.addFunction("r_pitch") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
val partialTickPitch = pokemon.riding.rotSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).x
|
||||
val maxPitch = 90.0
|
||||
return@addFunction DoubleValue((partialTickPitch / maxPitch).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_yaw") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
val partialTickYaw = pokemon.riding.rotSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).y
|
||||
val maxYaw = 180.0
|
||||
return@addFunction DoubleValue((partialTickYaw / maxYaw).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_roll") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
val partialTickRoll = pokemon.riding.rotSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).z
|
||||
val maxRoll = 180.0
|
||||
return@addFunction DoubleValue((partialTickRoll / maxRoll).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_yaw_change") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
val partialTickYawDelt = pokemon.riding.rotDeltaSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).y
|
||||
val maxRotRate = pokemon.riding.getController(pokemon)?.getStat(pokemon, RidingStat.SKILL)
|
||||
?: return@addFunction DoubleValue(0.0)
|
||||
return@addFunction DoubleValue((partialTickYawDelt / maxRotRate).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_pitch_change") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
val partialTickPitchDelt = pokemon.riding.rotDeltaSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).x
|
||||
val maxRotRate = pokemon.riding.getController(pokemon)?.getStat(pokemon, RidingStat.SKILL)
|
||||
?: return@addFunction DoubleValue(0.0)
|
||||
return@addFunction DoubleValue((partialTickPitchDelt / maxRotRate).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction(" r_roll_change") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
val partialTickRollDelt = pokemon.riding.rotDeltaSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).z
|
||||
val maxRotRate = pokemon.riding.getController(pokemon)?.getStat(pokemon, RidingStat.SKILL)
|
||||
?: return@addFunction DoubleValue(0.0)
|
||||
return@addFunction DoubleValue((partialTickRollDelt / maxRotRate).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_speed") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
|
||||
val partialTickSpeed = pokemon.riding.velSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).length()
|
||||
val topSpeed = pokemon.riding.getController(pokemon)?.getStat(pokemon, RidingStat.SPEED)
|
||||
?: return@addFunction DoubleValue(0.0)
|
||||
|
||||
return@addFunction DoubleValue((partialTickSpeed / topSpeed).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_speed_x") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
|
||||
val partialTickXVel = pokemon.riding.velSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).x
|
||||
|
||||
val topSpeed = pokemon.riding.getController(pokemon)?.getStat(pokemon, RidingStat.SPEED)
|
||||
?: return@addFunction DoubleValue(0.0)
|
||||
return@addFunction DoubleValue((partialTickXVel / topSpeed).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_speed_y") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
|
||||
val partialTickYVel = pokemon.riding.velSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).y
|
||||
|
||||
val topSpeed = pokemon.riding.getController(pokemon)?.getStat(pokemon, RidingStat.SPEED)
|
||||
?: return@addFunction DoubleValue(0.0)
|
||||
return@addFunction DoubleValue((partialTickYVel / topSpeed).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("r_speed_z") { params ->
|
||||
val lookBackTick = params.getInt(0)
|
||||
val pokemon = getEntity() as? PokemonEntity ?: return@addFunction DoubleValue(0.0)
|
||||
|
||||
val partialTickZVel = pokemon.riding.velSpring.getInterpolated(currentPartialTicks.toDouble(), lookBackTick).z
|
||||
|
||||
val topSpeed = pokemon.riding.getController(pokemon)?.getStat(pokemon, RidingStat.SPEED)
|
||||
?: return@addFunction DoubleValue(0.0)
|
||||
return@addFunction DoubleValue((partialTickZVel / topSpeed).coerceIn(-1.0,1.0))
|
||||
}
|
||||
.addFunction("current_aspects") { ArrayStruct(currentAspects.mapIndexed { index, s -> "$index" to StringValue(s)}.toMap())}
|
||||
.addFunction("has_aspect") { params -> DoubleValue(params.get<MoValue>(0).asString() in currentAspects) }
|
||||
.addFunction("has_entity") { DoubleValue(getEntity() != null) }
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright (C) 2023 Cobblemon Contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
package com.cobblemon.mod.common.client.render.models.blockbench.pokemon.gen7
|
||||
|
||||
import com.cobblemon.mod.common.client.render.models.blockbench.pokemon.PokemonPosableModel
|
||||
import com.cobblemon.mod.common.client.render.models.blockbench.frame.HeadedFrame
|
||||
import com.cobblemon.mod.common.client.render.models.blockbench.frame.QuadrupedFrame
|
||||
import com.cobblemon.mod.common.client.render.models.blockbench.pokemon.CryProvider
|
||||
import com.cobblemon.mod.common.client.render.models.blockbench.pose.Pose
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import net.minecraft.client.model.geom.ModelPart
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
class MudsdaleModel (root: ModelPart) : PokemonPosableModel(root), HeadedFrame, QuadrupedFrame {
|
||||
override val rootPart = root.registerChildWithAllChildren("mudsdale")
|
||||
override val head = getPart("neck")
|
||||
|
||||
override val foreLeftLeg = getPart("leg_front_left")
|
||||
override val foreRightLeg = getPart("leg_front_right")
|
||||
override val hindLeftLeg = getPart("leg_back_left")
|
||||
override val hindRightLeg = getPart("leg_back_right")
|
||||
|
||||
override var portraitScale = 1.5F
|
||||
override var portraitTranslation = Vec3(-1.0, 1.76, 0.0)
|
||||
|
||||
override var profileScale = 0.5F
|
||||
override var profileTranslation = Vec3(0.0, 1.0, 0.0)
|
||||
|
||||
lateinit var standing: Pose
|
||||
lateinit var walk: Pose
|
||||
lateinit var sleep: Pose
|
||||
|
||||
override val cryAnimation = CryProvider { bedrockStateful("mudsdale", "cry") }
|
||||
|
||||
override fun registerPoses() {
|
||||
val blink = quirk { bedrockStateful("mudsdale", "blink") }
|
||||
|
||||
sleep = registerPose(
|
||||
poseType = PoseType.SLEEP,
|
||||
animations = arrayOf(bedrock("mudsdale", "sleep"))
|
||||
)
|
||||
|
||||
standing = registerPose(
|
||||
poseName = "standing",
|
||||
poseTypes = PoseType.STATIONARY_POSES + PoseType.UI_POSES,
|
||||
transformTicks = 10,
|
||||
quirks = arrayOf(blink),
|
||||
animations = arrayOf(
|
||||
singleBoneLook(disableY = true),
|
||||
bedrock("mudsdale", "ground_idle")
|
||||
)
|
||||
)
|
||||
|
||||
walk = registerPose(
|
||||
poseName = "walk",
|
||||
poseTypes = PoseType.MOVING_POSES,
|
||||
transformTicks = 10,
|
||||
quirks = arrayOf(blink),
|
||||
animations = arrayOf(
|
||||
singleBoneLook(disableY = true),
|
||||
bedrock("mudsdale", "ground_walk")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// override fun getFaintAnimation(
|
||||
// pokemonEntity: PokemonEntity,
|
||||
// state: PosableState<PokemonEntity>
|
||||
// ) = if (state.isPosedIn(standing, walk)) bedrockStateful("mudsdale", "faint") else null
|
||||
}
|
||||
+1
@@ -497,6 +497,7 @@ object VaryingModelRepository {
|
||||
inbuilt("taillow", ::TaillowModel)
|
||||
inbuilt("swellow", ::SwellowModel)
|
||||
inbuilt("mudbray", ::MudbrayModel)
|
||||
inbuilt("mudsdale", ::MudsdaleModel)
|
||||
inbuilt("comfey", ::ComfeyModel)
|
||||
inbuilt("tandemaus", ::TandemausModel)
|
||||
inbuilt("maushold", ::MausholdModel)
|
||||
|
||||
@@ -1,41 +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.command
|
||||
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.mojang.brigadier.Command
|
||||
import com.mojang.brigadier.CommandDispatcher
|
||||
import com.mojang.brigadier.context.CommandContext
|
||||
import net.minecraft.commands.CommandSourceStack
|
||||
import net.minecraft.commands.Commands
|
||||
import net.minecraft.network.chat.Component
|
||||
|
||||
object ReloadShowdownCommand {
|
||||
|
||||
fun register(dispatcher: CommandDispatcher<CommandSourceStack>) {
|
||||
val command = Commands.literal("reloadshowdown")
|
||||
.requires { it.hasPermission(4) }
|
||||
.executes(::execute)
|
||||
dispatcher.register(command)
|
||||
}
|
||||
|
||||
private fun execute(context: CommandContext<CommandSourceStack>): Int {
|
||||
try {
|
||||
ShowdownService.service.closeConnection()
|
||||
ShowdownService.service.openConnection()
|
||||
ShowdownService.service.registerSpecies()
|
||||
ShowdownService.service.registerBagItems()
|
||||
context.source.sendSystemMessage(Component.literal("Reloaded showdown"))
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
return Command.SINGLE_SUCCESS
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,7 +13,6 @@ import com.cobblemon.mod.common.api.text.red
|
||||
import com.cobblemon.mod.common.command.argument.NPCClassArgumentType
|
||||
import com.cobblemon.mod.common.entity.npc.NPCEntity
|
||||
import com.cobblemon.mod.common.util.alias
|
||||
import com.cobblemon.mod.common.util.commandLang
|
||||
import com.cobblemon.mod.common.util.permission
|
||||
import com.cobblemon.mod.common.util.toBlockPos
|
||||
import com.mojang.brigadier.Command
|
||||
@@ -84,4 +83,4 @@ object SpawnNPCCommand {
|
||||
}
|
||||
throw FAILED_SPAWN_EXCEPTION.create()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import com.cobblemon.mod.common.util.effectiveName
|
||||
import com.cobblemon.mod.common.util.update
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
class NPCBattleActor(
|
||||
open class NPCBattleActor(
|
||||
val npc: NPCEntity,
|
||||
pokemonList: List<BattlePokemon>,
|
||||
val skill: Int
|
||||
@@ -84,4 +84,4 @@ class NPCBattleActor(
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ package com.cobblemon.mod.common.entity.pokemon
|
||||
|
||||
import com.cobblemon.mod.common.*
|
||||
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
|
||||
import com.cobblemon.mod.common.CobblemonSounds
|
||||
import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.drop.DropTable
|
||||
import com.cobblemon.mod.common.api.entity.Despawner
|
||||
import com.cobblemon.mod.common.api.entity.PokemonSender
|
||||
@@ -36,7 +38,6 @@ import com.cobblemon.mod.common.api.pokemon.status.Statuses
|
||||
import com.cobblemon.mod.common.api.reactive.ObservableSubscription
|
||||
import com.cobblemon.mod.common.api.reactive.SimpleObservable
|
||||
import com.cobblemon.mod.common.api.riding.*
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.RidingAltPose
|
||||
import com.cobblemon.mod.common.api.riding.events.SelectDriverEvent
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.api.scheduling.Schedulable
|
||||
@@ -85,6 +86,11 @@ import com.cobblemon.mod.common.util.*
|
||||
import com.cobblemon.mod.common.util.math.geometry.toRadians
|
||||
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules
|
||||
import com.mojang.serialization.Codec
|
||||
import java.util.EnumSet
|
||||
import java.util.Optional
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import kotlin.math.PI
|
||||
import net.minecraft.core.BlockPos
|
||||
import net.minecraft.core.registries.BuiltInRegistries
|
||||
import net.minecraft.core.registries.Registries
|
||||
@@ -137,9 +143,6 @@ import net.minecraft.world.phys.Vec2
|
||||
import net.minecraft.world.phys.Vec3
|
||||
import org.joml.Matrix3f
|
||||
import org.joml.Vector3f
|
||||
import java.util.*
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import kotlin.math.PI
|
||||
|
||||
@Suppress("unused")
|
||||
open class PokemonEntity(
|
||||
@@ -1407,22 +1410,11 @@ open class PokemonEntity(
|
||||
if (riders.isEmpty()) {
|
||||
super.handleRelativeFrictionAndCalculateMovement(deltaMovement, friction)
|
||||
} else {
|
||||
//val scale =
|
||||
//Handle ridden pokemon differently to allow vector lerp instead of simple addition.
|
||||
//val v = Entity.getInputVector(riding.velocity(this, this.controllingPassenger as Player, Vec3.ZERO), 1.0f, this.getYRot());
|
||||
val v = Entity.getInputVector(riding.velocity(this, this.controllingPassenger as Player, Vec3.ZERO), 1.0f, this.getYRot()).scale(this.speed.toDouble())
|
||||
val v = Entity.getInputVector(riding.velocity(this, this.controllingPassenger as Player, Vec3.ZERO), 1.0f, this.getYRot());
|
||||
//changing this will give the ride more or less inertia/handling/drift
|
||||
|
||||
//val smoothingFactor = 0.5
|
||||
//val t = 1.0 - exp(-smoothingFactor)
|
||||
|
||||
val diff = v.subtract(this.deltaMovement)
|
||||
|
||||
this.deltaMovement = this.deltaMovement.add( diff.scale(0.1) )
|
||||
|
||||
//this.deltaMovement = this.deltaMovement.lerp(v, riding.inertia(this))
|
||||
//this.deltaMovement = this.deltaMovement.scale(this.speed.toDouble()).lerp(v, riding.inertia(this));
|
||||
this.move(MoverType.SELF, this.deltaMovement)
|
||||
this.deltaMovement = this.deltaMovement.lerp(v, riding.inertia(this));
|
||||
this.move(MoverType.SELF, this.deltaMovement.scale(this.speed.toDouble()))
|
||||
}
|
||||
|
||||
return this.deltaMovement
|
||||
@@ -1444,36 +1436,14 @@ open class PokemonEntity(
|
||||
if (beamMode != 3) { // Don't let Pokémon move during recall
|
||||
|
||||
//Prevent current travel logic when riding a pokemon.
|
||||
/*
|
||||
val riders = this.passengers.filterIsInstance<LivingEntity>()
|
||||
if ( riders.isEmpty() ) {
|
||||
super.travel(movementInput)
|
||||
}
|
||||
else {
|
||||
//val v = Entity.getInputVector(riding.velocity(this, this.controllingPassenger as Player, Vec3.ZERO), this.speed.toFloat(), this.getYRot())
|
||||
val inp = riding.velocity(this, this.controllingPassenger as Player, Vec3.ZERO)
|
||||
|
||||
val f = Mth.sin(this.getYRot() * 0.017453292f)
|
||||
val g = Mth.cos(this.getYRot() * 0.017453292f)
|
||||
val v = Vec3(
|
||||
inp.x * g.toDouble() - inp.z * f.toDouble(),
|
||||
inp.y,
|
||||
inp.z * g.toDouble() + inp.x * f.toDouble()
|
||||
)
|
||||
|
||||
//val smoothingFactor = 0.5
|
||||
//val t = 1.0 - exp(-smoothingFactor)
|
||||
|
||||
val diff = v.subtract(this.deltaMovement)
|
||||
|
||||
this.deltaMovement = this.deltaMovement.add( diff.scale(riding.inertia(this)) )
|
||||
|
||||
//this.deltaMovement = this.deltaMovement.lerp(v, riding.inertia(this))
|
||||
//this.deltaMovement = this.deltaMovement.scale(this.speed.toDouble()).lerp(v, riding.inertia(this));
|
||||
this.move(MoverType.SELF, this.deltaMovement)
|
||||
}
|
||||
|
||||
|
||||
*/
|
||||
|
||||
super.travel(movementInput)
|
||||
|
||||
this.updateBlocksTraveled(prevBlockPos)
|
||||
}
|
||||
@@ -1843,9 +1813,9 @@ open class PokemonEntity(
|
||||
return this.riding.speed(this, controller)
|
||||
}
|
||||
|
||||
fun getActiveRidingAltPose(): RidingAltPose {
|
||||
val driver = this.controllingPassenger as? Player ?: return RidingAltPose.NONE
|
||||
return this.riding.getActiveRidingAltPose(this, driver)
|
||||
fun useRidingAltPose(): Boolean {
|
||||
val driver = this.controllingPassenger as? Player ?: return false
|
||||
return this.riding.useRidingAltPose(this, driver)
|
||||
}
|
||||
|
||||
var jumpInputStrength: Int = 0 // move this
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.cobblemon.mod.common.net.messages.client.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.api.net.NetworkPacket
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownStatus
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.readString
|
||||
import com.cobblemon.mod.common.util.writeString
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import java.util.Date
|
||||
|
||||
|
||||
/**
|
||||
* Packet sent to refresh the showdown information with the current status, messages, and available services.
|
||||
* This is typically sent when a user is in the Showdown Debug UI after they send a [RequestShowdownInfoPacket].
|
||||
*
|
||||
* @property status The current status of the showdown service.
|
||||
* @property service The resource location of the showdown service.
|
||||
* @property messages A list of messages from the active showdown service currently being refreshed.
|
||||
* @property availableServices A list of available showdown services. This allows the client to switch which server they are viewing.
|
||||
* @property requestProcessedAt The date and time when the request was processed.
|
||||
* @property includesStartOfLog Indicates if the messages include the start of the log.
|
||||
*
|
||||
* @author landonjw
|
||||
*/
|
||||
class ShowdownRefreshInfoPacket(
|
||||
val status: ShowdownStatus,
|
||||
val service: ResourceLocation,
|
||||
val messages: List<String>,
|
||||
val availableServices: List<ResourceLocation>,
|
||||
val requestProcessedAt: Date,
|
||||
val includesStartOfLog: Boolean
|
||||
) : NetworkPacket<ShowdownRefreshInfoPacket> {
|
||||
companion object {
|
||||
val ID = cobblemonResource("refresh_showdown_info")
|
||||
|
||||
/**
|
||||
* Decodes a [ShowdownRefreshInfoPacket] from the given [RegistryFriendlyByteBuf].
|
||||
*
|
||||
* @param buffer The buffer to read from.
|
||||
* @return The decoded [ShowdownRefreshInfoPacket].
|
||||
*/
|
||||
fun decode(buffer: RegistryFriendlyByteBuf) = ShowdownRefreshInfoPacket(
|
||||
status = ShowdownStatus.valueOf(buffer.readString()),
|
||||
service = buffer.readResourceLocation(),
|
||||
messages = buffer.readList { buffer.readString() },
|
||||
availableServices = buffer.readList { buffer.readResourceLocation() },
|
||||
requestProcessedAt = buffer.readDate(),
|
||||
includesStartOfLog = buffer.readBoolean()
|
||||
)
|
||||
}
|
||||
|
||||
override val id = ID
|
||||
|
||||
/**
|
||||
* Encodes this [ShowdownRefreshInfoPacket] to the given [RegistryFriendlyByteBuf].
|
||||
*
|
||||
* @param buffer The buffer to write to.
|
||||
*/
|
||||
override fun encode(buffer: RegistryFriendlyByteBuf) {
|
||||
buffer.writeString(status.name)
|
||||
buffer.writeResourceLocation(service)
|
||||
buffer.writeCollection(messages) { pb, value -> pb.writeString(value) }
|
||||
buffer.writeCollection(availableServices) { pb, value -> pb.writeResourceLocation(value) }
|
||||
buffer.writeDate(requestProcessedAt)
|
||||
buffer.writeBoolean(includesStartOfLog)
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.cobblemon.mod.common.net.messages.server.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.api.net.NetworkPacket
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import java.util.*
|
||||
|
||||
/**
|
||||
* Packet sent to request showdown information for a specific server.
|
||||
*
|
||||
* @property service The id of the showdown service to get showdown information for.
|
||||
* @author landonjw
|
||||
*/
|
||||
class RequestShowdownInfoPacket(val service: ResourceLocation, val lastRequest: Date?) : NetworkPacket<RequestShowdownInfoPacket> {
|
||||
override val id = ID
|
||||
|
||||
/**
|
||||
* Encodes this [RequestShowdownInfoPacket] to the given [RegistryFriendlyByteBuf].
|
||||
*
|
||||
* @param buffer The buffer to write to.
|
||||
*/
|
||||
override fun encode(buffer: RegistryFriendlyByteBuf) {
|
||||
buffer.writeResourceLocation(service)
|
||||
buffer.writeNullable(lastRequest) { pb, value -> pb.writeDate(value) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
val ID = cobblemonResource("request_showdown_info")
|
||||
|
||||
/**
|
||||
* Decodes a [RequestShowdownInfoPacket] from the given [RegistryFriendlyByteBuf].
|
||||
*
|
||||
* @param buffer The buffer to read from.
|
||||
* @return The decoded [RequestShowdownInfoPacket].
|
||||
*/
|
||||
fun decode(buffer: RegistryFriendlyByteBuf) = RequestShowdownInfoPacket(
|
||||
service = buffer.readResourceLocation(),
|
||||
lastRequest = buffer.readNullable { pb -> pb.readDate() }
|
||||
)
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.cobblemon.mod.common.net.messages.server.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.api.net.NetworkPacket
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
|
||||
/**
|
||||
* A network packet for sending action commands to the Showdown service.
|
||||
*
|
||||
* @property service The resource location of the Showdown service.
|
||||
* @property action The action command to be sent to the Showdown service.
|
||||
* @author landonjw
|
||||
*/
|
||||
class ShowdownActionPacket(val service: ResourceLocation, val action: Action) : NetworkPacket<ShowdownActionPacket> {
|
||||
override val id = ID
|
||||
|
||||
/**
|
||||
* Encodes the packet data into the given buffer.
|
||||
*
|
||||
* @param buffer The buffer to encode the data into.
|
||||
*/
|
||||
override fun encode(buffer: RegistryFriendlyByteBuf) {
|
||||
buffer.writeResourceLocation(service)
|
||||
buffer.writeEnum(action)
|
||||
}
|
||||
|
||||
companion object {
|
||||
val ID = cobblemonResource("showdown_action_request")
|
||||
|
||||
/**
|
||||
* Decodes the packet data from the given buffer.
|
||||
*
|
||||
* @param buffer The buffer to decode the data from.
|
||||
* @return The decoded ShowdownActionPacket.
|
||||
*/
|
||||
fun decode(buffer: RegistryFriendlyByteBuf) = ShowdownActionPacket(
|
||||
service = buffer.readResourceLocation(),
|
||||
action = buffer.readEnum(Action::class.java)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Enum representing possible actions for the Showdown service.
|
||||
*/
|
||||
enum class Action {
|
||||
START, STOP, RESTART, QUEUE
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.cobblemon.mod.common.net.messages.server.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.api.net.NetworkPacket
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.readString
|
||||
import com.cobblemon.mod.common.util.writeString
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
|
||||
/**
|
||||
* A network packet for sending input commands to the Showdown service.
|
||||
*
|
||||
* @property service The resource location of the Showdown service.
|
||||
* @property input The input command to be sent to the Showdown service.
|
||||
* @author landonjw
|
||||
*/
|
||||
class ShowdownInputPacket(val service: ResourceLocation, val input: String) : NetworkPacket<ShowdownInputPacket> {
|
||||
override val id = ID
|
||||
|
||||
/**
|
||||
* Encodes the packet data into the given buffer.
|
||||
*
|
||||
* @param buffer The buffer to encode the data into.
|
||||
*/
|
||||
override fun encode(buffer: RegistryFriendlyByteBuf) {
|
||||
buffer.writeResourceLocation(service)
|
||||
buffer.writeString(input)
|
||||
}
|
||||
|
||||
companion object {
|
||||
val ID = cobblemonResource("showdown_info_request")
|
||||
|
||||
/**
|
||||
* Decodes the packet data from the given buffer.
|
||||
*
|
||||
* @param buffer The buffer to decode the data from.
|
||||
* @return The decoded ShowdownInputPacket.
|
||||
*/
|
||||
fun decode(buffer: RegistryFriendlyByteBuf) = ShowdownInputPacket(
|
||||
service = buffer.readResourceLocation(),
|
||||
input = buffer.readString()
|
||||
)
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.cobblemon.mod.common.net.serverhandling.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
|
||||
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.net.messages.client.debug.showdown.ShowdownRefreshInfoPacket
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.RequestShowdownInfoPacket
|
||||
import net.minecraft.server.MinecraftServer
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import java.util.Date
|
||||
|
||||
/**
|
||||
* Handles the reception of a [RequestShowdownInfoPacket] on the server side.
|
||||
* This handler retrieves the showdown information from the specified service
|
||||
* and sends it back to the client.
|
||||
*
|
||||
* @author landonjw
|
||||
*/
|
||||
object RequestShowdownInfoHandler : ServerNetworkPacketHandler<RequestShowdownInfoPacket> {
|
||||
|
||||
/**
|
||||
* Handles the received [RequestShowdownInfoPacket] by retrieving the showdown information
|
||||
* from the specified service and sending it back to the client in a [ShowdownRefreshInfoPacket].
|
||||
*
|
||||
* @param packet The received packet requesting showdown information.
|
||||
* @param server The Minecraft server instance.
|
||||
* @param player The player who sent the request.
|
||||
*/
|
||||
override fun handle(packet: RequestShowdownInfoPacket, server: MinecraftServer, player: ServerPlayer) {
|
||||
if (!Cobblemon.config.enableDebugKeys) return
|
||||
if (!ShowdownService.contains(packet.service)) return
|
||||
|
||||
val service = ShowdownService.get(packet.service)
|
||||
val messages = service.log.get(after = packet.lastRequest)
|
||||
val availableServices = ShowdownService.all().map { it.id }
|
||||
val includesStartOfLog = if (packet.lastRequest == null) true else service.log.isStartOfLog(messages)
|
||||
player.sendPacket(ShowdownRefreshInfoPacket(service.status, packet.service, messages, availableServices, Date(), includesStartOfLog))
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.cobblemon.mod.common.net.serverhandling.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
|
||||
import com.cobblemon.mod.common.battles.BattleRegistry.packTeam
|
||||
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.ShowdownActionPacket
|
||||
import com.cobblemon.mod.common.util.party
|
||||
import com.google.gson.JsonObject
|
||||
import net.minecraft.server.MinecraftServer
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
/**
|
||||
* Handles network packets for Showdown actions on the server side.
|
||||
*
|
||||
* This handler processes incoming `ShowdownActionPacket` packets and performs the corresponding
|
||||
* actions (ie. restart it) on the specified Showdown service.
|
||||
*
|
||||
* @author landonjw
|
||||
*/
|
||||
object ShowdownActionHandler : ServerNetworkPacketHandler<ShowdownActionPacket> {
|
||||
|
||||
/**
|
||||
* Handles the received `ShowdownActionPacket`.
|
||||
*
|
||||
* @param packet The received packet containing the action to perform.
|
||||
* @param server The Minecraft server instance.
|
||||
* @param player The player who sent the packet.
|
||||
*/
|
||||
override fun handle(packet: ShowdownActionPacket, server: MinecraftServer, player: ServerPlayer) {
|
||||
if (!Cobblemon.config.enableDebugKeys) return
|
||||
if (!ShowdownService.contains(packet.service)) return
|
||||
|
||||
val service = ShowdownService.get(packet.service)
|
||||
when (packet.action) {
|
||||
ShowdownActionPacket.Action.START -> service.openConnection()
|
||||
ShowdownActionPacket.Action.STOP -> service.closeConnection()
|
||||
ShowdownActionPacket.Action.RESTART -> service.restartConnection()
|
||||
ShowdownActionPacket.Action.QUEUE -> {
|
||||
val cobblemonTeam = player.party().saveToJSON(JsonObject(), player.registryAccess())
|
||||
val showdownTeam = player.party().map { BattlePokemon(it, it.clone(false)) { entity -> entity.discard() } }
|
||||
showdownTeam.forEach {
|
||||
it.effectedPokemon.level = 100
|
||||
it.effectedPokemon.heal()
|
||||
}
|
||||
val showdownTeamStr = showdownTeam.packTeam()
|
||||
service.send(">queue-battle ${player.uuid} ${player.name.string} $cobblemonTeam@|@$showdownTeamStr")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.cobblemon.mod.common.net.serverhandling.debug.showdown
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
|
||||
import com.cobblemon.mod.common.battles.runner.ShowdownService
|
||||
import com.cobblemon.mod.common.net.messages.server.debug.showdown.ShowdownInputPacket
|
||||
import net.minecraft.server.MinecraftServer
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
/**
|
||||
* Handles the processing of `ShowdownInputPacket` on the server side.
|
||||
* This handler sends a command to the given showdown service. This is used for debugging purposes.
|
||||
*
|
||||
* @author landonjw
|
||||
*/
|
||||
object ShowdownInputHandler : ServerNetworkPacketHandler<ShowdownInputPacket> {
|
||||
|
||||
/**
|
||||
* Handles the received `ShowdownInputPacket`.
|
||||
*
|
||||
* @param packet The received packet containing the input command and service information.
|
||||
* @param server The Minecraft server instance.
|
||||
* @param player The player who sent the packet.
|
||||
*/
|
||||
override fun handle(packet: ShowdownInputPacket, server: MinecraftServer, player: ServerPlayer) {
|
||||
if (!Cobblemon.config.enableDebugKeys) return
|
||||
if (!ShowdownService.contains(packet.service)) return
|
||||
|
||||
val service = ShowdownService.get(packet.service)
|
||||
service.send(packet.input)
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -32,7 +32,7 @@ abstract class BaseCobblemonHeldItemManager : HeldItemManager {
|
||||
|
||||
internal open fun load() {
|
||||
this.itemIds.clear()
|
||||
val itemsJson = ShowdownService.service.getItemIds()
|
||||
val itemsJson = ShowdownService.get().getItemIds()
|
||||
val showdownIds = hashSetOf<String>()
|
||||
for (i in 0 until itemsJson.size()) {
|
||||
showdownIds += itemsJson[i].asString
|
||||
@@ -95,4 +95,4 @@ abstract class BaseCobblemonHeldItemManager : HeldItemManager {
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
-34
@@ -15,14 +15,13 @@ import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.RidingAltPose
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.riding.states.BirdAirState
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.util.Mth
|
||||
import net.minecraft.util.SmoothDouble
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.player.Player
|
||||
@@ -39,27 +38,27 @@ class BirdAirController : RideController {
|
||||
|
||||
override val condition: (PokemonEntity) -> Boolean = { true }
|
||||
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'AIR', 135.0, 45.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'AIR', 1.0, 0.35)".asExpression(),
|
||||
// Max accel is a whole 1.0 in 3 seconds. The conversion in the function below is to convert seconds to ticks
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'AIR', (1.0 / (20.0 * 3.0)), (1.0 / (20.0 * 8.0)))".asExpression(),
|
||||
//Seconds self propelled flight (glide is not self propelled in this case)
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'AIR', 120.0, 20.0)".asExpression(),
|
||||
//max y level for the ride
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'AIR', 200.0, 128.0)".asExpression()
|
||||
)
|
||||
var handlingExpr: Expression = "q.get_ride_stats('SKILL', 'AIR', 135.0, 45.0)".asExpression()
|
||||
private set
|
||||
var topSpeedExpr: Expression = "q.get_ride_stats('SPEED', 'AIR', 1.0, 0.35)".asExpression()
|
||||
private set
|
||||
var glideTopSpeedExpr: Expression = "q.get_ride_stats('SPEED', 'AIR', 2.0, 1.0)".asExpression()
|
||||
private set
|
||||
// Max accel is a whole 1.0 in 3 seconds. The conversion in the function below is to convert seconds to ticks
|
||||
var accelExpr: Expression = "q.get_ride_stats('ACCELERATION', 'AIR', (1.0 / (20.0 * 3.0)), (1.0 / (20.0 * 8.0)))".asExpression()
|
||||
private set
|
||||
//Seconds self propelled flight (glide is not self propelled in this case)
|
||||
var staminaExpr: Expression = "q.get_ride_stats('STAMINA', 'AIR', 120.0, 20.0)".asExpression()
|
||||
private set
|
||||
//max y level for the ride
|
||||
var altitudeExpr: Expression = "q.get_ride_stats('JUMP', 'AIR', 200.0, 128.0)".asExpression()
|
||||
private set
|
||||
|
||||
var infiniteStamina: Expression = "false".asExpression()
|
||||
private set
|
||||
var infiniteAltitude: Expression = "false".asExpression()
|
||||
private set
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
|
||||
//Retrieve the current bird controller state and stats
|
||||
@@ -100,7 +99,7 @@ class BirdAirController : RideController {
|
||||
upForce -= 0.3
|
||||
}
|
||||
|
||||
val altitudeLimit = this.getStat(entity, RidingStat.JUMP)
|
||||
val altitudeLimit = getRuntime(entity).resolveDouble(altitudeExpr)
|
||||
|
||||
//Only limit altitude if altitude is not infinite
|
||||
if (!getRuntime(entity).resolveBoolean(infiniteAltitude)) {
|
||||
@@ -118,13 +117,13 @@ class BirdAirController : RideController {
|
||||
val state = getState(entity, ::BirdAirState)
|
||||
|
||||
//TODO: Tie in handling
|
||||
val handling = this.getStat(entity, RidingStat.SKILL)
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val handling = getRuntime(entity).resolveDouble(handlingExpr)
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
val rotationChangeRate = 10.0
|
||||
|
||||
if (rollable != null) {
|
||||
var yawForce = rotationChangeRate * sin(Math.toRadians(rollable.roll.toDouble()))
|
||||
//for a bit of correction on the rolls limit it to a quarter the amount
|
||||
//for a bit of correction on the rolls influence pitch as well
|
||||
var pitchForce = -0.35 * rotationChangeRate * abs(sin(Math.toRadians(rollable.roll.toDouble())))
|
||||
|
||||
//limit rotation modulation when pitched up heavily or pitched down heavily
|
||||
@@ -151,8 +150,8 @@ class BirdAirController : RideController {
|
||||
val rollable = driver as Rollable
|
||||
|
||||
val state = getState(entity, ::BirdAirState)
|
||||
val handling = this.getStat(entity, RidingStat.SKILL)
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val handling = getRuntime(entity).resolveDouble(handlingExpr)
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
|
||||
//Smooth out mouse input.
|
||||
val smoothingSpeed = 4
|
||||
@@ -215,8 +214,8 @@ class BirdAirController : RideController {
|
||||
override fun shouldRoll(entity: PokemonEntity) = true
|
||||
|
||||
override fun rideFovMult(entity: PokemonEntity, driver: Player): Float {
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val glideTopSpeed = topSpeed * 1.5 //TODO: Should this be refined?
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
val glideTopSpeed = getRuntime(entity).resolveDouble(glideTopSpeedExpr)
|
||||
val state = getState(entity, ::BirdAirState)
|
||||
|
||||
//Must I ensure that topspeed is greater than minimum?
|
||||
@@ -229,19 +228,28 @@ class BirdAirController : RideController {
|
||||
|
||||
override fun useAngVelSmoothing(entity: PokemonEntity): Boolean = false
|
||||
|
||||
override fun getActiveRidingAltPose(entity: PokemonEntity, driver: Player): RidingAltPose {
|
||||
override fun useRidingAltPose(entity: PokemonEntity, driver: Player): Boolean {
|
||||
val state = getState(entity, ::BirdAirState)
|
||||
val pose = if (state.gliding) RidingAltPose.GLIDING else RidingAltPose.NONE
|
||||
return pose
|
||||
return state.gliding
|
||||
}
|
||||
|
||||
override fun encode(buffer: RegistryFriendlyByteBuf) {
|
||||
super.encode(buffer)
|
||||
buffer.writeString(topSpeedExpr.toString())
|
||||
buffer.writeString(glideTopSpeedExpr.toString())
|
||||
buffer.writeString(accelExpr.toString())
|
||||
buffer.writeString(handlingExpr.toString())
|
||||
buffer.writeString(altitudeExpr.toString())
|
||||
buffer.writeString(infiniteStamina.toString())
|
||||
buffer.writeString(infiniteAltitude.toString())
|
||||
}
|
||||
|
||||
override fun decode(buffer: RegistryFriendlyByteBuf) {
|
||||
topSpeedExpr = buffer.readString().asExpression()
|
||||
glideTopSpeedExpr = buffer.readString().asExpression()
|
||||
accelExpr = buffer.readString().asExpression()
|
||||
handlingExpr = buffer.readString().asExpression()
|
||||
altitudeExpr = buffer.readString().asExpression()
|
||||
infiniteStamina = buffer.readString().asExpression()
|
||||
infiniteAltitude = buffer.readString().asExpression()
|
||||
}
|
||||
@@ -268,12 +276,12 @@ class BirdAirController : RideController {
|
||||
|
||||
|
||||
//retrieve stats
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val glideTopSpeed = topSpeed * 1.5
|
||||
val accel = this.getStat(entity, RidingStat.ACCELERATION)
|
||||
val staminaStat = this.getStat(entity, RidingStat.STAMINA)
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
val glideTopSpeed = getRuntime(entity).resolveDouble(glideTopSpeedExpr)
|
||||
val accel = getRuntime(entity).resolveDouble(accelExpr)
|
||||
val staminaStat = getRuntime(entity).resolveDouble(staminaExpr)
|
||||
|
||||
var glideSpeedChange = 0.00
|
||||
var glideSpeedChange = 0.0
|
||||
|
||||
val currSpeed = state.rideVel.length()
|
||||
|
||||
@@ -386,7 +394,6 @@ class BirdAirController : RideController {
|
||||
}
|
||||
|
||||
//air resistance
|
||||
//TODO: This method is very unrefined and will need to be an active point of testing
|
||||
state.rideVel = Vec3(
|
||||
state.rideVel.x,
|
||||
state.rideVel.y,
|
||||
|
||||
+114
-295
@@ -8,37 +8,53 @@
|
||||
|
||||
package com.cobblemon.mod.common.pokemon.riding.controllers
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.riding.states.DolphinLiquidState
|
||||
import com.cobblemon.mod.common.pokemon.Pokemon
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.util.Mth.lerp
|
||||
import net.minecraft.util.SmoothDouble
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.player.Player
|
||||
import net.minecraft.world.phys.Vec2
|
||||
import net.minecraft.world.phys.Vec3
|
||||
import kotlin.math.*
|
||||
import net.minecraft.world.phys.shapes.Shapes
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
class DolphinController : RideController {
|
||||
companion object {
|
||||
val KEY: ResourceLocation = cobblemonResource("swim/dolphin")
|
||||
}
|
||||
|
||||
var canJump = "true".asExpression()
|
||||
private set
|
||||
var jumpVector = listOf("0".asExpression(), "0.3".asExpression(), "0".asExpression())
|
||||
private set
|
||||
var speed = "1.0".asExpression()
|
||||
private set
|
||||
var driveFactor = "1.0".asExpression()
|
||||
private set
|
||||
var reverseDriveFactor = "0.25".asExpression()
|
||||
private set
|
||||
var strafeFactor = "0.2".asExpression()
|
||||
private set
|
||||
var lastVelocity = Vec3(0.0,0.0,0.0)
|
||||
private set
|
||||
|
||||
private val rollSmoother = SmoothDouble()
|
||||
|
||||
override val key: ResourceLocation = KEY
|
||||
override val poseProvider: PoseProvider = PoseProvider(PoseType.FLOAT)
|
||||
.with(PoseOption(PoseType.SWIM) { it.deltaMovement.length() >= 0.05 })
|
||||
/*
|
||||
override val condition: (PokemonEntity) -> Boolean = { entity ->
|
||||
|
||||
//If there are only fluid blocks or air block below the ride
|
||||
@@ -52,332 +68,135 @@ class DolphinController : RideController {
|
||||
true
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
override val condition: (PokemonEntity) -> Boolean = { true }
|
||||
|
||||
//TODO:Implement real values for this
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'LIQUID', 135.0, 45.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'LIQUID', 0.6, 0.2)".asExpression(),
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'LIQUID', (1.0 / (20.0 * 3.0)), (1.0 / (20.0 * 8.0)))".asExpression(),
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'LIQUID', 120.0, 20.0)".asExpression(),
|
||||
//max y level for the ride
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'LIQUID', 200.0, 128.0)".asExpression()
|
||||
)
|
||||
|
||||
var glideTopSpeedExpr: Expression = "q.get_ride_stats('SPEED', 'LIQUID', 2.0, 1.0)".asExpression()
|
||||
private set
|
||||
|
||||
var infiniteStamina: Expression = "false".asExpression()
|
||||
private set
|
||||
var infiniteAltitude: Expression = "false".asExpression()
|
||||
private set
|
||||
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
|
||||
//Retrieve the current bird controller state and stats
|
||||
val state = getState(entity, ::DolphinLiquidState)
|
||||
|
||||
return state.rideVel.length().toFloat()
|
||||
return getRuntime(entity).resolveFloat(speed)
|
||||
}
|
||||
|
||||
override fun rotation(entity: PokemonEntity, driver: LivingEntity): Vec2 {
|
||||
return Vec2(driver.xRot * 0.5f, driver.yRot)
|
||||
return Vec2(driver.xRot * 0.5f, driver.yRot )
|
||||
}
|
||||
|
||||
override fun gravity(entity: PokemonEntity, regularGravity: Double): Double? {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
override fun inertia(entity: PokemonEntity ): Double
|
||||
{
|
||||
return 0.05
|
||||
}
|
||||
|
||||
override fun velocity(entity: PokemonEntity, driver: Player, input: Vec3): Vec3 {
|
||||
var yVel = 0.0
|
||||
var leftForce = 0.0
|
||||
var upForce = 0.0
|
||||
var forwardForce = 0.0
|
||||
val state = getState(entity, ::DolphinLiquidState)
|
||||
val runtime = getRuntime(entity)
|
||||
|
||||
//Perform ride velocity update
|
||||
calculateRideSpaceVel(entity, driver, state)
|
||||
if (!entity.isInWater && !entity.isUnderWater)
|
||||
{
|
||||
lastVelocity = Vec3(lastVelocity.x, lastVelocity.y - 0.035, lastVelocity.z)
|
||||
return lastVelocity
|
||||
}
|
||||
|
||||
//Translate ride space velocity to world space velocity.
|
||||
val driveFactor = runtime.resolveFloat(this.driveFactor)
|
||||
val strafeFactor = runtime.resolveFloat(this.strafeFactor)
|
||||
val f = driver.xxa * strafeFactor
|
||||
var g = driver.zza * driveFactor
|
||||
if (g <= 0.0f) {
|
||||
g *= runtime.resolveFloat(this.reverseDriveFactor)
|
||||
}
|
||||
|
||||
var yComp = 0.0
|
||||
|
||||
//Get roll to add a left and right strafe during roll
|
||||
//Not sure if this is desired? Will need to mess around with this
|
||||
//a bit more
|
||||
var zComp = 0.0
|
||||
val rollable = driver as? Rollable
|
||||
if (rollable != null) {
|
||||
//Need to deadzone this when straight up or down
|
||||
|
||||
upForce += -1.0 * sin(Math.toRadians(rollable.pitch.toDouble())) * state.rideVel.z
|
||||
forwardForce += cos(Math.toRadians(rollable.pitch.toDouble())) * state.rideVel.z
|
||||
|
||||
upForce += cos(Math.toRadians(rollable.pitch.toDouble())) * state.rideVel.y
|
||||
forwardForce += sin(Math.toRadians(rollable.pitch.toDouble())) * state.rideVel.y
|
||||
if (rollable != null)
|
||||
{
|
||||
//Can be used again if I better figure out how to deadzone it near the tops?
|
||||
zComp = -1.0 * g.toDouble() * sin(Math.toRadians(rollable.roll.toDouble()))
|
||||
yComp = -1.0 * g.toDouble() * sin(Math.toRadians(rollable.pitch.toDouble()))
|
||||
}
|
||||
|
||||
|
||||
//Bring the ride out of the sky when stamina is depleted.
|
||||
if (state.stamina <= 0.0) {
|
||||
upForce -= 0.3
|
||||
}
|
||||
|
||||
val altitudeLimit = this.getStat(entity, RidingStat.JUMP)
|
||||
|
||||
//Only limit altitude if altitude is not infinite
|
||||
if (!getRuntime(entity).resolveBoolean(infiniteAltitude)) {
|
||||
//Provide a hard limit on altitude
|
||||
upForce = if (entity.y >= altitudeLimit && upForce > 0) 0.0 else upForce
|
||||
}
|
||||
|
||||
val velocity = Vec3(state.rideVel.x , upForce, forwardForce)
|
||||
return velocity
|
||||
val currVelocity = Vec3(0.0, yComp , g.toDouble())
|
||||
lastVelocity = currVelocity
|
||||
return currVelocity
|
||||
}
|
||||
|
||||
override fun angRollVel(entity: PokemonEntity, driver: Player, deltaTime: Double): Vec3 {
|
||||
|
||||
if (!entity.isInWater && !entity.isUnderWater)
|
||||
{
|
||||
return Vec3(0.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
val rollable = driver as? Rollable
|
||||
val state = getState(entity, ::DolphinLiquidState)
|
||||
|
||||
//TODO: Tie in handling
|
||||
val handling = this.getStat(entity, RidingStat.SKILL)
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val rotationChangeRate = 10.0
|
||||
|
||||
//this should be changed to be speed maybe?
|
||||
val movingForce = driver.zza
|
||||
if (rollable != null) {
|
||||
var yawForce = rotationChangeRate * sin(Math.toRadians(rollable.roll.toDouble()))
|
||||
//for a bit of correction on the rolls limit it to a quarter the amount
|
||||
var pitchForce = -0.35 * rotationChangeRate * abs(sin(Math.toRadians(rollable.roll.toDouble())))
|
||||
var yawAngVel = 3 * sin(Math.toRadians(rollable.roll.toDouble())).toFloat()
|
||||
var pitchAngVel = -1 * Math.abs(sin(Math.toRadians(rollable.roll.toDouble())).toFloat())
|
||||
|
||||
//limit rotation modulation when pitched up heavily or pitched down heavily
|
||||
yawForce *= abs(cos(Math.toRadians(rollable.pitch.toDouble())))
|
||||
pitchForce *= abs(cos(Math.toRadians(rollable.pitch.toDouble()))) * 1.5
|
||||
|
||||
return Vec3(yawForce, pitchForce, 0.0)
|
||||
yawAngVel *= (abs(cos(Math.toRadians(rollable.pitch.toDouble())))).toFloat()
|
||||
pitchAngVel *= (abs(cos(Math.toRadians(rollable.pitch.toDouble())))).toFloat()
|
||||
//if you are not pressing forward then don't turn
|
||||
//yawAngVel *= movingForce
|
||||
//Ignore x,y,z its angular velocity:
|
||||
//yaw, pitch, roll
|
||||
return Vec3(yawAngVel.toDouble(), pitchAngVel.toDouble(), 0.0)
|
||||
}
|
||||
|
||||
return Vec3(0.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
override fun rotationOnMouseXY(
|
||||
entity: PokemonEntity,
|
||||
driver: Player,
|
||||
yMouse: Double,
|
||||
xMouse: Double,
|
||||
yMouseSmoother: SmoothDouble,
|
||||
xMouseSmoother: SmoothDouble,
|
||||
sensitivity: Double,
|
||||
deltaTime: Double
|
||||
): Vec3 {
|
||||
if (driver !is Rollable) return Vec3.ZERO
|
||||
val rollable = driver as Rollable
|
||||
override fun canJump(entity: PokemonEntity, driver: Player) = getRuntime(entity).resolveBoolean(canJump)
|
||||
|
||||
val state = getState(entity, ::DolphinLiquidState)
|
||||
val handling = this.getStat(entity, RidingStat.SKILL)
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
|
||||
//Smooth out mouse input.
|
||||
val smoothingSpeed = 4
|
||||
val invertRoll = if (Cobblemon.config.invertRoll) -1 else 1
|
||||
val invertPitch = if (Cobblemon.config.invertPitch) -1 else 1
|
||||
val xInput = xMouseSmoother.getNewDeltaValue(xMouse * 0.1 * invertRoll, deltaTime * smoothingSpeed);
|
||||
val yInput = yMouseSmoother.getNewDeltaValue(yMouse * 0.1 * invertPitch, deltaTime * smoothingSpeed);
|
||||
|
||||
//limit rolling based on handling and current speed.
|
||||
//modulated by speed so that when flapping idle in air you are ont wobbling around to look around
|
||||
val rotMin = 15.0
|
||||
var rollForce = xInput
|
||||
val rotLimit = max(handling * normalizeVal(state.rideVel.length(), 0.0, topSpeed).pow(3), rotMin)
|
||||
|
||||
//Limit roll by non linearly decreasing inputs towards
|
||||
// a rotation limit based on the current distance from
|
||||
// that rotation limit
|
||||
if (abs(rollable.roll + rollForce) < rotLimit) {
|
||||
if (sign(rollForce) == sign(rollable.roll).toDouble()) {
|
||||
val d = abs(abs(rollable.roll) - rotLimit)
|
||||
rollForce *= (d.pow(2)) / (rotLimit.pow(2))
|
||||
}
|
||||
} else if (sign(rollForce) == sign(rollable.roll).toDouble()) {
|
||||
rollForce = 0.0
|
||||
}
|
||||
|
||||
//Give the ability to yaw with x mouse input when at low speeds.
|
||||
val yawForce = xInput * ( 1.0 - normalizeVal(state.rideVel.length(), 0.0, topSpeed).pow(3))
|
||||
|
||||
//yaw, pitch, roll
|
||||
return Vec3(yawForce, yInput, rollForce)
|
||||
}
|
||||
|
||||
override fun canJump(
|
||||
entity: PokemonEntity,
|
||||
driver: Player
|
||||
): Boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
override fun setRideBar(entity: PokemonEntity, driver: Player): Float {
|
||||
//Retrieve stamina from state
|
||||
val state = getState(entity, ::DolphinLiquidState)
|
||||
|
||||
return (state.stamina / 1.0f)
|
||||
}
|
||||
|
||||
override fun jumpForce(
|
||||
entity: PokemonEntity,
|
||||
driver: Player,
|
||||
jumpStrength: Int
|
||||
): Vec3 {
|
||||
return Vec3.ZERO
|
||||
}
|
||||
|
||||
override fun gravity(entity: PokemonEntity, regularGravity: Double): Double {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
override fun turnOffOnGround(entity: PokemonEntity): Boolean {
|
||||
return false
|
||||
override fun jumpForce(entity: PokemonEntity, driver: Player, jumpStrength: Int): Vec3 {
|
||||
val runtime = getRuntime(entity)
|
||||
runtime.environment.query.addFunction("jump_strength") { DoubleValue(jumpStrength.toDouble()) }
|
||||
val jumpVector = jumpVector.map { runtime.resolveFloat(it) }
|
||||
return Vec3(jumpVector[0].toDouble(), jumpVector[1].toDouble(), jumpVector[2].toDouble())
|
||||
}
|
||||
|
||||
override fun shouldRoll(entity: PokemonEntity) = true
|
||||
|
||||
override fun rideFovMult(entity: PokemonEntity, driver: Player): Float {
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val glideTopSpeed = getRuntime(entity).resolveDouble(glideTopSpeedExpr)
|
||||
val state = getState(entity, ::DolphinLiquidState)
|
||||
override fun turnOffOnGround(entity: PokemonEntity): Boolean = true
|
||||
|
||||
//Must I ensure that topspeed is greater than minimum?
|
||||
val normalizedGlideSpeed = normalizeVal(state.rideVel.length(), topSpeed, glideTopSpeed)
|
||||
|
||||
//Only ever want the fov change to be a max of 0.2 and for it to have non linear scaling.
|
||||
return 1.0f + normalizedGlideSpeed.pow(2).toFloat() * 0.2f
|
||||
|
||||
}
|
||||
|
||||
override fun useAngVelSmoothing(entity: PokemonEntity): Boolean = false
|
||||
override fun dismountOnShift(entity: PokemonEntity): Boolean = false
|
||||
|
||||
override fun encode(buffer: RegistryFriendlyByteBuf) {
|
||||
super.encode(buffer)
|
||||
buffer.writeString(glideTopSpeedExpr.toString())
|
||||
buffer.writeString(infiniteStamina.toString())
|
||||
buffer.writeString(infiniteAltitude.toString())
|
||||
buffer.writeString(this.speed.getString())
|
||||
buffer.writeString(this.canJump.getString())
|
||||
buffer.writeString(this.jumpVector[0].getString())
|
||||
buffer.writeString(this.jumpVector[1].getString())
|
||||
buffer.writeString(this.jumpVector[2].getString())
|
||||
buffer.writeString(this.driveFactor.getString())
|
||||
buffer.writeString(this.reverseDriveFactor.getString())
|
||||
buffer.writeString(this.strafeFactor.getString())
|
||||
buffer.writeDouble(this.lastVelocity.x)
|
||||
buffer.writeDouble(this.lastVelocity.y)
|
||||
buffer.writeDouble(this.lastVelocity.z)
|
||||
}
|
||||
|
||||
|
||||
override fun decode(buffer: RegistryFriendlyByteBuf) {
|
||||
glideTopSpeedExpr = buffer.readString().asExpression()
|
||||
infiniteStamina = buffer.readString().asExpression()
|
||||
infiniteAltitude = buffer.readString().asExpression()
|
||||
}
|
||||
|
||||
/*
|
||||
* Normalizes the given value between a min and a max.
|
||||
* The result is clamped between 0.0 and 1.0, where 0.0 represents x is at or below min
|
||||
* and 1.0 represents x is at or above it.
|
||||
*/
|
||||
fun normalizeVal(x: Double, min: Double, max: Double): Double {
|
||||
require(max > min) { "max must be greater than min" }
|
||||
return ((x - min) / (max - min)).coerceIn(0.0, 1.0)
|
||||
}
|
||||
|
||||
/*s
|
||||
* Calculates the change in the ride space vector due to player input and ride state
|
||||
*/
|
||||
fun calculateRideSpaceVel(entity: PokemonEntity, driver: Player, state: DolphinLiquidState) {
|
||||
|
||||
|
||||
//retrieve stats
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val glideTopSpeed = getRuntime(entity).resolveDouble(glideTopSpeedExpr)
|
||||
val accel = this.getStat(entity, RidingStat.ACCELERATION)
|
||||
val staminaStat = this.getStat(entity, RidingStat.STAMINA)
|
||||
|
||||
var glideSpeedChange = 0.00
|
||||
|
||||
val currSpeed = state.rideVel.length()
|
||||
|
||||
//Flag for determining if player is actively inputting
|
||||
var activeInput = false
|
||||
|
||||
//speed up and slow down based on input
|
||||
if (driver.zza != 0.0f && state.stamina > 0.0) {
|
||||
//make sure it can't exceed top speed
|
||||
val forwardInput = when {
|
||||
driver.zza > 0 && state.rideVel.z > topSpeed -> 0.0
|
||||
driver.zza < 0 && state.rideVel.z < (-topSpeed / 3.0) -> 0.0
|
||||
else -> driver.zza.sign
|
||||
}
|
||||
|
||||
state.rideVel = Vec3(
|
||||
state.rideVel.x,
|
||||
state.rideVel.y,
|
||||
(state.rideVel.z + (accel * forwardInput.toDouble())))
|
||||
|
||||
activeInput = true
|
||||
}
|
||||
|
||||
//Lateral movement based on driver input.
|
||||
val latTopSpeed = topSpeed / 2.0
|
||||
if (driver.xxa != 0.0f && state.stamina > 0.0) {
|
||||
state.rideVel = Vec3(
|
||||
(state.rideVel.x + (accel * driver.xxa)).coerceIn(-latTopSpeed, latTopSpeed),
|
||||
state.rideVel.y,
|
||||
state.rideVel.z)
|
||||
activeInput = true
|
||||
}
|
||||
else {
|
||||
state.rideVel = Vec3(
|
||||
lerp(state.rideVel.x, 0.0, latTopSpeed / 20.0),
|
||||
state.rideVel.y,
|
||||
state.rideVel.z)
|
||||
}
|
||||
|
||||
//Vertical movement based on driver input.
|
||||
val vertTopSpeed = topSpeed / 2.0
|
||||
val vertInput = when {
|
||||
Minecraft.getInstance().options.keyJump.isDown() -> 1.0
|
||||
Minecraft.getInstance().options.keyShift.isDown() -> -1.0
|
||||
else -> 0.0
|
||||
}
|
||||
|
||||
if (vertInput != 0.0 && state.stamina > 0.0) {
|
||||
state.rideVel = Vec3(
|
||||
state.rideVel.x,
|
||||
(state.rideVel.y + (accel * vertInput)).coerceIn(-vertTopSpeed, vertTopSpeed),
|
||||
state.rideVel.z)
|
||||
activeInput = true
|
||||
}
|
||||
else {
|
||||
state.rideVel = Vec3(
|
||||
state.rideVel.x,
|
||||
lerp(state.rideVel.y, 0.0, vertTopSpeed / 20.0),
|
||||
state.rideVel.z)
|
||||
}
|
||||
|
||||
//Check if the ride should be gliding
|
||||
if (activeInput && state.stamina > 0.0) {
|
||||
state.gliding = false
|
||||
}else {
|
||||
state.gliding = true
|
||||
}
|
||||
|
||||
//Only perform stamina logic if the ride does not have infinite stamina
|
||||
if (!getRuntime(entity).resolveBoolean(infiniteStamina)) {
|
||||
if (activeInput) {
|
||||
state.stamina -= (0.05 / staminaStat).toFloat()
|
||||
}
|
||||
|
||||
//Lose a base amount of stamina just for being airborne
|
||||
state.stamina -= (0.01 / staminaStat).toFloat()
|
||||
}
|
||||
else
|
||||
{
|
||||
state.stamina = 1.0f
|
||||
}
|
||||
|
||||
//air resistance
|
||||
//TODO: This method is very unrefined and will need to be an active point of testing
|
||||
/*
|
||||
state.rideVel = Vec3(
|
||||
state.rideVel.x,
|
||||
state.rideVel.y,
|
||||
lerp( state.rideVel.z,0.0, topSpeed / ( 20.0 * 30.0)))
|
||||
*/
|
||||
this.speed = buffer.readString().asExpression()
|
||||
this.canJump = buffer.readString().asExpression()
|
||||
this.jumpVector = listOf(
|
||||
buffer.readString().asExpression(),
|
||||
buffer.readString().asExpression(),
|
||||
buffer.readString().asExpression()
|
||||
)
|
||||
this.driveFactor = buffer.readString().asExpression()
|
||||
this.reverseDriveFactor = buffer.readString().asExpression()
|
||||
this.strafeFactor = buffer.readString().asExpression()
|
||||
this.strafeFactor = buffer.readString().asExpression()
|
||||
val x = buffer.readDouble()
|
||||
val y = buffer.readDouble()
|
||||
val z = buffer.readDouble()
|
||||
this.lastVelocity = Vec3(x, y, z)
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -12,13 +12,17 @@ import com.bedrockk.molang.Expression
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.riding.states.CompositeState
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import com.cobblemon.mod.common.util.adapters.RideControllerAdapter
|
||||
import com.cobblemon.mod.common.util.asExpression
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.getString
|
||||
import com.cobblemon.mod.common.util.readString
|
||||
import com.cobblemon.mod.common.util.resolveFloat
|
||||
import com.cobblemon.mod.common.util.writeString
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.player.Player
|
||||
@@ -73,10 +77,6 @@ class FallToFlightCompositeController : RideController {
|
||||
}
|
||||
}
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
return getActiveController(entity).getStat(entity, stat)
|
||||
}
|
||||
|
||||
override fun speed(
|
||||
entity: PokemonEntity,
|
||||
driver: Player
|
||||
|
||||
+42
-154
@@ -9,21 +9,19 @@
|
||||
package com.cobblemon.mod.common.pokemon.riding.controllers
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.bedrockk.molang.runtime.MoLangMath.lerp
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.RidingAltPose
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.riding.states.GenericLandState
|
||||
import com.cobblemon.mod.common.pokemon.riding.states.JetAirState
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.util.Mth
|
||||
import net.minecraft.util.SmoothDouble
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.player.Player
|
||||
@@ -51,20 +49,20 @@ class GenericLandController : RideController {
|
||||
private set
|
||||
var strafeFactor = "0.2".asExpression()
|
||||
private set
|
||||
var sprintMod = "1.5".asExpression()
|
||||
private set
|
||||
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
//Degrees per second
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'LAND', 135.0, 90.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'LAND', 0.65, 0.3)".asExpression(),
|
||||
// In seconds to max speed
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'LAND', (1.0 / (20.0 * 0.5)), (1.0 / (20.0 * 5.0)))".asExpression(),
|
||||
// In Seconds
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'LAND', 30.0, 10.0)".asExpression(),
|
||||
// Block Jump Height
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'LAND', 10.0, 1.0)".asExpression()
|
||||
)
|
||||
var handlingExpr: Expression = "q.get_ride_stats('SKILL', 'LAND', 140.0, 20.0)".asExpression()
|
||||
private set
|
||||
var topSpeedExpr: Expression = "q.get_ride_stats('SPEED', 'LAND', 1.0, 0.3)".asExpression()
|
||||
private set
|
||||
// Max accel is a whole 1.0 in 1 second. The conversion in the function below is to convert seconds to ticks
|
||||
var accelExpr: Expression = "q.get_ride_stats('ACCELERATION', 'LAND', (1.0 / (20.0 * 0.5)), (1.0 / (20.0 * 5.0)))".asExpression()
|
||||
private set
|
||||
// Between 30 seconds and 10 seconds at the lowest when at full speed.
|
||||
var staminaExpr: Expression = "q.get_ride_stats('STAMINA', 'LAND', 30.0, 10.0)".asExpression()
|
||||
private set
|
||||
//Between a one block jump and a ten block jump
|
||||
var jumpExpr: Expression = "q.get_ride_stats('JUMP', 'LAND', 10.0, 1.0)".asExpression()
|
||||
private set
|
||||
|
||||
@Transient
|
||||
override val key: ResourceLocation = KEY
|
||||
@@ -89,53 +87,13 @@ class GenericLandController : RideController {
|
||||
}
|
||||
}
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
val state = getState(entity, ::GenericLandState)
|
||||
return state.rideVel.length().toFloat()
|
||||
}
|
||||
|
||||
override fun updatePassengerRotation(entity: PokemonEntity, driver: LivingEntity) {
|
||||
|
||||
//Take the inverse so that it cancels out how
|
||||
//much the entity rotates.
|
||||
val turnAmount = calcRotAmount(entity, driver)
|
||||
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val state = getState(entity, ::GenericLandState)
|
||||
val maxYawDiff = 90.0f
|
||||
|
||||
//Normalize the current rotation diff
|
||||
val rotMod = Mth.wrapDegrees(driver.yRot - entity.yRot) / maxYawDiff
|
||||
|
||||
val rotAmount = 10.0f
|
||||
|
||||
//Take the inverse so that you turn more at higher speeds
|
||||
val normSpeed = 1.0f - 0.5f*normalizeVal(state.rideVel.length(), 0.0, topSpeed).toFloat()
|
||||
|
||||
//driver.yRot += (entity.riding.deltaRotation.y - turnAmount)
|
||||
//driver.setYHeadRot(driver.yHeadRot + (entity.riding.deltaRotation.y) - turnAmount)
|
||||
}
|
||||
|
||||
override fun clampPassengerRotation(entity: PokemonEntity, driver: LivingEntity) {
|
||||
val f = Mth.wrapDegrees(driver.yRot - entity.yRot)
|
||||
val runtime = getRuntime(entity)
|
||||
val lookYawLimit = 90.0f
|
||||
val g = Mth.clamp(f, -lookYawLimit, lookYawLimit)
|
||||
driver.yRotO += g - f
|
||||
driver.yRot = driver.yRot + g - f
|
||||
driver.setYHeadRot(driver.yRot)
|
||||
}
|
||||
|
||||
override fun rotation(entity: PokemonEntity, driver: LivingEntity): Vec2 {
|
||||
|
||||
val turnAmount = calcRotAmount(entity, driver)
|
||||
|
||||
return Vec2(driver.xRot, entity.yRot + turnAmount )
|
||||
return Vec2(driver.xRot * 0.5f, driver.yRot)
|
||||
}
|
||||
|
||||
override fun velocity(entity: PokemonEntity, driver: Player, input: Vec3): Vec3 {
|
||||
@@ -158,7 +116,7 @@ class GenericLandController : RideController {
|
||||
|
||||
//Jump the thang!
|
||||
if (Minecraft.getInstance().options.keyJump.isDown() && entity.onGround()) {
|
||||
state.rideVel = Vec3(state.rideVel.x, 1.0, state.rideVel.z)
|
||||
state.rideVel = Vec3(state.rideVel.x, 2.0, state.rideVel.z)
|
||||
}
|
||||
|
||||
//This is cheap.
|
||||
@@ -169,8 +127,6 @@ class GenericLandController : RideController {
|
||||
|
||||
//entity.deltaMovement = entity.deltaMovement.lerp(velocity, 1.0)
|
||||
//state.currVel = state.currVel.add( f.toDouble() / 20.0, gravity / 20.0 , g.toDouble() / 20.0)
|
||||
|
||||
println("Z speed: %.2f".format(state.rideVel.z) + "->" + "Z speed: %.2f".format(entity.deltaMovement.horizontalDistance()))
|
||||
return state.rideVel
|
||||
}
|
||||
|
||||
@@ -221,28 +177,7 @@ class GenericLandController : RideController {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
override fun rideFovMult(entity: PokemonEntity, driver: Player): Float {
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val sprintTopSpeed = topSpeed * getRuntime(entity).resolveDouble(sprintMod) //TODO: make it so sprint mod is global and likely molang json configurable
|
||||
val state = getState(entity, ::GenericLandState)
|
||||
|
||||
//Must I ensure that topspeed is greater than minimum?
|
||||
val normalizedSprintSpeed = normalizeVal(state.rideVel.z, topSpeed, sprintTopSpeed)
|
||||
|
||||
//Only ever want the fov change to be a max of 0.2 and for it to have non linear scaling.
|
||||
val fovChange = 1.0f + normalizedSprintSpeed.pow(2).toFloat() * 0.2f
|
||||
return fovChange
|
||||
|
||||
}
|
||||
|
||||
override fun getActiveRidingAltPose(entity: PokemonEntity, driver: Player): RidingAltPose {
|
||||
//TODO: Should this be converted to a sprint flag?
|
||||
val isSprinting = Minecraft.getInstance().options.keySprint.isDown
|
||||
val pose = if (isSprinting) RidingAltPose.SPRINTING else RidingAltPose.NONE
|
||||
return pose
|
||||
}
|
||||
|
||||
override fun inertia(entity: PokemonEntity ): Double = 0.7
|
||||
override fun inertia(entity: PokemonEntity ): Double = 0.3
|
||||
|
||||
override fun encode(buffer: RegistryFriendlyByteBuf) {
|
||||
super.encode(buffer)
|
||||
@@ -270,89 +205,42 @@ class GenericLandController : RideController {
|
||||
}
|
||||
|
||||
/*
|
||||
* Normalizes the given value between a min and a max.
|
||||
* The result is clamped between 0.0 and 1.0, where 0.0 represents x is at or below min
|
||||
* and 1.0 represents x is at or above it.
|
||||
* Normalizes the current speed between minSpeed and maxSpeed.
|
||||
* The result is clamped between 0.0 and 1.0, where 0.0 represents minSpeed and 1.0 represents maxSpeed.
|
||||
*/
|
||||
fun normalizeVal(x: Double, min: Double, max: Double): Double {
|
||||
require(max > min) { "max must be greater than min" }
|
||||
return ((x - min) / (max - min)).coerceIn(0.0, 1.0)
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculates the rotation amount given the difference between
|
||||
* the current player y rot and entity y rot. This gives the
|
||||
* affect of influencing a rides rotation through the mouse
|
||||
* without it being instant.
|
||||
*/
|
||||
fun calcRotAmount(entity: PokemonEntity, driver: LivingEntity): Float {
|
||||
val state = getState(entity, ::GenericLandState)
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
//In degrees per second
|
||||
val handling = this.getStat(entity, RidingStat.SKILL)
|
||||
val maxYawDiff = 90.0f
|
||||
|
||||
//Normalize the current rotation diff
|
||||
val rotDiff = Mth.wrapDegrees(driver.yRot - entity.yRot)
|
||||
val rotDiffNorm = rotDiff / maxYawDiff
|
||||
|
||||
//Take the square root so that the ride levels out quicker when at lower differences between entity
|
||||
//y and driver y
|
||||
//This influences the speed of the turn based on how far in one direction you're looking
|
||||
val rotDiffMod = (sqrt(abs(rotDiffNorm)) * rotDiffNorm.sign)
|
||||
|
||||
//Take the inverse so that you turn more at higher speeds
|
||||
val normSpeed = 1.0f // = 1.0f - 0.5f*normalizeVal(state.rideVel.length(), 0.0, topSpeed).toFloat()
|
||||
|
||||
//Ensure you only ever rotate as much difference as there is between the angles.
|
||||
val turnSpeed = handling.toFloat() / 20.0f * rotDiffMod * normSpeed
|
||||
val rotAmount = turnSpeed.coerceIn(-abs(rotDiff), abs(rotDiff))
|
||||
|
||||
return rotAmount
|
||||
fun normalizeSpeed(currSpeed: Double, minSpeed: Double, maxSpeed: Double): Double {
|
||||
require(maxSpeed > minSpeed) { "maxSpeed must be greater than minSpeed" }
|
||||
return ((currSpeed - minSpeed) / (maxSpeed - minSpeed)).coerceIn(0.0, 1.0)
|
||||
}
|
||||
|
||||
fun calculateRideSpaceVel( entity: PokemonEntity, driver: Player, state: GenericLandState){
|
||||
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val accel = this.getStat(entity, RidingStat.ACCELERATION)
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
val accel = getRuntime(entity).resolveDouble(accelExpr)
|
||||
val speed = state.rideVel.length()
|
||||
|
||||
val reverseMod = 1.0 / 3.0
|
||||
val isSprinting = Minecraft.getInstance().options.keySprint.isDown
|
||||
val sprintMod = getRuntime(entity).resolveDouble(sprintMod)
|
||||
val minSpeed = 0.0
|
||||
|
||||
//speed up and slow down based on input
|
||||
if ((driver.zza != 0.0f && state.rideVel.z < topSpeed && !isSprinting) ||
|
||||
(driver.zza != 0.0f && state.rideVel.z < topSpeed * sprintMod && isSprinting)) {
|
||||
//make sure it can't exceed top speed
|
||||
val forwardInput = when {
|
||||
driver.zza > 0 && state.rideVel.z > topSpeed && !isSprinting -> 0.0
|
||||
driver.zza < 0 && state.rideVel.z < (-topSpeed * reverseMod) && !isSprinting -> 0.0
|
||||
driver.zza > 0 && state.rideVel.z > topSpeed * sprintMod && isSprinting -> 0.0
|
||||
driver.zza < 0 && state.rideVel.z < (-topSpeed * sprintMod * reverseMod) && isSprinting -> 0.0
|
||||
else -> driver.zza.sign
|
||||
}
|
||||
|
||||
state.rideVel = Vec3(
|
||||
state.rideVel.x,
|
||||
state.rideVel.y,
|
||||
(state.rideVel.z + (accel * forwardInput.toDouble())))
|
||||
if (driver.zza > 0.0 && speed <= topSpeed && state.stamina > 0.0f) {
|
||||
//modify acceleration to be slower when at closer speeds to top speed
|
||||
val accelMod = max((normalizeSpeed(speed, minSpeed, topSpeed) - 1).pow(2), 0.1)
|
||||
state.rideVel = Vec3(state.rideVel.x, state.rideVel.y, min(state.rideVel.z + (accel * accelMod) , topSpeed))
|
||||
}
|
||||
//Otherwise if there is no input then apply deceleration
|
||||
else if (driver.zza == 0.0f) {
|
||||
//Make deceleration constant no matter the stats
|
||||
val decelRate = 1.0 / 20.0
|
||||
state.rideVel = Vec3(
|
||||
state.rideVel.x,
|
||||
state.rideVel.y,
|
||||
lerp( state.rideVel.z, 0.0, decelRate )
|
||||
)
|
||||
else if (driver.zza >= 0.0 && state.stamina == 0.0f || speed > topSpeed) {
|
||||
state.rideVel = Vec3(state.rideVel.x, state.rideVel.y, max(state.rideVel.z - ((accel) / 4) , minSpeed))
|
||||
}
|
||||
else if (driver.zza < 0.0 && speed > minSpeed) {
|
||||
//modify deccel to be slower when at closer speeds to minimum speed
|
||||
val deccelMod = max( -(normalizeSpeed(speed, minSpeed, topSpeed)) + 1, 0.0)
|
||||
|
||||
//Decelerate currently always a constant half of max acceleration.
|
||||
state.rideVel = Vec3(state.rideVel.x, state.rideVel.y, max( state.rideVel.z - ((accel * deccelMod) / 2) , minSpeed))
|
||||
}
|
||||
|
||||
//If on the ground then stop the increase of rideVel's gravity velocity
|
||||
if (!entity.onGround()) {
|
||||
state.rideVel = Vec3(state.rideVel.x, max(state.rideVel.y - 0.1, -1.0) , state.rideVel.z)
|
||||
} else {
|
||||
state.rideVel = Vec3(state.rideVel.x, max(state.rideVel.y - 0.2, -1.0) , state.rideVel.z)
|
||||
|
||||
if (entity.onGround()) {
|
||||
state.rideVel = Vec3(state.rideVel.x, 0.0 , state.rideVel.z)
|
||||
}
|
||||
|
||||
|
||||
+20
-30
@@ -8,15 +8,20 @@
|
||||
|
||||
package com.cobblemon.mod.common.pokemon.riding.controllers
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import com.cobblemon.mod.common.util.asExpression
|
||||
import com.cobblemon.mod.common.util.blockPositionsAsListRounded
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.getString
|
||||
import com.cobblemon.mod.common.util.readString
|
||||
import com.cobblemon.mod.common.util.resolveBoolean
|
||||
import com.cobblemon.mod.common.util.resolveFloat
|
||||
import com.cobblemon.mod.common.util.writeString
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
@@ -32,20 +37,6 @@ class GenericLiquidController : RideController {
|
||||
val KEY: ResourceLocation = cobblemonResource("swim/generic")
|
||||
}
|
||||
|
||||
override val key: ResourceLocation = KEY
|
||||
override val poseProvider: PoseProvider = PoseProvider(PoseType.FLOAT)
|
||||
.with(PoseOption(PoseType.SWIM) { it.isSwimming && it.entityData.get(PokemonEntity.MOVING) })
|
||||
override val condition: (PokemonEntity) -> Boolean = { entity ->
|
||||
//This could be kinda weird... what if the top of the mon is in a fluid but the bottom isnt?
|
||||
Shapes.create(entity.boundingBox).blockPositionsAsListRounded().any {
|
||||
if (entity.isInWater || entity.isUnderWater) {
|
||||
return@any true
|
||||
}
|
||||
val blockState = entity.level().getBlockState(it)
|
||||
return@any !blockState.fluidState.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
var canJump = "true".asExpression()
|
||||
private set
|
||||
var jumpVector = listOf("0".asExpression(), "0.3".asExpression(), "0".asExpression())
|
||||
@@ -59,19 +50,18 @@ class GenericLiquidController : RideController {
|
||||
var strafeFactor = "0.2".asExpression()
|
||||
private set
|
||||
|
||||
//TODO: These are temp and need to be updated to real values
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'LIQUID', 135.0, 45.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'LIQUID', 0.6, 0.2)".asExpression(),
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'LIQUID', (1.0 / (20.0 * 3.0)), (1.0 / (20.0 * 8.0)))".asExpression(),
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'LIQUID', 120.0, 20.0)".asExpression(),
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'LIQUID', 200.0, 128.0)".asExpression()
|
||||
)
|
||||
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
override val key: ResourceLocation = KEY
|
||||
override val poseProvider: PoseProvider = PoseProvider(PoseType.FLOAT)
|
||||
.with(PoseOption(PoseType.SWIM) { it.isSwimming && it.entityData.get(PokemonEntity.MOVING) })
|
||||
override val condition: (PokemonEntity) -> Boolean = { entity ->
|
||||
//This could be kinda weird... what if the top of the mon is in a fluid but the bottom isnt?
|
||||
Shapes.create(entity.boundingBox).blockPositionsAsListRounded().any {
|
||||
if (entity.isInWater || entity.isUnderWater) {
|
||||
return@any true
|
||||
}
|
||||
val blockState = entity.level().getBlockState(it)
|
||||
return@any !blockState.fluidState.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
|
||||
-15
@@ -44,21 +44,6 @@ class GliderAirController : RideController {
|
||||
var canStrafe: Expression = "false".asExpression()
|
||||
private set
|
||||
|
||||
//TODO: These are temp and need to be updated to real values
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'AIR', 135.0, 45.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'AIR', 1.0, 0.35)".asExpression(),
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'AIR', (1.0 / (20.0 * 3.0)), (1.0 / (20.0 * 8.0)))".asExpression(),
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'AIR', 120.0, 20.0)".asExpression(),
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'AIR', 200.0, 128.0)".asExpression()
|
||||
)
|
||||
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
return getRuntime(entity).resolveFloat(speed)
|
||||
}
|
||||
|
||||
-15
@@ -14,7 +14,6 @@ import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.util.*
|
||||
@@ -64,20 +63,6 @@ class HelicopterAirController : RideController {
|
||||
var speed: Expression = "1.0".asExpression()
|
||||
private set
|
||||
|
||||
//TODO: These are temp and need to be updated to real values
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'AIR', 135.0, 45.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'AIR', 1.0, 0.35)".asExpression(),
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'AIR', (1.0 / (20.0 * 3.0)), (1.0 / (20.0 * 8.0)))".asExpression(),
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'AIR', 120.0, 20.0)".asExpression(),
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'AIR', 200.0, 128.0)".asExpression()
|
||||
)
|
||||
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
//Increased max speed to exaggerate movement.
|
||||
|
||||
+33
-24
@@ -9,12 +9,12 @@
|
||||
package com.cobblemon.mod.common.pokemon.riding.controllers
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.cobblemon.mod.common.Rollable
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.riding.states.JetAirState
|
||||
@@ -36,36 +36,35 @@ class JetAirController : RideController {
|
||||
|
||||
var gravity: Expression = "0".asExpression()
|
||||
private set
|
||||
|
||||
var minSpeed: Expression = "1.2".asExpression()
|
||||
private set
|
||||
//TODO: Think about converting this to fully rely on the skillExpr evaluation
|
||||
var handlingExpr: Expression = "q.get_ride_stats('SKILL', 'AIR', 140.0, 20.0)".asExpression()
|
||||
private set
|
||||
var handlingYawExpr: Expression = "q.get_ride_stats('SKILL', 'AIR', 25.0, 8.0)".asExpression()
|
||||
private set
|
||||
var topSpeedExpr: Expression = "q.get_ride_stats('SPEED', 'AIR', 2.5, 1.0)".asExpression()
|
||||
private set
|
||||
// Max accel is a whole 1.0 in 1 second. The conversion in the function below is to convert seconds to ticks
|
||||
var accelExpr: Expression = "q.get_ride_stats('ACCELERATION', 'AIR', (1.0 / (20.0 * 1.0)), (1.0 / (20.0 * 5.0)))".asExpression()
|
||||
private set
|
||||
// Between 60 seconds and 10 seconds at the lowest when at full speed.
|
||||
var staminaExpr: Expression = "q.get_ride_stats('STAMINA', 'AIR', 60.0, 10.0)".asExpression()
|
||||
private set
|
||||
var jumpExpr: Expression = "q.get_ride_stats('JUMP', 'AIR', 300.0, 128.0)".asExpression()
|
||||
private set
|
||||
|
||||
// Make configurable by json
|
||||
var infiniteStamina: Expression = "false".asExpression()
|
||||
private set
|
||||
var infiniteAltitude: Expression = "false".asExpression()
|
||||
private set
|
||||
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'AIR', 140.0, 20.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'AIR', 2.5, 1.0)".asExpression(),
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'AIR', (1.0 / (20.0 * 1.0)), (1.0 / (20.0 * 5.0)))".asExpression(),
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'AIR', 60.0, 10.0)".asExpression(),
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'AIR', 300.0, 128.0)".asExpression()
|
||||
)
|
||||
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
|
||||
//retrieve stats
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val staminaStat = this.getStat(entity, RidingStat.STAMINA)
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
val staminaStat = getRuntime(entity).resolveDouble(staminaExpr)
|
||||
|
||||
//retrieve state
|
||||
val state = getState(entity, ::JetAirState)
|
||||
@@ -123,7 +122,7 @@ class JetAirController : RideController {
|
||||
//If stamina has run out then initiate forced glide down.
|
||||
upForce = if(state.stamina > 0.0) upForce else -0.7
|
||||
|
||||
val altitudeLimit = this.getStat(entity, RidingStat.JUMP)
|
||||
val altitudeLimit = getRuntime(entity).resolveDouble(jumpExpr)
|
||||
|
||||
//Only limit altitude if altitude is not infinite
|
||||
if (!getRuntime(entity).resolveBoolean(infiniteAltitude)) {
|
||||
@@ -186,7 +185,7 @@ class JetAirController : RideController {
|
||||
state.currMouseYForce = (state.currMouseYForce + (0.0015 * yMouse * invertPitch)).coerceIn(-1.0, 1.0)
|
||||
|
||||
//Get handling in degrees per second
|
||||
var handling = this.getStat(entity, RidingStat.SKILL)
|
||||
var handling = getRuntime(entity).resolveDouble(handlingExpr)
|
||||
|
||||
//convert it to delta time
|
||||
handling *= (cappedDeltaTime)
|
||||
@@ -240,7 +239,7 @@ class JetAirController : RideController {
|
||||
override fun shouldRoll(entity: PokemonEntity) = true
|
||||
|
||||
override fun rideFovMult(entity: PokemonEntity, driver: Player): Float {
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
val minSpeed = getRuntime(entity).resolveDouble(minSpeed)
|
||||
val state = getState(entity, ::JetAirState)
|
||||
|
||||
@@ -257,7 +256,12 @@ class JetAirController : RideController {
|
||||
super.encode(buffer)
|
||||
buffer.writeString(gravity.toString())
|
||||
buffer.writeString(minSpeed.toString())
|
||||
buffer.writeString(handlingExpr.toString())
|
||||
buffer.writeString(handlingYawExpr.toString())
|
||||
buffer.writeString(topSpeedExpr.toString())
|
||||
buffer.writeString(accelExpr.toString())
|
||||
buffer.writeString(jumpExpr.toString())
|
||||
buffer.writeString(staminaExpr.toString())
|
||||
buffer.writeString(infiniteStamina.toString())
|
||||
buffer.writeString(infiniteAltitude.toString())
|
||||
}
|
||||
@@ -265,7 +269,12 @@ class JetAirController : RideController {
|
||||
override fun decode(buffer: RegistryFriendlyByteBuf) {
|
||||
gravity = buffer.readString().asExpression()
|
||||
minSpeed = buffer.readString().asExpression()
|
||||
handlingExpr = buffer.readString().asExpression()
|
||||
handlingYawExpr = buffer.readString().asExpression()
|
||||
topSpeedExpr = buffer.readString().asExpression()
|
||||
accelExpr = buffer.readString().asExpression()
|
||||
jumpExpr = buffer.readString().asExpression()
|
||||
staminaExpr = buffer.readString().asExpression()
|
||||
infiniteStamina = buffer.readString().asExpression()
|
||||
infiniteAltitude = buffer.readString().asExpression()
|
||||
}
|
||||
@@ -279,9 +288,9 @@ class JetAirController : RideController {
|
||||
*/
|
||||
fun calculateRideSpaceVel( entity: PokemonEntity, driver: Player, state: JetAirState){
|
||||
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val accel = this.getStat(entity, RidingStat.ACCELERATION)
|
||||
val altitudeLimit = this.getStat(entity, RidingStat.JUMP)
|
||||
val topSpeed = getRuntime(entity).resolveDouble(topSpeedExpr)
|
||||
val accel = getRuntime(entity).resolveDouble(accelExpr)
|
||||
val altitudeLimit = getRuntime(entity).resolveDouble(jumpExpr)
|
||||
val minSpeed = getRuntime(entity).resolveDouble(minSpeed)
|
||||
val speed = state.rideVel.length()
|
||||
|
||||
|
||||
+6
-18
@@ -12,8 +12,6 @@ import com.bedrockk.molang.Expression
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.RidingAltPose
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
@@ -69,10 +67,6 @@ class RunUpToFlightCompositeController : RideController {
|
||||
}
|
||||
}
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
return getActiveController(entity).getStat(entity, stat)
|
||||
}
|
||||
|
||||
override fun speed(
|
||||
entity: PokemonEntity,
|
||||
driver: Player
|
||||
@@ -82,8 +76,9 @@ class RunUpToFlightCompositeController : RideController {
|
||||
state.timeTransitioned + 20 < entity.level().gameTime) {
|
||||
|
||||
//Pass the speed to the next state
|
||||
val flightState = flightController.getState( entity, ::BirdAirState )
|
||||
val groundState = landController.getState( entity, ::GenericLandState )
|
||||
val flightState = flightController.getState(entity, ::BirdAirState)
|
||||
val groundState = landController.getState(entity, ::GenericLandState)
|
||||
groundState.currSpeed = flightState.currSpeed
|
||||
groundState.rideVel = flightState.rideVel
|
||||
groundState.stamina = flightState.stamina
|
||||
|
||||
@@ -99,6 +94,7 @@ class RunUpToFlightCompositeController : RideController {
|
||||
//Pass the speed to the next state
|
||||
val flightState = flightController.getState( entity, ::BirdAirState )
|
||||
val groundState = landController.getState( entity, ::GenericLandState )
|
||||
flightState.currSpeed = groundState.currSpeed
|
||||
flightState.rideVel = groundState.rideVel
|
||||
flightState.stamina = groundState.stamina
|
||||
|
||||
@@ -116,14 +112,6 @@ class RunUpToFlightCompositeController : RideController {
|
||||
return getActiveController(entity).rotation(entity, driver)
|
||||
}
|
||||
|
||||
override fun updatePassengerRotation(entity: PokemonEntity, driver: LivingEntity) {
|
||||
return getActiveController(entity).updatePassengerRotation(entity, driver)
|
||||
}
|
||||
|
||||
override fun clampPassengerRotation(entity: PokemonEntity, driver: LivingEntity) {
|
||||
return getActiveController(entity).clampPassengerRotation(entity, driver)
|
||||
}
|
||||
|
||||
override fun velocity(
|
||||
entity: PokemonEntity,
|
||||
driver: Player,
|
||||
@@ -172,8 +160,8 @@ class RunUpToFlightCompositeController : RideController {
|
||||
|
||||
override fun useAngVelSmoothing(entity: PokemonEntity): Boolean = getActiveController(entity).useAngVelSmoothing(entity)
|
||||
|
||||
override fun getActiveRidingAltPose(entity: PokemonEntity, driver: Player): RidingAltPose {
|
||||
return getActiveController(entity).getActiveRidingAltPose(entity, driver)
|
||||
override fun useRidingAltPose(entity: PokemonEntity, driver: Player): Boolean {
|
||||
return getActiveController(entity).useRidingAltPose(entity, driver)
|
||||
}
|
||||
|
||||
override fun rotationOnMouseXY
|
||||
|
||||
-14
@@ -12,7 +12,6 @@ import com.bedrockk.molang.Expression
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
@@ -68,10 +67,6 @@ class RunUpToJetFlightCompositeController : RideController {
|
||||
}
|
||||
}
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
return getActiveController(entity).getStat(entity, stat)
|
||||
}
|
||||
|
||||
//TODO: This composite controller needs to have the jet lift off at a certain speed.
|
||||
//maybe just pressing shift or space? Unsure, will need to test to see what works best.
|
||||
override fun speed(
|
||||
@@ -130,15 +125,6 @@ class RunUpToJetFlightCompositeController : RideController {
|
||||
return getActiveController(entity).rotation(entity, driver)
|
||||
}
|
||||
|
||||
override fun clampPassengerRotation(entity: PokemonEntity, driver: LivingEntity) {
|
||||
return getActiveController(entity).clampPassengerRotation(entity, driver)
|
||||
}
|
||||
|
||||
override fun updatePassengerRotation(entity: PokemonEntity, driver: LivingEntity) {
|
||||
return getActiveController(entity).updatePassengerRotation(entity, driver)
|
||||
}
|
||||
|
||||
|
||||
override fun velocity(
|
||||
entity: PokemonEntity,
|
||||
driver: Player,
|
||||
|
||||
-18
@@ -8,17 +8,13 @@
|
||||
|
||||
package com.cobblemon.mod.common.pokemon.riding.controllers
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseOption
|
||||
import com.cobblemon.mod.common.api.riding.controller.posing.PoseProvider
|
||||
import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.util.asExpression
|
||||
import com.cobblemon.mod.common.util.blockPositionsAsListRounded
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.resolveDouble
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
@@ -48,24 +44,10 @@ class SwimDashController : RideController {
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: These are temp and need to be updated to real values
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'LIQUID', 135.0, 45.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'LIQUID', 0.6, 0.2)".asExpression(),
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'LIQUID', (1.0 / (20.0 * 3.0)), (1.0 / (20.0 * 8.0)))".asExpression(),
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'LIQUID', 120.0, 20.0)".asExpression(),
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'LIQUID', 200.0, 128.0)".asExpression()
|
||||
)
|
||||
|
||||
/** Indicates that we are currently enacting a dash, and that further movement inputs should be ignored */
|
||||
private var dashing = false
|
||||
private var ticks = 0
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
if(this.dashing) {
|
||||
if(this.ticks++ >= DASH_TICKS) {
|
||||
|
||||
+49
-94
@@ -8,7 +8,6 @@
|
||||
|
||||
package com.cobblemon.mod.common.pokemon.riding.controllers
|
||||
|
||||
import com.bedrockk.molang.Expression
|
||||
import com.bedrockk.molang.runtime.value.DoubleValue
|
||||
import com.cobblemon.mod.common.api.riding.RidingStyle
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
@@ -18,13 +17,17 @@ import com.cobblemon.mod.common.api.riding.stats.RidingStat
|
||||
import com.cobblemon.mod.common.entity.PoseType
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import com.cobblemon.mod.common.pokemon.riding.controllers.BirdAirController.Companion
|
||||
import com.cobblemon.mod.common.pokemon.riding.states.VehicleLandState
|
||||
import com.cobblemon.mod.common.util.*
|
||||
import net.minecraft.client.Minecraft
|
||||
import com.cobblemon.mod.common.util.asExpression
|
||||
import com.cobblemon.mod.common.util.blockPositionsAsListRounded
|
||||
import com.cobblemon.mod.common.util.cobblemonResource
|
||||
import com.cobblemon.mod.common.util.getString
|
||||
import com.cobblemon.mod.common.util.readString
|
||||
import com.cobblemon.mod.common.util.resolveBoolean
|
||||
import com.cobblemon.mod.common.util.resolveFloat
|
||||
import com.cobblemon.mod.common.util.writeString
|
||||
import kotlin.math.absoluteValue
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf
|
||||
import net.minecraft.resources.ResourceLocation
|
||||
import net.minecraft.sounds.SoundEvents
|
||||
import net.minecraft.util.Mth
|
||||
import net.minecraft.world.entity.LivingEntity
|
||||
import net.minecraft.world.entity.player.Player
|
||||
@@ -33,13 +36,49 @@ import net.minecraft.world.phys.Vec3
|
||||
import net.minecraft.world.phys.shapes.Shapes
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sign
|
||||
|
||||
class VehicleLandController : RideController {
|
||||
companion object {
|
||||
val KEY: ResourceLocation = cobblemonResource("land/vehicle")
|
||||
|
||||
val MAXTOPSPEED = 1.0 // 20 bl/s
|
||||
val MINTOPSPEED = 0.35 // 7 bl/s
|
||||
//val MINSPEED = 0.25 // 5 bl/s
|
||||
|
||||
//Accel will lie between 1.0 second and 5.0 seconds
|
||||
val MAXACCEL = (MAXTOPSPEED ) / (20*3) //3.0 second to max speed
|
||||
val MINACCEL = (MAXTOPSPEED ) / (20*8) // 8 seconds to max speed
|
||||
|
||||
//Can rotate 90 degrees
|
||||
val MAXHANDLING = 90.0
|
||||
val MINHANDLING = 30.0
|
||||
|
||||
|
||||
val MAXYAWHANDLING = 16.0
|
||||
val MINYAWHANDLING = 8.0
|
||||
}
|
||||
|
||||
var canJump = "true".asExpression()
|
||||
private set
|
||||
var jumpVector = listOf("0".asExpression(), "0.3".asExpression(), "0".asExpression())
|
||||
private set
|
||||
var speed = "0.3".asExpression()
|
||||
private set
|
||||
var driveFactor = "1.0".asExpression()
|
||||
private set
|
||||
var reverseDriveFactor = "0.25".asExpression()
|
||||
private set
|
||||
|
||||
var minimumSpeedToTurn = "0.1".asExpression()
|
||||
private set
|
||||
var rotationSpeed = "45/20".asExpression()
|
||||
private set
|
||||
var lookYawLimit = "101".asExpression()
|
||||
private set
|
||||
|
||||
var currSpeed = 0.0
|
||||
private set
|
||||
|
||||
@Transient
|
||||
override val key: ResourceLocation = KEY
|
||||
@Transient
|
||||
@@ -63,57 +102,17 @@ class VehicleLandController : RideController {
|
||||
}
|
||||
}
|
||||
|
||||
var canJump = "true".asExpression()
|
||||
private set
|
||||
var jumpVector = listOf("0".asExpression(), "0.3".asExpression(), "0".asExpression())
|
||||
private set
|
||||
var speed = "0.3".asExpression()
|
||||
private set
|
||||
var driveFactor = "1.0".asExpression()
|
||||
private set
|
||||
var reverseDriveFactor = "0.25".asExpression()
|
||||
private set
|
||||
|
||||
var minimumSpeedToTurn = "0.1".asExpression()
|
||||
private set
|
||||
var rotationSpeed = "45/20".asExpression()
|
||||
private set
|
||||
var lookYawLimit = "101".asExpression()
|
||||
private set
|
||||
|
||||
var currSpeed = 0.0
|
||||
private set
|
||||
|
||||
//TODO: Replace these temp values
|
||||
private val statExpressions: Map<RidingStat, Expression> = mapOf(
|
||||
RidingStat.SKILL to "q.get_ride_stats('SKILL', 'LAND', 140.0, 20.0)".asExpression(),
|
||||
RidingStat.SPEED to "q.get_ride_stats('SPEED', 'LAND', 1.0, 0.3)".asExpression(),
|
||||
// In seconds to max speed
|
||||
RidingStat.ACCELERATION to "q.get_ride_stats('ACCELERATION', 'LAND', (1.0 / (20.0 * 0.5)), (1.0 / (20.0 * 5.0)))".asExpression(),
|
||||
// In Seconds
|
||||
RidingStat.STAMINA to "q.get_ride_stats('STAMINA', 'LAND', 30.0, 10.0)".asExpression(),
|
||||
// Block Jump Height
|
||||
RidingStat.JUMP to "q.get_ride_stats('JUMP', 'LAND', 10.0, 1.0)".asExpression()
|
||||
)
|
||||
|
||||
|
||||
|
||||
override fun getStat(entity: PokemonEntity, stat: RidingStat): Double {
|
||||
val expr = statExpressions[stat] ?: return 0.0
|
||||
return getRuntime(entity).resolveDouble(expr)
|
||||
}
|
||||
|
||||
override fun speed(entity: PokemonEntity, driver: Player): Float {
|
||||
|
||||
val topSpeed = this.getStat(entity, RidingStat.SPEED)
|
||||
val accel = this.getStat(entity, RidingStat.ACCELERATION)
|
||||
val topSpeed = entity.getRideStat(RidingStat.SPEED, RidingStyle.AIR, MINTOPSPEED, MAXTOPSPEED)
|
||||
val accel = entity.getRideStat(RidingStat.ACCELERATION, RidingStyle.AIR, MINACCEL, MAXACCEL)
|
||||
|
||||
//speed up and slow down based on input
|
||||
if (driver.zza > 0.0 && currSpeed < topSpeed) {
|
||||
currSpeed = min(currSpeed + accel , topSpeed)
|
||||
} else if (driver.zza < 0.0 && currSpeed > 0.0) {
|
||||
//Decelerate is now always a constant half of max acceleration.
|
||||
currSpeed = max(currSpeed - (accel / 2), 0.0)
|
||||
currSpeed = max(currSpeed - (MAXACCEL / 2), 0.0)
|
||||
}
|
||||
|
||||
return currSpeed.toFloat()
|
||||
@@ -121,51 +120,7 @@ class VehicleLandController : RideController {
|
||||
|
||||
override fun rotation(entity: PokemonEntity, driver: LivingEntity): Vec2 {
|
||||
val rotationDegrees = driver.xxa * getRuntime(entity).resolveFloat(this.rotationSpeed)
|
||||
val state = getState(entity, ::VehicleLandState)
|
||||
|
||||
if( Minecraft.getInstance().options.keyJump.isDown() ){
|
||||
//If the current drift has not been set and the car is rotating then set drift
|
||||
if( state.currDrift == 0.0 && rotationDegrees != 0.0f) {
|
||||
//Set to base value which will be half.
|
||||
state.currDrift = sign(rotationDegrees) * 2.5
|
||||
state.turnSmoother.reset()
|
||||
}
|
||||
|
||||
//Calculate any changes to drift
|
||||
val driftChangeRate = (1.0 / (20.0 * 0.15))
|
||||
|
||||
//If Drift is negative already
|
||||
if(state.currDrift < 0) {
|
||||
state.currDrift = (state.currDrift + (sign(rotationDegrees) * driftChangeRate)).coerceIn(-5.0, -1.0)
|
||||
}else{
|
||||
state.currDrift = (state.currDrift + (sign(rotationDegrees) * driftChangeRate)).coerceIn(1.0, 5.0)
|
||||
}
|
||||
return Vec2(driver.xRot, entity.yRot - state.currDrift.toFloat())
|
||||
}
|
||||
//If the drift key is not held then reset the curr drift to 0 and use normal rotation
|
||||
else{
|
||||
//If the drift key has just been released perform boost addition and drift reset
|
||||
if( state.currDrift != 0.0){
|
||||
state.turnSmoother.reset()
|
||||
state.currDrift = 0.0
|
||||
state.driftBoost = min(state.driftBoost + 1.0, 2.0)
|
||||
driver.level().playSound(
|
||||
null as Player?,
|
||||
driver.getX(),
|
||||
driver.getY(),
|
||||
driver.getZ(), SoundEvents.PLAYER_ATTACK_WEAK,
|
||||
driver.getSoundSource(), 1.0f, 0.2f
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
//Restrict turning while boost is active
|
||||
val boostRotDebuff = if( state.driftBoost != 0.0 ) 0.5f else 1.0f
|
||||
|
||||
return Vec2(driver.xRot, entity.yRot - (rotationDegrees * boostRotDebuff) )
|
||||
//return Vec2(driver.xRot, state.turnSmoother.getNewDeltaValue((entity.yRot - rotationDegrees).toDouble(), 1.0).toFloat())
|
||||
}
|
||||
|
||||
return Vec2(driver.xRot, entity.yRot - rotationDegrees)
|
||||
}
|
||||
|
||||
override fun velocity(entity: PokemonEntity, driver: Player, input: Vec3): Vec3 {
|
||||
|
||||
+3
-2
@@ -13,7 +13,8 @@ import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
data class BirdAirState(val entity: PokemonEntity) : RidingState {
|
||||
override var rideVel: Vec3 = Vec3.ZERO
|
||||
override var stamina: Float = 1.0f
|
||||
var currSpeed: Double = 0.0
|
||||
var stamina: Float = 1.0f
|
||||
var rideVel: Vec3 = Vec3.ZERO
|
||||
var gliding: Boolean = false
|
||||
}
|
||||
-3
@@ -11,11 +11,8 @@ package com.cobblemon.mod.common.pokemon.riding.states
|
||||
import com.cobblemon.mod.common.api.riding.RidingState
|
||||
import com.cobblemon.mod.common.api.riding.controller.RideController
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
open class CompositeState(pokemonEntity: PokemonEntity) : RidingState {
|
||||
override var rideVel: Vec3 = Vec3.ZERO
|
||||
override var stamina: Float = 1.0f
|
||||
var activeController: RideController? = null
|
||||
var timeTransitioned = -100L
|
||||
}
|
||||
-20
@@ -1,20 +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.pokemon.riding.states
|
||||
|
||||
import com.cobblemon.mod.common.api.riding.RidingState
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
data class DolphinLiquidState(val entity: PokemonEntity) : RidingState {
|
||||
override var rideVel: Vec3 = Vec3.ZERO
|
||||
override var stamina: Float = 1.0f
|
||||
var currSpeed: Double = 0.0
|
||||
var gliding: Boolean = false
|
||||
}
|
||||
+2
-2
@@ -13,7 +13,7 @@ import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
data class GenericLandState(val entity: PokemonEntity) : RidingState {
|
||||
override var rideVel: Vec3 = Vec3.ZERO
|
||||
override var stamina: Float = 1.0f
|
||||
var currSpeed: Double = 0.0
|
||||
var rideVel: Vec3 = Vec3.ZERO
|
||||
var stamina: Float = 1.0f
|
||||
}
|
||||
+2
-2
@@ -13,9 +13,9 @@ import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
data class JetAirState(val entity: PokemonEntity) : RidingState {
|
||||
override var rideVel: Vec3 = Vec3.ZERO
|
||||
override var stamina: Float = 1.0f
|
||||
var currSpeed: Double = 0.0
|
||||
var stamina: Float = 1.0f
|
||||
var rideVel: Vec3 = Vec3.ZERO
|
||||
var currMouseXForce: Double = 0.0
|
||||
var currMouseYForce: Double = 0.0
|
||||
}
|
||||
-3
@@ -9,10 +9,7 @@
|
||||
package com.cobblemon.mod.common.pokemon.riding.states
|
||||
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
class RunUpToFlightCompositeState(pokemonEntity: PokemonEntity) : CompositeState(pokemonEntity) {
|
||||
override var rideVel: Vec3 = Vec3.ZERO
|
||||
override var stamina: Float = 1.0f
|
||||
var currSpeed: Double = 0.0
|
||||
}
|
||||
-22
@@ -1,22 +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.pokemon.riding.states
|
||||
|
||||
import com.cobblemon.mod.common.api.riding.RidingState
|
||||
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
|
||||
import net.minecraft.util.SmoothDouble
|
||||
import net.minecraft.world.phys.Vec3
|
||||
|
||||
data class VehicleLandState(val entity: PokemonEntity) : RidingState {
|
||||
override var rideVel: Vec3 = Vec3.ZERO
|
||||
override var stamina: Float = 1.0f
|
||||
var currDrift: Double = 0.0
|
||||
var driftBoost: Double = 0.0
|
||||
var turnSmoother: SmoothDouble = SmoothDouble()
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.cobblemon.mod.common.util
|
||||
|
||||
import com.cobblemon.mod.common.Cobblemon
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URI
|
||||
|
||||
object HttpService {
|
||||
|
||||
val gson: Gson = GsonBuilder().create()
|
||||
|
||||
inline fun <reified T> get(url: String): HttpResponse<T> {
|
||||
val connection = (URI.create(url).toURL().openConnection() as HttpURLConnection).also {
|
||||
it.requestMethod = "GET"
|
||||
it.connectTimeout = 5000
|
||||
it.readTimeout = 5000
|
||||
it.useCaches = false
|
||||
}
|
||||
return readFromUrlConnection<T>(connection)
|
||||
}
|
||||
|
||||
inline fun <reified T> post(url: String, body: Any? = null): HttpResponse<T> {
|
||||
val bodyJson = gson.toJson(body)
|
||||
val bodyBytes = bodyJson.toByteArray(Charsets.UTF_8)
|
||||
|
||||
val connection = (URI.create(url).toURL().openConnection() as HttpURLConnection).also {
|
||||
it.requestMethod = "POST"
|
||||
it.doOutput = true
|
||||
it.connectTimeout = 5000
|
||||
it.readTimeout = 5000
|
||||
it.useCaches = false
|
||||
it.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
|
||||
it.setRequestProperty("Content-Length", bodyBytes.size.toString())
|
||||
}
|
||||
|
||||
connection.connect()
|
||||
connection.outputStream.use {
|
||||
it.write(bodyBytes)
|
||||
}
|
||||
|
||||
return readFromUrlConnection<T>(connection)
|
||||
}
|
||||
|
||||
inline fun <reified T> readFromUrlConnection(connection: HttpURLConnection): HttpResponse<T> {
|
||||
try {
|
||||
val status = connection.responseCode
|
||||
|
||||
if (status >= 400) {
|
||||
connection.errorStream.use {
|
||||
val error = readFromStream(it)
|
||||
return HttpResponse(error = HttpError(status, error), body = null)
|
||||
}
|
||||
}
|
||||
else {
|
||||
connection.inputStream.use {
|
||||
val bodyStr = readFromStream(it)
|
||||
return when {
|
||||
T::class == Unit::class -> HttpResponse(error = null, body = null)
|
||||
T::class == String::class -> HttpResponse(error = null, body = bodyStr as T)
|
||||
else -> HttpResponse(error = null, body = gson.fromJson(bodyStr, T::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e: Exception) {
|
||||
Cobblemon.LOGGER.error("Failed to read from connection url at ${connection.url}", e)
|
||||
return HttpResponse(error = HttpError(500, null), body = null)
|
||||
}
|
||||
}
|
||||
|
||||
fun readFromStream(stream: InputStream): String {
|
||||
ByteArrayOutputStream().use { result ->
|
||||
val buffer = ByteArray(1024)
|
||||
var length: Int
|
||||
while (stream.read(buffer).also { length = it } != -1) {
|
||||
result.write(buffer, 0, length)
|
||||
}
|
||||
return result.toString("UTF-8")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class HttpResponse<T>(val error: HttpError?, val body: T?)
|
||||
data class HttpError(val statusCode: Int, val details: String?)
|
||||
+2
-2
@@ -7,8 +7,8 @@
|
||||
"texture_width": 256,
|
||||
"texture_height": 128,
|
||||
"visible_bounds_width": 10,
|
||||
"visible_bounds_height": 7,
|
||||
"visible_bounds_offset": [0, 2.5, 0]
|
||||
"visible_bounds_height": 5,
|
||||
"visible_bounds_offset": [0, 1.5, 0]
|
||||
},
|
||||
"bones": [
|
||||
{
|
||||
|
||||
+1
-4
@@ -34,10 +34,7 @@
|
||||
"pivot": [0, 26.2, 0],
|
||||
"cubes": [
|
||||
{"origin": [-5, 25.2, -4], "size": [10, 7, 8], "inflate": 0.01, "uv": [26, 32]}
|
||||
],
|
||||
"locators": {
|
||||
"seat_1": [0, 28, 4]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "fin",
|
||||
|
||||
+1
-4
@@ -26,10 +26,7 @@
|
||||
"pivot": [0, 24.5, -1],
|
||||
"cubes": [
|
||||
{"origin": [-6, 18.5, -13.75], "size": [12, 12, 26], "uv": [52, 39]}
|
||||
],
|
||||
"locators": {
|
||||
"seat_1": [0, 30, 0]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "neck",
|
||||
|
||||
+4
-18
@@ -86,15 +86,8 @@
|
||||
"fly": {
|
||||
"poseTypes": ["FLY"],
|
||||
"isBattle": false,
|
||||
"condition": "!q.riding_alt_pose('GLIDING')",
|
||||
"animations": [
|
||||
"q.look('head_ai')",
|
||||
"q.bedrock('charizard', 'air_fly')",
|
||||
{
|
||||
"condition": "q.has_passenger",
|
||||
"animation": "q.bedrock('charizard', 'riding_look')"
|
||||
}
|
||||
],
|
||||
"condition": "!q.is_gliding",
|
||||
"animations": ["q.look('head_ai')", "q.bedrock('charizard', 'air_fly')"],
|
||||
"quirks": [
|
||||
"q.bedrock_quirk('charizard', 'blink')",
|
||||
"q.bedrock_quirk('charizard', 'air_fly_quirk')"
|
||||
@@ -103,15 +96,8 @@
|
||||
"glide": {
|
||||
"poseTypes": ["FLY"],
|
||||
"isBattle": false,
|
||||
"condition": "q.riding_alt_pose('GLIDING')",
|
||||
"animations": [
|
||||
"q.look('head_ai')",
|
||||
"q.bedrock('charizard', 'air_glide_TEST')",
|
||||
{
|
||||
"condition": "q.has_passenger",
|
||||
"animation": "q.bedrock('charizard', 'riding_look')"
|
||||
}
|
||||
],
|
||||
"condition": "q.is_gliding",
|
||||
"animations": ["q.look('head_ai')", "q.bedrock('charizard', 'air_glide_TEST')"],
|
||||
"quirks": [
|
||||
"q.bedrock_quirk('charizard', 'blink')"
|
||||
]
|
||||
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
{
|
||||
"portraitScale": 1.5,
|
||||
"portraitTranslation": [-1.0, 1.76, 0.0],
|
||||
"profileScale": 0.5,
|
||||
"profileTranslation": [0.0, 1.0, 0.0],
|
||||
"rootBone": "mudsdale",
|
||||
"animations": {
|
||||
"cry": "q.bedrock_stateful('mudsdale', 'cry')"
|
||||
},
|
||||
"poses": {
|
||||
"portrait": {
|
||||
"poseTypes": ["PORTRAIT", "PROFILE"],
|
||||
"isBattle": false,
|
||||
"isTouchingWater": false,
|
||||
"animations": [
|
||||
"q.look('head_ai')",
|
||||
"q.bedrock('mudsdale', 'ground_idle')"
|
||||
],
|
||||
"quirks": ["q.bedrock_quirk('mudsdale', 'blink')"]
|
||||
},
|
||||
"standing": {
|
||||
"poseTypes": ["STAND", "NONE"],
|
||||
"isBattle": false,
|
||||
"isTouchingWater": false,
|
||||
"animations": [
|
||||
"q.look('head_ai')",
|
||||
"q.bedrock('mudsdale', 'ground_idle')"
|
||||
],
|
||||
"quirks": ["q.bedrock_quirk('mudsdale', 'blink')"]
|
||||
},
|
||||
"walking": {
|
||||
"poseTypes": ["WALK"],
|
||||
"isTouchingWater": false,
|
||||
"condition": "!q.riding_alt_pose('SPRINTING')",
|
||||
"animations": [
|
||||
"q.look('head_ai')",
|
||||
"q.bedrock('mudsdale', 'ground_walk')"
|
||||
],
|
||||
"quirks": ["q.bedrock_quirk('mudsdale', 'blink')"]
|
||||
},
|
||||
"running": {
|
||||
"poseTypes": ["WALK"],
|
||||
"isTouchingWater": false,
|
||||
"condition": "q.riding_alt_pose('SPRINTING')",
|
||||
"animations": [
|
||||
"q.look('head_ai')",
|
||||
"q.bedrock('mudsdale', 'ground_run')"
|
||||
],
|
||||
"quirks": ["q.bedrock_quirk('mudsdale', 'blink')"]
|
||||
},
|
||||
"sleep": {
|
||||
"poseTypes": ["SLEEP"],
|
||||
"animations": ["q.bedrock('mudsdale', 'sleep')"],
|
||||
"quirks": ["q.bedrock_quirk('mudsdale', 'blink')"],
|
||||
"namedAnimations": {
|
||||
"cry": "q.bedrock_stateful('dummy', 'cry')"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
{
|
||||
{
|
||||
"species": "cobblemon:garchomp",
|
||||
"order": 1,
|
||||
"variations": [
|
||||
|
||||
@@ -1253,6 +1253,7 @@
|
||||
"key.cobblemon.translateportraitleft": "Translate Portrait Left",
|
||||
"key.cobblemon.translateportraitright": "Translate Portrait Right",
|
||||
"key.cobblemon.printmodelsettings": "Print Model Settings",
|
||||
"key.cobblemon.toggleshowdowndebugui": "Toggle Showdown Debugger UI",
|
||||
"key.cobblemon.categories.cobblemon.debug": "Cobblemon Debug",
|
||||
|
||||
"cobblemon.subtitle.poke_ball.capture_succeeded": "Poké Ball capture succeeds",
|
||||
@@ -7211,4 +7212,4 @@
|
||||
"cobblemon.ability.zenmode.desc": "Changes the Pokémon's shape when HP is half or less.",
|
||||
"cobblemon.ability.zerotohero": "Zero to Hero",
|
||||
"cobblemon.ability.zerotohero.desc": "The Pokémon transforms into its Hero Form when it switches out."
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"hitbox": "player",
|
||||
"presets": [
|
||||
|
||||
"cobblemon:looks_in_one_direction"
|
||||
],
|
||||
"variation": {
|
||||
"dirt": [
|
||||
@@ -105,4 +105,4 @@
|
||||
"garchomp level=100 pokeball=quick_ball held_item=cobblemon:yache_berry ability=roughskin nature=jolly moves=dragonclaw,earthquake,swordsdance,poisonjab hp_iv=31 attack_iv=31 defence_iv=31 special_attack_iv=31 special_defence_iv=31 speed_iv=31 hp_ev=6 attack_ev=252 speed_ev=252"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,5 +317,26 @@
|
||||
"tutor:waterpulse"
|
||||
],
|
||||
"preEvolution": "dragonair",
|
||||
"evolutions": []
|
||||
"evolutions": [],
|
||||
"riding": {
|
||||
"stats": {
|
||||
"SPEED": {
|
||||
"ranges": "30-60"
|
||||
},
|
||||
"ACCELERATION": {
|
||||
"ranges": "30-65"
|
||||
},
|
||||
"SKILL": {
|
||||
"ranges": "30-60"
|
||||
},
|
||||
"JUMP": {
|
||||
"ranges": "30-60"
|
||||
},
|
||||
"STAMINA": {
|
||||
"ranges": "35-75"
|
||||
}
|
||||
},
|
||||
"seats": [],
|
||||
"controller": null
|
||||
}
|
||||
}
|
||||
@@ -59,64 +59,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"riding": {
|
||||
"stats": {
|
||||
"SPEED": {
|
||||
"ranges": {
|
||||
"LAND": "100-101",
|
||||
"LIQUID": "5-20"
|
||||
}
|
||||
},
|
||||
"ACCELERATION": {
|
||||
"ranges": {
|
||||
"LAND": "100-101",
|
||||
"LIQUID": "50-80"
|
||||
}
|
||||
},
|
||||
"SKILL": {
|
||||
"ranges": {
|
||||
"LAND": "100-101",
|
||||
"LIQUID": "20-40"
|
||||
}
|
||||
},
|
||||
"JUMP": {
|
||||
"ranges": {
|
||||
"LAND": "100-101",
|
||||
"LIQUID": "5-10"
|
||||
}
|
||||
},
|
||||
"STAMINA": {
|
||||
"ranges": {
|
||||
"LAND": "100-101",
|
||||
"LIQUID": "25-65"
|
||||
}
|
||||
}
|
||||
},
|
||||
"seats": [
|
||||
{
|
||||
"offset": {
|
||||
"x": 0,
|
||||
"y": 0.4,
|
||||
"z": 0
|
||||
},
|
||||
"poseOffsets": [
|
||||
{
|
||||
"poseTypes": [
|
||||
"WALK"
|
||||
],
|
||||
"offset": {
|
||||
"x": 0,
|
||||
"y": 0.0,
|
||||
"z": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"controller": {
|
||||
"key": "cobblemon:land/generic"
|
||||
}
|
||||
},
|
||||
"drops": {
|
||||
"amount": 6,
|
||||
"entries": [
|
||||
|
||||
@@ -16,9 +16,9 @@ val bundle: Configuration by configurations.creating {
|
||||
loom {
|
||||
val clientConfig = runConfigs.getByName("client")
|
||||
clientConfig.runDir = "runClient"
|
||||
clientConfig.programArg("--username=AshKetchum")
|
||||
// clientConfig.programArg("--username=GaryOak")
|
||||
//This is AshKetchum's UUID so you get an Ash Ketchum skin
|
||||
clientConfig.programArg("--uuid=93e4e551-589a-41cb-ab2d-435266c8e035")
|
||||
// clientConfig.programArg("--uuid=93e4e551-589a-41cb-ab2d-435266c8e035")
|
||||
val serverConfig = runConfigs.getByName("server")
|
||||
serverConfig.runDir = "runServer"
|
||||
}
|
||||
@@ -59,4 +59,4 @@ tasks {
|
||||
dependsOn(copyJar)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user