storagechests (actually all fixtures) now has their own inventory

This commit is contained in:
minjaesong
2021-03-16 15:01:17 +09:00
parent 76f5d0a924
commit 0fa889bc55
10 changed files with 331 additions and 263 deletions

View File

@@ -738,7 +738,7 @@ public class AppLoader implements ApplicationListener {
textureWhiteCircle.dispose();
logo.getTexture().dispose();
disposableSingletonsPool.forEach(Disposable::dispose);
disposableSingletonsPool.forEach((it) -> {try { it.dispose(); } catch (GdxRuntimeException e) {}});
ModMgr.INSTANCE.disposeMods();

View File

@@ -43,7 +43,7 @@ open class ActorHumanoid(
/** Must be set by PlayerFactory */
override var inventory: ActorInventory = ActorInventory(this, 2000, ActorInventory.CAPACITY_MODE_WEIGHT) // default constructor
override var inventory: ActorInventory = ActorInventory(this, 2000, FixtureInventory.CAPACITY_MODE_WEIGHT) // default constructor
/** Must be set by PlayerFactory */

View File

@@ -19,13 +19,8 @@ import java.util.concurrent.locks.ReentrantLock
* Created by minjaesong on 2016-03-15.
*/
class ActorInventory(@Transient val actor: Pocketed, var maxCapacity: Int, var capacityMode: Int) {
companion object {
val CAPACITY_MODE_NO_ENCUMBER = 0
val CAPACITY_MODE_COUNT = 1
val CAPACITY_MODE_WEIGHT = 2
}
class ActorInventory(@Transient val actor: Pocketed, maxCapacity: Int, capacityMode: Int):
FixtureInventory(maxCapacity, capacityMode) {
// FIXME unless absolutely necessary, don't store full item object; only store its dynamicID
@@ -34,99 +29,23 @@ class ActorInventory(@Transient val actor: Pocketed, var maxCapacity: Int, var c
*/
val itemEquipped = Array<ItemID?>(GameItem.EquipPosition.INDEX_MAX) { null }
/**
* Sorted by referenceID.
*/
val itemList = ArrayList<InventoryPair>()
val quickSlot = Array<ItemID?>(UIQuickslotBar.SLOT_COUNT) { null } // 0: Slot 1, 9: Slot 10
var wallet = BigInteger("0") // unified currency for whole civs; Dwarf Fortress approach seems too complicated
init {
}
fun add(itemID: ItemID, count: Int = 1) {
if (ItemCodex[itemID] == null)
throw NullPointerException("Item not found: $itemID")
else
add(ItemCodex[itemID]!!, count)
}
fun add(item: GameItem, count: Int = 1) {
println("[ActorInventory] add-by-elem $item, $count")
// other invalid values
if (count == 0)
throw IllegalArgumentException("Item count is zero.")
if (count < 0)
throw IllegalArgumentException("Item count is negative number. If you intended removing items, use remove()\n" +
"These commands are NOT INTERCHANGEABLE; they handle things differently according to the context.")
if (item.originalID == "actor:${Terrarum.PLAYER_REF_ID}" || item.originalID == ("actor:${0x51621D}")) // do not delete this magic
throw IllegalArgumentException("Attempted to put human player into the inventory.")
if (((Terrarum.ingame as? TerrarumIngame)?.gameFullyLoaded ?: false) &&
(item.originalID == "actor:${(Terrarum.ingame as? TerrarumIngame)?.actorNowPlaying?.referenceID}"))
throw IllegalArgumentException("Attempted to put active player into the inventory.")
if ((!item.stackable || item.dynamicID.startsWith("dyn:")) && count > 1)
throw IllegalArgumentException("Attempting to adding stack of item but the item is not stackable; item: $item, count: $count")
// If we already have the item, increment the amount
// If not, add item with specified amount
val existingItem = invSearchByDynamicID(item.dynamicID)
// if the item already exists
if (existingItem != null) {
// increment count
existingItem.amount += count
}
// new item
else {
itemList.add(InventoryPair(item.dynamicID, count))
}
insertionSortLastElem(itemList)
}
fun remove(itemID: ItemID, count: Int) = remove(ItemCodex[itemID]!!, count)
/** Will check existence of the item using its Dynamic ID; careful with command order!
* e.g. re-assign after this operation */
fun remove(item: GameItem, count: Int = 1) {
super.remove(item, count) { existingItem ->
// unequip, if applicable
actor.unequipItem(existingItem.item)
// depleted item; remove entry from inventory
itemList.remove(existingItem)
println("[ActorInventory] remove $item, $count")
if (count == 0)
throw IllegalArgumentException("Item count is zero.")
if (count < 0)
throw IllegalArgumentException("Item count is negative number. If you intended adding items, use add()" +
"These commands are NOT INTERCHANGEABLE; they handle things differently according to the context.")
val existingItem = invSearchByDynamicID(item.dynamicID)
if (existingItem != null) { // if the item already exists
val newCount = existingItem.amount - count
if (newCount < 0) {
throw Error("Tried to remove $count of $item, but the inventory only contains ${existingItem.amount} of them.")
// also unequip on the quickslot
actor.actorValue.getAsInt(AVKey.__PLAYER_QUICKSLOTSEL)?.let {
setQuickBar(it, null)
}
else if (newCount > 0) {
// decrement count
existingItem.amount = newCount
}
else {
// unequip, if applicable
actor.unequipItem(existingItem.item)
// depleted item; remove entry from inventory
itemList.remove(existingItem)
// also unequip on the quickslot
actor.actorValue.getAsInt(AVKey.__PLAYER_QUICKSLOTSEL)?.let {
actor.inventory.setQuickBar(it, null)
}
}
}
else {
throw Error("Tried to remove $item, but the inventory does not have it.")
}
}
@@ -136,48 +55,6 @@ class ActorInventory(@Transient val actor: Pocketed, var maxCapacity: Int, var c
fun getQuickslot(slot: Int): InventoryPair? = invSearchByDynamicID(quickSlot[slot])
/**
* HashMap<GameItem, Amounts>
*/
inline fun forEach(consumer: (InventoryPair) -> Unit) = itemList.forEach(consumer)
/**
* Get capacity of inventory
* @return
*/
val capacity: Double
get() = if (capacityMode == CAPACITY_MODE_NO_ENCUMBER)
maxCapacity.toDouble()
else if (capacityMode == CAPACITY_MODE_WEIGHT)
getTotalWeight()
else
getTotalCount().toDouble()
fun getTotalWeight(): Double = itemList.map { ItemCodex[it.item]!!.mass * it.amount }.sum()
/**
* Real amount
*/
fun getTotalCount(): Int = itemList.map { it.amount }.sum()
/**
* Unique amount, multiple items are calculated as one
*/
fun getTotalUniqueCount(): Int = itemList.size
/**
* Check whether the itemList contains too many items
* @return
*/
val isEncumbered: Boolean
get() = if (capacityMode == CAPACITY_MODE_NO_ENCUMBER)
false
else if (capacityMode == CAPACITY_MODE_WEIGHT)
maxCapacity < capacity
else
false
fun consumeItem(item: GameItem) {
val actor = this.actor as Actor
@@ -231,74 +108,5 @@ class ActorInventory(@Transient val actor: Pocketed, var maxCapacity: Int, var c
//println("[ActorInventory] consumed; ${item.durability}")
}
}
fun contains(item: GameItem) = contains(item.dynamicID)
fun contains(id: ItemID) =
if (itemList.size == 0)
false
else
itemList.binarySearch(id, DYNAMIC_ID) >= 0
fun invSearchByDynamicID(id: ItemID?): InventoryPair? {
if (itemList.size == 0 || id == null)
return null
val index = itemList.binarySearch(id, DYNAMIC_ID)
if (index < 0)
return null
else
return itemList[index]
}
private fun invSearchByStaticID(id: ItemID?): InventoryPair? {
if (itemList.size == 0 || id == null)
return null
val index = itemList.binarySearch(id, STATIC_ID)
if (index < 0)
return null
else
return itemList[index]
}
private fun insertionSortLastElem(arr: ArrayList<InventoryPair>) {
ReentrantLock().lock {
var j = arr.lastIndex - 1
val x = arr.last()
while (j >= 0 && arr[j].item > x.item) {
arr[j + 1] = arr[j]
j -= 1
}
arr[j + 1] = x
}
}
@Transient private val STATIC_ID = 41324534
@Transient private val DYNAMIC_ID = 181643953
private fun ArrayList<InventoryPair>.binarySearch(ID: ItemID, searchMode: Int): Int {
// code from collections/Collections.kt
var low = 0
var high = this.size - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = if (searchMode == STATIC_ID)
ItemCodex[this[mid].item]!!.originalID
else
ItemCodex[this[mid].item]!!.dynamicID
if (ID > midVal)
low = mid + 1
else if (ID < midVal)
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
}
}
data class InventoryPair(val item: ItemID, var amount: Int)

View File

@@ -1,5 +1,6 @@
package net.torvald.terrarum.modulebasegame.gameactors
import net.torvald.terrarum.AppLoader
import net.torvald.terrarum.IngameInstance
import net.torvald.terrarum.Point2i
import net.torvald.terrarum.Terrarum
@@ -18,8 +19,8 @@ open class FixtureBase(
blockBox0: BlockBox,
val blockBoxProps: BlockBoxProps = BlockBoxProps(0),
renderOrder: RenderOrder = RenderOrder.MIDDLE,
val mainUI: UICanvas? = null
val mainUI: UICanvas? = null,
val inventory: FixtureInventory? = null
// disabling physics (not allowing the fixture to move) WILL make things easier in many ways
) : ActorWithBody(renderOrder, PhysProperties.IMMOBILE), CuedByTerrainChange {
@@ -36,6 +37,11 @@ open class FixtureBase(
*/
private var worldBlockPos: Point2i? = null
init {
if (mainUI != null)
AppLoader.disposableSingletonsPool.add(mainUI)
}
/**
* Adds this instance of the fixture to the world
*
@@ -121,6 +127,7 @@ open class FixtureBase(
}
worldBlockPos = null
mainUI?.dispose()
this.isVisible = false
}

View File

@@ -0,0 +1,212 @@
package net.torvald.terrarum.modulebasegame.gameactors
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameitem.GameItem
import net.torvald.terrarum.gameitem.ItemID
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.lock
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import java.math.BigInteger
import java.util.concurrent.locks.ReentrantLock
/**
* Created by minjaesong on 2021-03-16.
*/
open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
companion object {
val CAPACITY_MODE_NO_ENCUMBER = 0
val CAPACITY_MODE_COUNT = 1
val CAPACITY_MODE_WEIGHT = 2
}
/**
* Sorted by referenceID.
*/
val itemList = ArrayList<InventoryPair>()
var wallet = BigInteger("0") // unified currency for whole civs; Dwarf Fortress approach seems too complicated
open fun add(itemID: ItemID, count: Int = 1) {
if (ItemCodex[itemID] == null)
throw NullPointerException("Item not found: $itemID")
else
add(ItemCodex[itemID]!!, count)
}
open fun add(item: GameItem, count: Int = 1) {
println("[ActorInventory] add-by-elem $item, $count")
// other invalid values
if (count == 0)
throw IllegalArgumentException("Item count is zero.")
if (count < 0)
throw IllegalArgumentException("Item count is negative number. If you intended removing items, use remove()\n" +
"These commands are NOT INTERCHANGEABLE; they handle things differently according to the context.")
if (item.originalID == "actor:${Terrarum.PLAYER_REF_ID}" || item.originalID == ("actor:${0x51621D}")) // do not delete this magic
throw IllegalArgumentException("Attempted to put human player into the inventory.")
if (((Terrarum.ingame as? TerrarumIngame)?.gameFullyLoaded ?: false) &&
(item.originalID == "actor:${(Terrarum.ingame as? TerrarumIngame)?.actorNowPlaying?.referenceID}"))
throw IllegalArgumentException("Attempted to put active player into the inventory.")
if ((!item.stackable || item.dynamicID.startsWith("dyn:")) && count > 1)
throw IllegalArgumentException("Attempting to adding stack of item but the item is not stackable; item: $item, count: $count")
// If we already have the item, increment the amount
// If not, add item with specified amount
val existingItem = invSearchByDynamicID(item.dynamicID)
// if the item already exists
if (existingItem != null) {
// increment count
existingItem.amount += count
}
// new item
else {
itemList.add(InventoryPair(item.dynamicID, count))
}
insertionSortLastElem(itemList)
}
open fun remove(itemID: ItemID, count: Int, unequipFun: (InventoryPair) -> Unit) =
remove(ItemCodex[itemID]!!, count, unequipFun)
/** Will check existence of the item using its Dynamic ID; careful with command order!
* e.g. re-assign after this operation */
open fun remove(item: GameItem, count: Int = 1, unequipFun: (InventoryPair) -> Unit) {
println("[ActorInventory] remove $item, $count")
if (count == 0)
throw IllegalArgumentException("Item count is zero.")
if (count < 0)
throw IllegalArgumentException("Item count is negative number. If you intended adding items, use add()" +
"These commands are NOT INTERCHANGEABLE; they handle things differently according to the context.")
val existingItem = invSearchByDynamicID(item.dynamicID)
if (existingItem != null) { // if the item already exists
val newCount = existingItem.amount - count
if (newCount < 0) {
throw Error("Tried to remove $count of $item, but the inventory only contains ${existingItem.amount} of them.")
}
else if (newCount > 0) {
// decrement count
existingItem.amount = newCount
}
else {
unequipFun(existingItem)
}
}
else {
throw Error("Tried to remove $item, but the inventory does not have it.")
}
}
/**
* HashMap<GameItem, Amounts>
*/
inline fun forEach(consumer: (InventoryPair) -> Unit) = itemList.forEach(consumer)
/**
* Get capacity of inventory
* @return
*/
val capacity: Double
get() = if (capacityMode == CAPACITY_MODE_NO_ENCUMBER)
maxCapacity.toDouble()
else if (capacityMode == CAPACITY_MODE_WEIGHT)
getTotalWeight()
else
getTotalCount().toDouble()
fun getTotalWeight(): Double = itemList.map { ItemCodex[it.item]!!.mass * it.amount }.sum()
/**
* Real amount
*/
fun getTotalCount(): Int = itemList.map { it.amount }.sum()
/**
* Unique amount, multiple items are calculated as one
*/
fun getTotalUniqueCount(): Int = itemList.size
/**
* Check whether the itemList contains too many items
* @return
*/
val isEncumbered: Boolean
get() = if (capacityMode == CAPACITY_MODE_NO_ENCUMBER)
false
else if (capacityMode == CAPACITY_MODE_WEIGHT)
maxCapacity < capacity
else
false
fun contains(item: GameItem) = contains(item.dynamicID)
fun contains(id: ItemID) =
if (itemList.size == 0)
false
else
itemList.binarySearch(id, DYNAMIC_ID) >= 0
fun invSearchByDynamicID(id: ItemID?): InventoryPair? {
if (itemList.size == 0 || id == null)
return null
val index = itemList.binarySearch(id, DYNAMIC_ID)
if (index < 0)
return null
else
return itemList[index]
}
protected fun invSearchByStaticID(id: ItemID?): InventoryPair? {
if (itemList.size == 0 || id == null)
return null
val index = itemList.binarySearch(id, STATIC_ID)
if (index < 0)
return null
else
return itemList[index]
}
protected fun insertionSortLastElem(arr: ArrayList<InventoryPair>) {
ReentrantLock().lock {
var j = arr.lastIndex - 1
val x = arr.last()
while (j >= 0 && arr[j].item > x.item) {
arr[j + 1] = arr[j]
j -= 1
}
arr[j + 1] = x
}
}
@Transient private val STATIC_ID = 41324534
@Transient private val DYNAMIC_ID = 181643953
protected fun ArrayList<InventoryPair>.binarySearch(ID: ItemID, searchMode: Int): Int {
// code from collections/Collections.kt
var low = 0
var high = this.size - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = if (searchMode == STATIC_ID)
ItemCodex[this[mid].item]!!.originalID
else
ItemCodex[this[mid].item]!!.dynamicID
if (ID > midVal)
low = mid + 1
else if (ID < midVal)
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
}
}
data class InventoryPair(val item: ItemID, var amount: Int)

View File

@@ -8,6 +8,7 @@ import net.torvald.terrarum.*
import net.torvald.terrarum.AppLoader.printdbg
import net.torvald.terrarum.gameactors.AVKey
import net.torvald.terrarum.gameitem.GameItem
import net.torvald.terrarum.modulebasegame.gameactors.FixtureInventory.Companion.CAPACITY_MODE_COUNT
import net.torvald.terrarum.modulebasegame.ui.HasInventory
import net.torvald.terrarum.modulebasegame.ui.InventoryNegotiator
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.CELLS_HOR
@@ -20,7 +21,9 @@ import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.gradHeig
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.gradStartCol
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.internalHeight
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.internalWidth
import net.torvald.terrarum.modulebasegame.ui.UIItemInventoryEquippedView
import net.torvald.terrarum.modulebasegame.ui.UIItemInventoryItemGrid
import net.torvald.terrarum.modulebasegame.ui.UIItemInventoryItemGrid.Companion.listGap
import net.torvald.terrarum.ui.UICanvas
import net.torvald.terrarumsansbitmap.gdx.TextureRegionPack
@@ -29,10 +32,13 @@ import net.torvald.terrarumsansbitmap.gdx.TextureRegionPack
*/
internal class FixtureStorageChest : FixtureBase(
BlockBox(BlockBox.ALLOW_MOVE_DOWN, 1, 1),
mainUI = UIStorageChest
inventory = FixtureInventory(40, CAPACITY_MODE_COUNT),
mainUI = UIStorageChest()
) {
init {
(mainUI as UIStorageChest).chest = this.inventory!!
setHitboxDimension(16, 16, 0, 0)
makeNewSprite(TextureRegionPack(CommonResourcePool.getAsTextureRegion("itemplaceholder_16").texture, 16, 16))
@@ -47,7 +53,9 @@ internal class FixtureStorageChest : FixtureBase(
}
internal object UIStorageChest : UICanvas(), HasInventory {
internal class UIStorageChest : UICanvas(), HasInventory {
lateinit var chest: FixtureInventory
override var width = AppLoader.screenW
override var height = AppLoader.screenH
@@ -75,45 +83,69 @@ internal object UIStorageChest : UICanvas(), HasInventory {
TODO("Not yet implemented")
}
private var catBar: UIItemInventoryCatBar
private var itemList: UIItemInventoryItemGrid
private lateinit var catBar: UIItemInventoryCatBar
private lateinit var itemListChest: UIItemInventoryItemGrid
private lateinit var itemListPlayer: UIItemInventoryItemGrid
init {
catBar = UIItemInventoryCatBar(
this,
(AppLoader.screenW - catBarWidth) / 2,
42 + (AppLoader.screenH - internalHeight) / 2,
internalWidth,
catBarWidth,
false
)
catBar.selectionChangeListener = { old, new -> itemListUpdate() }
itemList = UIItemInventoryItemGrid(
this,
catBar,
Terrarum.ingame!!.actorNowPlaying!!.inventory, // just for a placeholder...
INVENTORY_CELLS_OFFSET_X,
INVENTORY_CELLS_OFFSET_Y,
CELLS_HOR / 2, CELLS_VRT,
drawScrollOnRightside = false,
drawWallet = false,
keyDownFun = { _,_ -> Unit },
touchDownFun = { _,_,_,_,_ -> itemListUpdate() }
)
private var halfSlotOffset = (UIItemInventoryElemSimple.height + listGap) / 2
handler.allowESCtoClose = true
addUIitem(catBar)
addUIitem(itemList)
}
private var initialised = false
private fun itemListUpdate() {
itemList.rebuild(catBar.catIconsMeaning[catBar.selectedIcon])
itemListChest.rebuild(catBar.catIconsMeaning[catBar.selectedIcon])
itemListPlayer.rebuild(catBar.catIconsMeaning[catBar.selectedIcon])
}
override fun updateUI(delta: Float) {
if (!initialised) {
initialised = true
catBar = UIItemInventoryCatBar(
this,
(AppLoader.screenW - catBarWidth) / 2,
42 + (AppLoader.screenH - internalHeight) / 2,
internalWidth,
catBarWidth,
false
)
catBar.selectionChangeListener = { old, new -> itemListUpdate() }
itemListChest = UIItemInventoryItemGrid(
this,
catBar,
chest,
INVENTORY_CELLS_OFFSET_X - halfSlotOffset,
INVENTORY_CELLS_OFFSET_Y,
6, CELLS_VRT,
drawScrollOnRightside = false,
drawWallet = false,
keyDownFun = { _, _ -> Unit },
touchDownFun = { _, _, _, _, _ -> itemListUpdate() }
)
itemListPlayer = UIItemInventoryItemGrid(
this,
catBar,
Terrarum.ingame!!.actorNowPlaying!!.inventory, // literally a player's inventory
INVENTORY_CELLS_OFFSET_X - halfSlotOffset + (listGap + UIItemInventoryElem.height) * 7,
INVENTORY_CELLS_OFFSET_Y,
6, CELLS_VRT,
drawScrollOnRightside = true,
drawWallet = false,
keyDownFun = { _, _ -> Unit },
touchDownFun = { _, _, _, _, _ -> itemListUpdate() }
)
handler.allowESCtoClose = true
addUIitem(catBar)
addUIitem(itemListChest)
addUIitem(itemListPlayer)
}
catBar.update(delta)
itemList.update(delta)
itemListChest.update(delta)
itemListPlayer.update(delta)
}
override fun renderUI(batch: SpriteBatch, camera: Camera) {
@@ -142,7 +174,8 @@ internal object UIStorageChest : UICanvas(), HasInventory {
batch.color = Color.WHITE
catBar.render(batch, camera)
itemList.render(batch, camera)
itemListChest.render(batch, camera)
itemListPlayer.render(batch, camera)
}
override fun doOpening(delta: Float) {

View File

@@ -60,7 +60,7 @@ object PlayerBuilderSigrid {
p.setHitboxDimension(15, p.actorValue.getAsInt(AVKey.BASEHEIGHT)!!, 11, 0)
p.inventory = ActorInventory(p, 0, ActorInventory.CAPACITY_MODE_NO_ENCUMBER)
p.inventory = ActorInventory(p, 0, FixtureInventory.CAPACITY_MODE_NO_ENCUMBER)
p.faction.add(FactionFactory.create("basegame", "factions/FactionSigrid.json"))

View File

@@ -7,6 +7,7 @@ import net.torvald.terrarum.*
import net.torvald.terrarum.gameactors.ActorWithBody
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.gameactors.ActorInventory
import net.torvald.terrarum.modulebasegame.gameactors.FixtureInventory
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.CELLS_HOR
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.CELLS_VRT
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull.Companion.INVENTORY_CELLS_OFFSET_X
@@ -53,7 +54,8 @@ internal class UIInventoryCells(
full.actor.inventory,
full.actor as ActorWithBody,
internalWidth - UIItemInventoryEquippedView.WIDTH + (AppLoader.screenW - internalWidth) / 2,
INVENTORY_CELLS_OFFSET_Y
INVENTORY_CELLS_OFFSET_Y,
{ rebuildList() }
)
init {
@@ -124,7 +126,7 @@ internal class UIInventoryCells(
batch.color = encumbCol
batch.fillRect(
encumbBarXPos, encumbBarYPos,
if (full.actor.inventory.capacityMode == ActorInventory.CAPACITY_MODE_NO_ENCUMBER)
if (full.actor.inventory.capacityMode == FixtureInventory.CAPACITY_MODE_NO_ENCUMBER)
1f
else // make sure 1px is always be seen
minOf(weightBarWidth, maxOf(1f, weightBarWidth * encumbrancePerc)),

View File

@@ -15,17 +15,19 @@ import net.torvald.terrarum.modulebasegame.ui.UIItemInventoryItemGrid.Companion.
import net.torvald.terrarum.modulebasegame.ui.UIItemInventoryItemGrid.Companion.createInvCellGenericTouchDownFun
import net.torvald.terrarum.ui.Toolkit
import net.torvald.terrarum.ui.Toolkit.DEFAULT_BOX_BORDER_COL
import net.torvald.terrarum.ui.UICanvas
import net.torvald.terrarum.ui.UIItem
/**
* Created by minjaesong on 2017-10-28.
*/
class UIItemInventoryEquippedView(
parentUI: UIInventoryFull,
parentUI: UICanvas,
val inventory: ActorInventory,
val theActor: ActorWithBody,
initialX: Int,
initialY: Int
initialY: Int,
inventoryListRebuildFun: () -> Unit
) : UIItem(parentUI, initialX, initialY) {
@@ -66,7 +68,7 @@ class UIItemInventoryEquippedView(
backBlendMode = BlendMode.NORMAL,
drawBackOnNull = true,
keyDownFun = createInvCellGenericKeyDownFun(),
touchDownFun = createInvCellGenericTouchDownFun { parentUI.rebuildList() } // to "unselect" the equipped item and main item grid would "untick" accordingly
touchDownFun = createInvCellGenericTouchDownFun(inventoryListRebuildFun) // to "unselect" the equipped item and main item grid would "untick" accordingly
)
}

View File

@@ -12,6 +12,7 @@ import net.torvald.terrarum.gameworld.fmod
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.gameactors.ActorInventory
import net.torvald.terrarum.modulebasegame.gameactors.FixtureInventory
import net.torvald.terrarum.modulebasegame.gameactors.InventoryPair
import net.torvald.terrarum.modulebasegame.ui.ItemSlotImageFactory.CELLCOLOUR_BLACK
import net.torvald.terrarum.modulebasegame.ui.ItemSlotImageFactory.CELLCOLOUR_BLACK_ACTIVE
@@ -38,7 +39,7 @@ import kotlin.math.floor
class UIItemInventoryItemGrid(
parentUI: UICanvas,
val catBar: UIItemInventoryCatBar,
val inventory: ActorInventory, // when you're going to display List of Craftables, you could implement a Delegator...? Or just build a virtual inventory
val inventory: FixtureInventory, // when you're going to display List of Craftables, you could implement a Delegator...? Or just build a virtual inventory
initialX: Int,
initialY: Int,
val horizontalCells: Int,
@@ -192,7 +193,8 @@ class UIItemInventoryItemGrid(
}
// automatically determine how much columns are needed. Minimum Width = 5 grids
private val itemListColumnCount = floor(horizontalCells / 5f).toInt().coerceAtLeast(1)
private val largeListWidth = (horizontalCells * UIItemInventoryElemSimple.height + (horizontalCells - 2) * listGap) / itemListColumnCount
private val actualItemCellWidth = (listGap + UIItemInventoryElemSimple.height) * horizontalCells - listGap // in pixels
private val largeListWidth = ((listGap + actualItemCellWidth) / itemListColumnCount) - (itemListColumnCount - 1).coerceAtLeast(1) * listGap
private val itemList = Array<UIItemInventoryCellBase>(verticalCells * itemListColumnCount) {
UIItemInventoryElem(
parentUI = inventoryUI,
@@ -428,24 +430,26 @@ class UIItemInventoryItemGrid(
items[k].itemImage = ItemCodex.getItemImage(sortListItem.item)
// set quickslot number
for (qs in 1..UIQuickslotBar.SLOT_COUNT) {
if (sortListItem.item == inventory.getQuickslot(qs - 1)?.item) {
items[k].quickslot = qs % 10 // 10 -> 0, 1..9 -> 1..9
break
}
else
items[k].quickslot = null
}
// set equippedslot number
for (eq in inventory.itemEquipped.indices) {
if (eq < inventory.itemEquipped.size) {
if (inventory.itemEquipped[eq] == items[k].item?.dynamicID) {
items[k].equippedSlot = eq
if (inventory is ActorInventory) {
for (qs in 1..UIQuickslotBar.SLOT_COUNT) {
if (sortListItem.item == inventory.getQuickslot(qs - 1)?.item) {
items[k].quickslot = qs % 10 // 10 -> 0, 1..9 -> 1..9
break
}
else
items[k].equippedSlot = null
items[k].quickslot = null
}
// set equippedslot number
for (eq in inventory.itemEquipped.indices) {
if (eq < inventory.itemEquipped.size) {
if (inventory.itemEquipped[eq] == items[k].item?.dynamicID) {
items[k].equippedSlot = eq
break
}
else
items[k].equippedSlot = null
}
}
}
}