Compare commits

...
Author SHA1 Message Date
whatsy 7468902b43 sort button implementation 2026-12-01 18:54:57 -05:00
Gertimoshka da9da12630 Infastructure of Sorting 2026-12-01 20:35:16 +01:00
14 changed files with 298 additions and 10 deletions

No files matched your search

@@ -26,7 +26,9 @@ class BagCategory(
val icon: ResourceLocation,
val whiteListTag: TagKey<Item>,
val blackListTag: TagKey<Item>,
val maxCount: Int
val maxCount: Int,
val defaultSort: ResourceLocation?,
val sortMethods: List<ResourceLocation>?
): StringRepresentable {
@Transient
var identifier: ResourceLocation = identifier
@@ -42,6 +44,13 @@ class BagCategory(
return false
}
fun getAllSortMethods(): List<ResourceLocation> {
val returnList = mutableListOf<ResourceLocation>()
returnList.add(defaultSort ?: BagSortComparators.DEFAULT_SORT)
sortMethods?.let { returnList.addAll(it) }
return returnList
}
fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeIdentifier(identifier)
buffer.writeInt(order)
@@ -49,6 +58,10 @@ class BagCategory(
buffer.writeIdentifier(whiteListTag.location)
buffer.writeIdentifier(blackListTag.location)
buffer.writeInt(maxCount)
buffer.writeIdentifier(defaultSort ?: BagSortComparators.DEFAULT_SORT)
val sortMethods = sortMethods.orEmpty()
buffer.writeInt(sortMethods.size)
buffer.writeCollection(sortMethods) { buf, method -> buf.writeIdentifier(method) }
}
companion object {
@@ -59,7 +72,9 @@ class BagCategory(
buffer.readIdentifier(),
TagKey.create(Registries.ITEM, buffer.readIdentifier()),
TagKey.create(Registries.ITEM, buffer.readIdentifier()),
buffer.readInt()
buffer.readInt(),
buffer.readIdentifier(),
buffer.readList { it.readIdentifier() }
)
}
}
@@ -0,0 +1,16 @@
package com.cobblemon.mod.common.api.bag
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.item.ItemStack
/**
* Event to register code-based functions to define sorting order
* Function compares 2 itemStacks, returns 0 if they are equal, less than 0
*/
class BagSortComparatorRegistryEvent {
val comparators = mutableMapOf<ResourceLocation, Comparator<ItemStack>>()
fun registerFunction(id: ResourceLocation, comparator: Comparator<ItemStack>) {
comparators[id] = comparator
}
}
@@ -0,0 +1,43 @@
package com.cobblemon.mod.common.api.bag
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.item.CreativeModeTabs
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
object BagSortComparators {
private val SORT_METHODS = mutableMapOf<ResourceLocation, Comparator<ItemStack>>()
val INPUT_ORDER = cobblemonResource("input_order")
val ALPHABETICAL = cobblemonResource("alphabetical")
val CREATIVE_MENU = cobblemonResource("creative_menu")
val DEFAULT_SORT = CREATIVE_MENU
fun registerComparator(type: ResourceLocation, comparator: Comparator<ItemStack>) {
SORT_METHODS[type] = comparator
}
fun getComparator(type: ResourceLocation): Comparator<ItemStack>? {
return SORT_METHODS[type]
}
private val creativeItemOrder: Map<Item, Int> by lazy {
buildMap {
CreativeModeTabs.searchTab().displayItems.forEachIndexed { index, stack ->
getOrPut(stack.item) { index }
}
}
}
fun setupComparators() {
registerComparator(ALPHABETICAL, compareBy { it.displayName.toString() })
registerComparator(CREATIVE_MENU, compareBy { creativeItemOrder[it.item] ?: Int.MAX_VALUE })
registerComparator(INPUT_ORDER, compareBy { null })
CobblemonEvents.BAG_SORTING_REGISTRATION.post(BagSortComparatorRegistryEvent()) { event ->
event.comparators.forEach { (type, comparator) -> registerComparator(type, comparator) }
}
}
}
@@ -8,6 +8,7 @@
package com.cobblemon.mod.common.api.events
import com.cobblemon.mod.common.api.bag.BagSortComparatorRegistryEvent
import com.cobblemon.mod.common.api.events.battles.BattleFaintedEvent
import com.cobblemon.mod.common.api.events.battles.BattleFledEvent
import com.cobblemon.mod.common.api.events.battles.BattleFleeAttemptEvent
@@ -393,4 +394,8 @@ object CobblemonEvents {
val HABITAT_SETTINGS_SAVED_PRE = CancelableObservable<SaveHabitatBlockSettingsEvent.Pre>()
@JvmField
val HABITAT_SETTINGS_SAVED_POST = EventObservable<SaveHabitatBlockSettingsEvent.Post>()
// Bag
@JvmField
val BAG_SORTING_REGISTRATION = EventObservable<BagSortComparatorRegistryEvent>()
}
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.gui.bag
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.client.sounds.SoundManager
import net.minecraft.network.chat.Component
class BagCycleSortButton(
x: Int,
y: Int,
val parent: CobblemonBagScreen,
val action: OnPress
): Button(x, y, WIDTH, HEIGHT, Component.empty(), action, DEFAULT_NARRATION), CobblemonRenderable {
companion object {
private const val WIDTH = 12
private const val HEIGHT = 10
private val LEFT_BUTTON = cobblemonResource("textures/gui/bag/button_left.png")
}
var enabled = false
override fun renderWidget(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
if (!enabled) return
blitk(
matrixStack = context.pose(),
texture = LEFT_BUTTON,
x = x / 0.5F, y = y / 0.5F,
width = WIDTH * 2, height = HEIGHT * 2,
textureHeight = 40,
vOffset = if (enabled) 20 else 0,
scale = 0.5f
)
if (isHovered) {
val currentCategory = BagCategories.getOrderedCategoriesList().getOrNull(parent.menu.currentlySelectedCategory)
val currentSort = currentCategory?.getAllSortMethods()[parent.menu.currentlySelectedSort]
currentSort?.let {
val lang = lang("bag.sort.${it.path}")
context.renderTooltip(Minecraft.getInstance().font, lang, mouseX, mouseY)
}
}
}
override fun playDownSound(handler: SoundManager) {}
}
@@ -0,0 +1,58 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.gui.bag
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.client.sounds.SoundManager
import net.minecraft.network.chat.Component
class BagSortAscendingButton(
x: Int,
y: Int,
val parent: CobblemonBagScreen,
val action: OnPress
): Button(x, y, WIDTH, HEIGHT, Component.empty(), action, DEFAULT_NARRATION), CobblemonRenderable {
companion object {
private const val WIDTH = 12
private const val HEIGHT = 10
private val LEFT_BUTTON = cobblemonResource("textures/gui/bag/button_left.png")
}
var enabled = false
override fun renderWidget(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
if (!enabled) return
blitk(
matrixStack = context.pose(),
texture = LEFT_BUTTON,
x = x / 0.5F, y = y / 0.5F,
width = WIDTH * 2, height = HEIGHT * 2,
textureHeight = 40,
vOffset = if (enabled) 20 else 0,
scale = 0.5f
)
if (isHovered) {
if (parent.menu.ascending) {
context.renderTooltip(Minecraft.getInstance().font, lang("bag.sort.ascending"), mouseX, mouseY)
} else {
context.renderTooltip(Minecraft.getInstance().font, lang("bag.sort.descending"), mouseX, mouseY)
}
}
}
override fun playDownSound(handler: SoundManager) {}
}
@@ -74,6 +74,8 @@ class CobblemonBagScreen(
lateinit var allItemsCategoryWidget: BagCategoryButton
lateinit var leftCategoryPageButton: BagCategoryPageButton
lateinit var rightCategoryPageButton: BagCategoryPageButton
lateinit var cycleCategorySortButton: BagCycleSortButton
lateinit var ascendingButton: BagSortAscendingButton
var currentCategoryPage = 0
var lastCategory = menu.currentlySelectedCategory
var lastScroll = menu.scroll
@@ -94,6 +96,7 @@ class CobblemonBagScreen(
BagCategoryButton(leftPos + 76 + i * 33, topPos, this, i) {
if (menu.currentlySelectedCategory != i) {
menu.changeCategory(i)
updateSortButtonState(false)
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
@@ -104,6 +107,7 @@ class CobblemonBagScreen(
allItemsCategoryWidget = BagCategoryButton(leftPos + 214, topPos, this, -1) {
if (menu.currentlySelectedCategory != -1) {
menu.changeCategory(-1)
updateSortButtonState(false)
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
@@ -114,12 +118,27 @@ class CobblemonBagScreen(
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
leftCategoryPageButton.enabled = false
rightCategoryPageButton = BagCategoryPageButton(leftPos + 229, topPos + 32, this, false) {
if (rightCategoryPageButton.enabled) {
cycleCategoryPage(true)
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
cycleCategorySortButton = BagCycleSortButton(
leftPos + 200, topPos + 32, this
) {
updateSortButtonState(true)
}.also { addRenderableWidget(it) }
ascendingButton = BagSortAscendingButton(
leftPos + 180, topPos + 32, this
) {
if (ascendingButton.enabled) {
playSound(CobblemonSounds.ITEM_BAG_CLICK)
menu.ascending = !menu.ascending
menu.setupSlotsBasedOnContent()
}
}.also { addRenderableWidget(it) }
playSound(CobblemonSounds.ITEM_BAG_OPEN)
}
@@ -334,12 +353,38 @@ class CobblemonBagScreen(
BagCategoryButton(leftPos + 76 + i * 33, topPos, this, adjustedIndex) {
playSound(CobblemonSounds.ITEM_BAG_CLICK)
menu.changeCategory(adjustedIndex)
updateSortButtonState(false)
}.also { addRenderableWidget(it) }
)
} else break
}
leftCategoryPageButton.enabled = currentCategoryPage > 0
rightCategoryPageButton.enabled = currentCategoryPage < (orderedCategories.size - 1) / 4
updateSortButtonState(false)
}
/** Updates the state of [cycleCategorySortButton]. If cycle = true, will cycle to the next sort type. */
private fun updateSortButtonState(cycle: Boolean) {
val currentCategory = BagCategories.getOrderedCategoriesList().getOrNull(menu.currentlySelectedCategory)
if (menu.currentlySelectedCategory == -1) {
cycleCategorySortButton.enabled = false
ascendingButton.enabled = false
return
}
cycleCategorySortButton.enabled = currentCategory != null && currentCategory.getAllSortMethods().size > 1
ascendingButton.enabled = currentCategory != null && currentCategory.getAllSortMethods().size > 1
if (cycle && cycleCategorySortButton.enabled) {
val currentCategory = BagCategories.getOrderedCategoriesList().getOrNull(menu.currentlySelectedCategory) ?: return
playSound(CobblemonSounds.ITEM_BAG_CLICK)
if (menu.currentlySelectedSort == currentCategory.getAllSortMethods().size-1) {
menu.currentlySelectedSort = 0
} else { menu.currentlySelectedSort++ }
menu.setupSlotsBasedOnContent()
sendToServer(UpdateBagMenuDataPacket(menu.currentlySelectedCategory, menu.scroll, menu.currentlySelectedSort))
}
}
fun updateScrollValue(mouseY: Double) {
@@ -358,7 +403,7 @@ class CobblemonBagScreen(
if (slotId in CobblemonBagMenu.BAG_SLOTS && (lastCategory != menu.currentlySelectedCategory || lastScroll != menu.scroll)) {
lastCategory = menu.currentlySelectedCategory
lastScroll = menu.scroll
sendToServer(UpdateBagMenuDataPacket(menu.currentlySelectedCategory, menu.scroll)) // Synchronize this data
sendToServer(UpdateBagMenuDataPacket(menu.currentlySelectedCategory, menu.scroll, menu.currentlySelectedSort)) // Synchronize this data
}
super.slotClicked(slot, slotId, mouseButton, type)
}
@@ -25,6 +25,7 @@ object UpdateBagMenuDataHandler : ServerNetworkPacketHandler<UpdateBagMenuDataPa
val menu = player.containerMenu as? CobblemonBagMenu ?: return
menu.currentlySelectedCategory = packet.categoryId
menu.scroll = packet.scroll
menu.currentlySelectedSort = packet.sort
menu.setupSlotsBasedOnContent()
}
}
@@ -12,6 +12,7 @@ import com.cobblemon.mod.common.*
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.api.abilities.Abilities
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.bag.BagSortComparators
import com.cobblemon.mod.common.api.berry.Berries
import com.cobblemon.mod.common.api.cooking.Seasonings
import com.cobblemon.mod.common.api.data.DataProvider
@@ -123,6 +124,7 @@ object CobblemonDataProvider : DataProvider {
this.register(TechnicalMachines, reloadable = false)
this.register(BagCategories, reloadable = false)
SpawnBait.Effects.setupEffects()
BagSortComparators.setupComparators()
PlatformEvents.SERVER_PLAYER_LOGOUT.subscribe {
synchronizedPlayerIds.remove(it.player.uuid)
@@ -14,6 +14,8 @@ import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.advancement.CobblemonCriteria
import com.cobblemon.mod.common.advancement.criterion.PokemonInteractContext
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.bag.BagCategory
import com.cobblemon.mod.common.api.bag.BagSortComparators
import com.cobblemon.mod.common.api.item.PokemonSelectingItem
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
@@ -57,6 +59,8 @@ class CobblemonBagMenu: AbstractContainerMenu {
var scroll = 0
var maxScroll = 0
var categoryItemCounts = mutableListOf<Int>()
var currentlySelectedSort = 0
var ascending = true
constructor(containerId: Int, playerInventory: Inventory): super(CobblemonMenuType.COBBLEMON_BAG, containerId) {
this.playerInventory = playerInventory
@@ -78,6 +82,23 @@ class CobblemonBagMenu: AbstractContainerMenu {
calculateCategoriesItemCounts()
}
private fun sort(items: MutableList<ItemStack>, category: BagCategory?): List<ItemStack> {
if (category == null) return items
val sortMethod = category.getAllSortMethods().getOrNull(currentlySelectedSort)
?: category.defaultSort
?: BagSortComparators.DEFAULT_SORT
val comparator = BagSortComparators.getComparator(sortMethod)
?: BagSortComparators.getComparator(category.defaultSort ?: BagSortComparators.DEFAULT_SORT)
?: return items
return if (ascending) {
items.sortedWith(comparator)
} else {
items.sortedWith(comparator).asReversed()
}
}
private fun initializeSlots(playerInventory: Inventory) {
for ((index, _) in BAG_SLOTS.withIndex()) {
val i = index / 8
@@ -120,9 +141,17 @@ class CobblemonBagMenu: AbstractContainerMenu {
}
}
val items = bagContainer.items
val indexByStack = mutableMapOf<ItemStack, Int>()
items.forEachIndexed { i, stack -> indexByStack[stack] = i }
val orderedCategories = BagCategories.getOrderedCategoriesList()
val category = if (currentlySelectedCategory == -1) null else orderedCategories[currentlySelectedCategory]
val sortedItems = sort(items, category)
var slotId = BAG_SLOTS.first - 8 * scroll
bagContainer.items.forEachIndexed { index, itemStack ->
if (currentlySelectedCategory == -1 || BagCategories.getOrderedCategoriesList()[currentlySelectedCategory].itemIsValid(itemStack)) {
sortedItems.forEach { itemStack ->
val index = indexByStack[itemStack] ?: return@forEach
if (category == null || category.itemIsValid(itemStack)) {
val stackCount = ceil(itemStack.count.toFloat() / itemStack.maxStackSize).toInt()
for (i in 0..<stackCount) {
if (slotId in BAG_SLOTS) {
@@ -131,7 +160,7 @@ class CobblemonBagMenu: AbstractContainerMenu {
slot.slotOverflowValue = i
}
slotId += 1
if (slotId > BAG_SLOTS.last) return@forEachIndexed
if (slotId > BAG_SLOTS.last) return@forEach
}
}
}
@@ -158,6 +187,7 @@ class CobblemonBagMenu: AbstractContainerMenu {
fun changeCategory(categoryId: Int) {
currentlySelectedCategory = categoryId
currentlySelectedSort = 0
scroll = 0
setupSlotsBasedOnContent()
}
@@ -12,11 +12,11 @@ import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class UpdateBagMenuDataPacket(val categoryId: Int, val scroll: Int): NetworkPacket<UpdateBagMenuDataPacket> {
class UpdateBagMenuDataPacket(val categoryId: Int, val scroll: Int, val sort: Int): NetworkPacket<UpdateBagMenuDataPacket> {
companion object {
val ID = cobblemonResource("update_bag_menu_data")
fun decode(buffer: RegistryFriendlyByteBuf): UpdateBagMenuDataPacket {
return UpdateBagMenuDataPacket(buffer.readInt(), buffer.readInt())
return UpdateBagMenuDataPacket(buffer.readInt(), buffer.readInt(), buffer.readInt())
}
}
@@ -24,5 +24,6 @@ class UpdateBagMenuDataPacket(val categoryId: Int, val scroll: Int): NetworkPack
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeInt(categoryId)
buffer.writeInt(scroll)
buffer.writeInt(sort)
}
}
@@ -1208,6 +1208,11 @@
"cobblemon.bag_category.tms": "Technical Machines",
"cobblemon.bag_category.currency": "Currency",
"cobblemon.bag_categories.all_items": "Bag",
"cobblemon.bag.sort.alphabetical": "Alphabetical",
"cobblemon.bag.sort.input_order": "Input Order",
"cobblemon.bag.sort.creative_menu": "Creative Order",
"cobblemon.bag.sort.ascending": "Ascending",
"cobblemon.bag.sort.descending": "Descending",
"cobblemon.ui.pokenav.title": "PokéNav",
"cobblemon.ui.pokenav.narrator.backbutton": "PokéNav button pressed",
@@ -3,5 +3,9 @@
"icon": "cobblemon:textures/item/held_items/exp_share.png",
"whiteListTag": "cobblemon:bag/whitelist_held_evo",
"blackListTag": "cobblemon:bag/blacklist_held_evo",
"maxCount": 128
"maxCount": 128,
"sortMethods": [
"cobblemon:input_order",
"cobblemon:creative_menu"
]
}
@@ -3,5 +3,8 @@
"icon": "cobblemon:textures/item/blank_disc.png",
"whiteListTag": "cobblemon:bag/whitelist_tms",
"blackListTag": "cobblemon:bag/blacklist_tms",
"maxCount": 64
"maxCount": 64,
"sortMethods": [
"cobblemon:input_order"
]
}