Loot, Inventory and Crafting

LootItemDefinition

LootItemDefinition (ScriptableObject) is the authoritative item descriptor. Fields:

FieldTypeDefaultNotes
itemIdstringβ€”Matches items.id in the DB.
displayNamestringβ€”
databaseItemTypeLootDatabaseItemTypeβ€”Determines inventory filter category.
rarityItemRarityCommonCommon (0), Uncommon (1), Rare (2), Epic (3), Legendary (4), Relic (5). All tiers are supported in the live database. Enum values are stable integers serialized by Unity; never reorder.
sellValueintβ€”
craftedboolβ€”DB flag for craft-produced items.
stackablebooltrueWhether multiple copies share one inventory slot.
maxStackSizeint99Max quantity per slot. Ignored when stackable is false; must be at least 1.
inventoryIconSpriteβ€”Required.
worldVisualPrefabGameObjectnullOptional. Leave empty for inventory-only items (tickets, materials, consumables). When null, the enemy's assigned network-ready pickup prefab is used as the world representation. When assigned, must be a prefab asset from the Project window.

LootDatabaseItemType.Consumable is a valid type value. LootPersistenceService maps it to the database string "consumable". The existing inventory filter tabs (All Β· Gear Β· Materials) do not filter by this type.

Equipment fields

Equipment items carry additional fields for paper-doll display and 3D attachment:

FieldTypeNotes
equipmentSlotLootEquipmentSlotRequired for equipment. Determines the paper-doll slot and authoritative database slot.
equippedVisualPrefabGameObjectClient-side model attached to the equipped player and paper-doll preview. Falls back to worldVisualPrefab when null.
attachmentProfileEquipmentAttachmentProfileReusable bone and transform defaults for this equipment family (e.g. Two-Handed Sword). Required for all equipment slots except Ring and Trinket.
overrideAttachmentProfileboolUse this item's own bone/position/rotation/scale instead of the profile defaults.
twoHandedboolReserves both hands. Shown in Loot Forge when the MainHand slot is selected.
attachmentBoneNamestringOptional exact skeleton transform name. Leave empty to use slot-aware hand/head/body aliases.
equippedLocalPositionVector3Item-level position override (used when no profile, or overrideAttachmentProfile).
equippedLocalEulerAnglesVector3Item-level rotation override.
equippedLocalScaleVector3Item-level scale override.
classAttachmentOverridesEquipmentAttachmentClassOverride[]Per-class bone/position/rotation/scale overrides applied on top of profile defaults.

Effective values (used by the runtime) are resolved via EffectiveAttachmentBoneNameForClass(classIndex), EffectiveEquippedLocalPositionForClass, EffectiveEquippedLocalEulerAnglesForClass, and EffectiveEquippedLocalScaleForClass β€” class overrides take precedence over profile values, which take precedence over item-level fields.

Items are authored in Loot Forge (BCE β–Ά Loot Forge). LootPersistenceService syncs stackable and maxStackSize to the items database table on server deployment. See Editor Tooling for Loot Forge documentation.

LootEquipmentSlot

LootEquipmentSlot enum values (defined in LootItemDefinition.cs):

ValueNotes
NoneNot equippable.
Head
Chest
Legs
Feet
Hands
MainHandWhen a main-hand item is equipped, the player's built-in starter weapon is hidden.
OffHand
Ring
Trinket
UnspecifiedDefault; serialized last so existing enum indices are stable.

Equipment pipeline (server-authoritative)

Equipment state lives in PlayerIdentity.Equipment.cs as a partial class extension of PlayerIdentity.

Server flow:

  1. On OnStartServer, PlayerIdentity fetches GET /api/game/equipment/:characterId using CROSSWORLDS_GAME_SERVICE_TOKEN.
  2. The response populates SyncList<EquippedLootState> equippedLoot with one entry per equipped slot.
  3. Stat bonuses from the server response are applied via CharacterStats.SetEquipmentStatBonuses(str, agi, int, vit).
  4. Clients can call CmdRefreshEquipment() to trigger a server-side reload.

Client flow:

  • InventoryBagUI handles equip/unequip via POST /api/inventory/equip.
  • equippedLoot is a Mirror SyncList; changes propagate to all clients automatically.
  • On each change, RebuildEquipmentVisuals() destroys and recreates all attached equipment models on the local character.
  • When a main-hand item is equipped, the player's built-in starter weapon is hidden (SetBuiltInMainHandVisible(false)).

Attachment resolution (client): ResolveEquipmentAnchor finds the skeleton bone named in attachmentBoneName first. If no match, it falls back to slot-aware aliases (e.g. MainHand β†’ RightHand, Hand_R, mixamorig:RightHand, etc.).

Skinned armor: Prefabs assigned to Head, Chest, Hands, Legs, or Feet slots that contain a SkinnedMeshRenderer are treated as skinned armor. At runtime, the visual is parented to the player's root transform (not a bone anchor) and RemapSkinnedArmorBones rebinds each renderer's bone array to matching transforms on the player skeleton by name (case-insensitive). A warning is logged if a renderer has no bones that match the player skeleton; those renderers are left with their original (likely broken) bone references.

EquipmentAttachmentProfile

EquipmentAttachmentProfile (ScriptableObject) stores reusable attachment defaults for a family of equipment (e.g. all two-handed swords). Fields mirror the item-level attachment fields plus twoHanded. Multiple items can share one profile; per-item or per-class overrides layer on top.

Default profiles for standard slots are managed by LootForgeAttachmentDefaults (editor-only). See Editor Tooling for Loot Forge documentation.

World item pickup flow

WorldItem (Mirror NetworkBehaviour) is spawned by the server when an enemy drops loot. The pickup handshake is server-authoritative with client-confirmed persistence:

  1. Client presses interact β†’ CmdPickup on server.
  2. Server validates proximity and _pickedUp state. On rejection, TargetResetPickup is sent to the client to clear the pending flag.
  3. On acceptance: server sets _pickedUp = true and _pendingPickerConnectionId, then calls TargetOnPickedUp on the picker's client.
  4. Gold items (itemId starting with "gold:") are destroyed immediately after DestroyAfterRewardDispatch.
  5. Non-gold items start a 12-second server timeout (ResetTimedOutPickup). If the client does not confirm within 12 seconds, _pickedUp is reset and the item becomes available again.
  6. Client receives TargetOnPickedUp β†’ calls InventoryManager.PersistWorldPickup(itemId, qty, callback) β†’ sends POST /api/inventory/add-item. The response includes stored (quantity actually added) and rejected (quantity that did not fit).
  7. Client calls CmdCompleteItemPickup(stored) back on the server.
  8. Server validates that the caller matches _pendingPickerConnectionId, then:
  9. Reports to the quest system via QuestLocalRuntime.ServerReport for the confirmed stored quantity.
  10. Decrements quantity by stored.
  11. Destroys the WorldItem if quantity reaches zero; otherwise resets pickup state so another player can pick up the remainder.

Inventory manager

InventoryManager runs on the client (#if UNITY_EDITOR || !UNITY_SERVER).

PersistWorldPickup(itemId, qty, callback) β€” called when a world item is picked up (step 4 above). POSTs { characterId, itemId, quantity } to /api/inventory/add-item with a 10-second timeout. On success, reloads inventory from the server and refreshes InventoryBagUI. Invokes callback(stored) on completion; passes 0 on auth failure or API error.

  • Gold (itemId starting with "gold:") does not call this method β€” the server handles gold directly.
  • Stackable items fill existing slots of the same item (unequipped, below maxStackSize) before creating new slots (enforced server-side).
  • Non-stackable items always create a new slot (enforced server-side).

Inventory UI (client)

InventoryBagUI is a DontDestroyOnLoad singleton that loads its visuals from the InventoryBagView prefab at Resources/Inventory/InventoryWindow. Run BCE β–Ά Setup β–Ά Rebuild Inventory UI to regenerate the prefab from the approved art assets if it is missing.

Controls:

  • B β€” toggle open/close (blocked if chat or an input field is focused)
  • Escape β€” close when open
  • Click a slot β€” equip/unequip gear, or use consumables
  • Hover a slot β€” shows ItemTooltipUI near the cursor
  • Drag the header β€” repositions the window (clamped to screen bounds via InventoryWindowDragHandle)
  • Drag a slot outside the window β€” deletes the item. Common-rarity items delete immediately. Items of Uncommon rarity or higher show a confirmation dialog before the request is sent.

Filter tabs: All Β· Gear Β· Materials

  • Gear β€” items whose databaseItemType contains weapon, armor, offhand, ring, trinket, or gear.
  • Materials β€” items whose type contains "material".
  • All β€” no filter.

The footer shows the character's current gold from PlayerProgressManager.Local.Gold.

Slot visuals: Filled slots display a rarity-colored background tint and a neon-colored Outline component (rarityOutline) on the slot border. The neon color is derived from the item's rarity color. Empty slots use a plain dark background with no outline.

Automatic refresh: InventoryBagUI.Refresh() is called by PlayerProgressManager.ApplyKillReward() on every kill reward response and by ForgeCraftingPanel after a successful craft. Kill loot is inserted directly into the authoritative inventory by the auth server, so this refresh pulls the updated server snapshot β€” including any dropped items β€” without the client adding items locally. If a refresh fetch is already in flight when Refresh() is called, the second refresh is queued and fires immediately after the first completes.

API endpoints:

  • GET /api/inventory/:characterId β€” fetch current inventory (JWT-gated)
  • POST /api/inventory/equip β€” toggle equipped state for a slot
  • POST /api/inventory/save β€” save full inventory state (used after consuming an item)
  • POST /api/inventory/delete β€” delete a single slot by characterId and slot_index (JWT-gated)
  • POST /api/inventory/add-item β€” add an item to inventory (called by the client after picking up a world item; returns { success, data: { stored, rejected } })

Consumables

Items recognized by ConsumableEffect.IsConsumable(itemId) are consumed on click rather than equipped. ConsumableEffect.Apply() runs on the local player, quantity decrements by one, the slot is cleared if depleted, and the inventory is saved to the server.

ConsumableEffect.TryGetTooltip(itemId, out string tooltip) returns a player-facing description of the item's effect. This is used by inventory and vendor tooltips.

Known consumable effect types and their behavior:

Effect typeBehavior
hp_regenRestores HP gradually over a duration (DoT-style ticks). Stacks are replaced, not added.
mana_restoreRestores MP immediately via CharacterStats.RestoreMana. No duration.
resist_voidReduces Void damage by a percentage for a duration.
resist_blastReduces Blast damage by a percentage for a duration.
speedIncreases movement speed by a percentage for a duration.
damage_ampIncreases damage output by a percentage for a duration.

Item stats in ConsumableEffect (code-verified 2026-08-20):

Item IDEffectValueDuration
flask_hp_minorhp_regen15 HP40 s
flask_mp_minormana_restore15 MPinstant
flask_hp_majorhp_regen80 HP60 s
flask_void_resistresist_void25%90 s
kit_iron_wardenresist_blast25%60 s

Mining materials

The following ore and ingot items are defined in Loot Forge (Assets/Game/Resources/LootForge/Items/) and are yielded by their corresponding gathering node definitions in Node Forge:

Ore item IDIngot item IDNode definition
ore_bronzeingot_bronzebronze_vein
ore_hellingot_hellhell_vein
ore_mooningot_moonmoon_vein
ore_silveringot_silversilver_vein
ore_steelingot_steelsteel_vein
ore_tiningot_tintin_vein

Ores are smelted into ingots at the Forge via the SMELT tab. See Editor Tooling for Node Forge and Loot Forge documentation.

GatheringLootTable

GatheringLootTable (ScriptableObject) is a weighted reward table used by gathering nodes. Create one via BCE β–Ά Gathering Loot Table in the Asset Create menu.

FieldTypeNotes
displayNamestringLabel shown in the Gathering HUD when the node uses this table. Default: "Random Resource".
entriesGatheringLootEntry[]Weighted entry list. Only entries with a valid LootItemDefinition of type Material and weight > 0 participate in rolls.

Each GatheringLootEntry carries:

FieldTypeNotes
itemLootItemDefinitionMust have databaseItemType == Material and a non-empty itemId.
weightfloatRelative probability weight (β‰₯ 0).
minimumQuantityintMinimum items awarded per roll (β‰₯ 1).
maximumQuantityintMaximum items awarded per roll (β‰₯ minimumQuantity).

TryRoll(out LootItemDefinition item, out int quantity) selects one eligible entry by weighted random and returns a quantity uniformly drawn from [minimumQuantity, maximumQuantity]. Returns false when no eligible entries exist.

A GatheringLootTable is assigned to a GatheringNodeDefinition via the lootTable field (labeled "Weighted Loot Table" in Node Forge). When assigned, the dedicated server rolls the reward; when absent, the node falls back to the bare itemId + itemQuantity fields.

Server-authoritative gathering award flow

When a networked gathering node grants an award, GatheringNodeNetworkState calls GatheringPersistenceService.Award() server-side. The service:

  1. Resolves characterId from the connection's PlayerIdentity.
  2. POSTs to POST /api/game/gathering/award using CROSSWORLDS_GAME_SERVICE_TOKEN (environment variable, 10-second timeout):

``json { "characterId": <int>, "nodeId": "<string>", "itemId": "<string>", "baseQuantity": <int>, "professionId": "<string>", "xpAmount": <int>, "bonusYieldLevel": <int> } ``

professionId is a string: 0 β†’ "woodcutting", 1 β†’ "fishing", all others β†’ "mining".

  1. On success, the server sends TargetAwardResult to the client with the confirmed item_id, stored quantity, skill_level, skill_xp, leveled_up, and whether bonus_yield was applied.
  1. The client AfkGatheringStation.OnAwardRequestCompleted handler:
  2. Calls ProfessionManager.ApplyAuthoritativeState() to update the local profession cache from the server-confirmed values.
  3. Reloads inventory via InventoryManager.LoadInventory().
  4. Displays a chat message and pulses the Gathering HUD.

The server response carries:

FieldTypeNotes
successboolWhether the award was stored.
errorstringHuman-readable reason on failure.
data.item_idstringItem actually stored.
data.storedintQuantity accepted into inventory.
data.rejectedintQuantity rejected (inventory full).
data.bonus_yieldboolWhether a bonus yield was applied.
data.skill_levelintProfession level after the award.
data.skill_xpintProfession XP after the award.
data.leveled_upboolWhether this award caused a level-up.

Offline/solo mode: When NetworkClient is not active, AfkGatheringStation rolls rewards locally using GatheringLootTable.TryRoll() and posts the item directly to POST /api/inventory/add-item. Bonus yield (20% chance to double quantity) applies only to Common or Uncommon items when the player's profession level is at or above bonusYieldLevel.

Sources: GatheringPersistenceService.cs, GatheringNodeNetworkState.cs, AfkGatheringStation.cs.

Vendors

NetworkVendor (Mirror NetworkBehaviour, INPCInteractable) is a world NPC placed in scenes. When the local player is within VendorProfile.interactionRadius units, the interaction prompt appears; pressing the interact key opens the vendor shop.

VendorProfile (ScriptableObject) defines the vendor's content:

FieldTypeNotes
vendorIdstringUnique identifier matched on the auth server.
displayNamestringShown as the shop title. Default: "Merchant".
subtitlestringOptional line shown below the vendor name in the shop window and hover tooltip. Default: empty.
buysItemsboolWhether the vendor has a Sell tab.
interactionRadiusfloat (0–20)Detection radius in world units, clamped to β‰₯ 1 at runtime.
stockVendorStockEntry[]Items the vendor sells.

Each VendorStockEntry references a LootItemDefinition item and carries a buyPrice (minimum 1 gold).

Buy flow: client calls RequestBuy(itemId, 1) β†’ CmdBuy on server validates proximity and request β†’ VendorPersistenceService POSTs { characterId, vendorId, itemId, quantity } to /api/game/vendors/buy β†’ result returned to client via TargetVendorResult.

Sell flow: client calls RequestSell(slotIndex, 1) β†’ CmdSell on server validates that buysItems is true, the slot exists (index 0–23), is unequipped, the item has sellValue > 0, and the player is within proximity β†’ POSTs { characterId, vendorId, slotIndex, quantity } to /api/game/vendors/sell.

After a transaction: InventoryManager.LoadInventory() reloads from the server, InventoryBagUI.Refresh() and PlayerProgressManager.Local.Refresh() are called.

Server sync: VendorPersistenceService.SyncProfile() is called OnStartServer for each NetworkVendor. It POSTs { vendorId, displayName, buysItems, stock } to /api/game/vendors/definitions using the CROSSWORLDS_GAME_SERVICE_TOKEN server environment variable, retrying up to 3 times on failure (3-second gap between retries, after an initial 2-second delay to allow Loot Forge item rows to be written first).

VendorShopUI is a client-side DontDestroyOnLoad singleton created on first use. It provides Buy and Sell tabs; the shop title shows the vendor's displayName with the subtitle displayed below it when non-empty. The Escape key closes the shop window.

VendorHoverUI shows the vendor name and subtitle (when non-empty) in a screen-space overlay when the player's cursor is over a vendor. The subtitle renders in smaller gold-tinted text below the name.

Sources: NetworkVendor.cs, VendorShopUI.cs, VendorProfile.cs, VendorPersistenceService.cs.

Crafting

Crafting takes place at the Forge (prefab_forge) in the Hub scene.

ForgeNPC

ForgeNPC (Assets/Game/Networking/ForgeNPC.cs) is a purely client-side MonoBehaviour placed on the prefab_forge GameObject. It is not a Mirror NetworkBehaviour; crafting API calls happen inside ForgeCraftingPanel.

Key fields:

  • professionId β€” the profession used for this forge (default 2 = Mining).
  • interactRange β€” proximity radius to show the E-prompt (default 3.5 units).
  • promptHeight β€” height of the world-space billboard prompt above the forge (default 3 units).

When the local player (PlayerIdentity.Local) enters interactRange, a world-space "[E] Craft" billboard appears. Pressing E while no TMP_InputField is focused opens ForgeCraftingPanel. The billboard is parented independently of the forge model hierarchy to avoid scale inheritance.

ForgeCraftingPanel

ForgeCraftingPanel (Assets/Game/UI/ForgeCraftingPanel.cs) is the crafting UI. It auto-instantiates from Resources/Forge/ForgeWindow.prefab at scene load (RuntimeInitializeOnLoadMethod(AfterSceneLoad)) and persists across scenes (DontDestroyOnLoad). ForgeCraftingPanel.Instance provides global access.

On Open(), the panel moves to the front of the canvas, restores any saved drag position, and fetches the character's available recipes from the server using AuthManager.CharacterId and AuthManager.Token. The panel has two tabs:

  • SMELT β€” raw gathering materials β†’ refined materials (e.g. ore β†’ ingot, log β†’ plank).
  • CRAFT β€” refined materials β†’ gear and consumables.

After a successful craft, the inventory is reloaded (InventoryManager.LoadInventory()) and InventoryBagUI.Refresh() is called. If the crafting action caused the profession to level up, the new level is shown in the status bar.

The panel is draggable (via ForgeWindowDragHandle) and can be closed with the Γ— button or the Escape key (while no input field is focused).

Rebuild the prefab if missing: BCE β–Ά Setup β–Ά Rebuild Forge Crafting UI.

RecipeRowUI

RecipeRowUI (Assets/Game/UI/RecipeRowUI.cs) renders one server-provided recipe row. Each row shows:

  • Rarity badge β€” color-coded strip on the left edge.
  • Item icon β€” sourced from LootItemCatalog.
  • Name and required level (dimmed when the recipe is locked).
  • Ingredients β€” listed as quantityΓ— name; ingredients the player lacks are shown in red.
  • Craft time.
  • CRAFT button β€” disabled (and row partially transparent) when the recipe is locked or any ingredient is insufficient.

Hovering a row triggers ItemTooltipUI for the result item.

Recipes and ingredients database

Recipes and ingredients are stored in the recipes and recipe_ingredients database tables. See Database Schema.


Related: Database Schema Β· Editor Tooling Β· Enemies, Waves & Bosses Β· Heroes and Classes