diff --git a/Assets/Script/CorpseLootContainer.cs b/Assets/Script/CorpseLootContainer.cs new file mode 100644 index 0000000..42ee668 --- /dev/null +++ b/Assets/Script/CorpseLootContainer.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using UnityEngine; +using ZoneUA.Inventory; + +[RequireComponent(typeof(LootContainer), typeof(InventoryComponent))] +public sealed class CorpseLootContainer : MonoBehaviour +{ + [SerializeField] private bool clearSourceInventory = true; + + private InventoryComponent corpseInventory; + private LootContainer lootContainer; + + public bool IsInitialised { get; private set; } + + private void Awake() + { + corpseInventory = GetComponent(); + lootContainer = GetComponent(); + } + + public bool InitialiseFrom(InventoryComponent sourceInventory) + { + if (IsInitialised || sourceInventory == null || sourceInventory == corpseInventory) return false; + + List snapshot = new List(sourceInventory.Entries); + corpseInventory.ReplaceContents(snapshot); + if (clearSourceInventory) sourceInventory.ReplaceContents(System.Array.Empty()); + + lootContainer.MarkSearched(); + IsInitialised = true; + return true; + } +} diff --git a/Assets/Script/CorpseLootContainer.cs.meta b/Assets/Script/CorpseLootContainer.cs.meta new file mode 100644 index 0000000..952ef95 --- /dev/null +++ b/Assets/Script/CorpseLootContainer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a5a67ee4bb7410fb69a0dbdd5503ec1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/InventoryComponent.cs b/Assets/Script/InventoryComponent.cs new file mode 100644 index 0000000..e9017ca --- /dev/null +++ b/Assets/Script/InventoryComponent.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using ZoneUA.Inventory; + +[DisallowMultipleComponent] +public sealed class InventoryComponent : MonoBehaviour +{ + [SerializeField, Min(0)] private int capacity; + [SerializeField] private List initialItems = new List(); + + private InventoryState state; + + public event Action InventoryChanged; + public InventoryState State => state ??= CreateState(); + public IReadOnlyList Entries => State.Entries; + public int Capacity => State.Capacity; + public int TotalItemCount => State.TotalItemCount; + + private void Awake() => state = CreateState(); + + public int GetAmount(string itemId) => State.GetAmount(itemId); + public bool Has(string itemId, int amount = 1) => State.Has(itemId, amount); + + public bool Add(string itemId, int amount) + { + if (!State.Add(itemId, amount)) return false; + NotifyExternalChange(); + return true; + } + + public bool Remove(string itemId, int amount) + { + if (!State.Remove(itemId, amount)) return false; + NotifyExternalChange(); + return true; + } + + public bool TryConsume(IEnumerable costs) + { + if (!State.TryConsume(costs)) return false; + NotifyExternalChange(); + return true; + } + + public bool TryTransferTo(InventoryComponent destination, string itemId, int amount) + { + if (destination == null || !State.TryTransferTo(destination.State, itemId, amount)) return false; + NotifyExternalChange(); + destination.NotifyExternalChange(); + return true; + } + + public void ReplaceContents(IEnumerable entries) + { + State.Replace(entries); + NotifyExternalChange(); + } + + public void NotifyExternalChange() => InventoryChanged?.Invoke(); + + private InventoryState CreateState() + { + var result = new InventoryState(capacity); + result.Replace(initialItems); + return result; + } + + private void OnValidate() => capacity = Mathf.Max(0, capacity); +} diff --git a/Assets/Script/InventoryComponent.cs.meta b/Assets/Script/InventoryComponent.cs.meta new file mode 100644 index 0000000..dd34850 --- /dev/null +++ b/Assets/Script/InventoryComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 47aa3cb45f4644839c3ca8fb52b1e987 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/InventoryDropper.cs b/Assets/Script/InventoryDropper.cs new file mode 100644 index 0000000..f94b00c --- /dev/null +++ b/Assets/Script/InventoryDropper.cs @@ -0,0 +1,54 @@ +using System; +using UnityEngine; +using ZoneUA.Inventory; +using ZoneUA.Persistence; + +[RequireComponent(typeof(InventoryComponent))] +public sealed class InventoryDropper : MonoBehaviour +{ + [SerializeField] private ItemCatalog itemCatalog; + [SerializeField] private Transform dropOrigin; + [SerializeField] private Transform droppedItemsRoot; + [SerializeField, Min(0f)] private float forwardOffset = 0.75f; + + private InventoryComponent inventory; + + private void Awake() + { + inventory = GetComponent(); + dropOrigin ??= transform; + } + + public bool Drop(string itemId, int amount = 1) + { + Vector3 position = (dropOrigin != null ? dropOrigin.position : transform.position) + transform.right * forwardOffset; + return DropAt(itemId, amount, position); + } + + public bool DropAt(string itemId, int amount, Vector3 position) + { + inventory ??= GetComponent(); + if (amount <= 0 || itemCatalog == null || !itemCatalog.TryGet(itemId, out ItemDefinition item)) return false; + if (item.WorldPrefab == null || !inventory.Remove(item.ItemId, amount)) return false; + + GameObject instance = null; + try + { + instance = Instantiate(item.WorldPrefab, position, Quaternion.identity, droppedItemsRoot); + PersistentIdentity identity = instance.GetComponent() ?? instance.AddComponent(); + identity.AssignRuntimeId(Guid.NewGuid().ToString("N"), item.PersistentWorldPrefabId); + WorldItemPickup pickup = instance.GetComponent() ?? instance.AddComponent(); + pickup.Configure(item, amount); + return true; + } + catch (Exception exception) + { + inventory.Add(item.ItemId, amount); + if (instance != null) Destroy(instance); + Debug.LogException(exception, this); + return false; + } + } + + private void OnValidate() => forwardOffset = Mathf.Max(0f, forwardOffset); +} diff --git a/Assets/Script/InventoryDropper.cs.meta b/Assets/Script/InventoryDropper.cs.meta new file mode 100644 index 0000000..e799c01 --- /dev/null +++ b/Assets/Script/InventoryDropper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 354b3a2f6ac344db94fbec506f61429f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/InventorySaveParticipant.cs b/Assets/Script/InventorySaveParticipant.cs new file mode 100644 index 0000000..34d1b5c --- /dev/null +++ b/Assets/Script/InventorySaveParticipant.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using ZoneUA.Inventory; +using ZoneUA.Persistence; + +[RequireComponent(typeof(InventoryComponent))] +public sealed class InventorySaveParticipant : MonoBehaviour, IPersistentSaveParticipant +{ + [Serializable] + private sealed class Payload + { + public List entries = new List(); + } + + private InventoryComponent inventory; + + public string ParticipantKey => "inventory"; + public int ParticipantVersion => 1; + + private void Awake() => inventory = GetComponent(); + + public string CaptureState() + { + inventory ??= GetComponent(); + return JsonUtility.ToJson(new Payload { entries = new List(inventory.Entries) }); + } + + public void RestoreState(string payload, int version) + { + inventory ??= GetComponent(); + Payload state = string.IsNullOrWhiteSpace(payload) ? new Payload() : JsonUtility.FromJson(payload); + inventory.ReplaceContents(state?.entries ?? new List()); + } +} diff --git a/Assets/Script/InventorySaveParticipant.cs.meta b/Assets/Script/InventorySaveParticipant.cs.meta new file mode 100644 index 0000000..e755419 --- /dev/null +++ b/Assets/Script/InventorySaveParticipant.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38801d9187684c1388fa6e57b5d3c2be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/LootContainer.cs b/Assets/Script/LootContainer.cs new file mode 100644 index 0000000..c337029 --- /dev/null +++ b/Assets/Script/LootContainer.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using ZoneUA.Inventory; +using ZoneUA.Persistence; + +[RequireComponent(typeof(PersistentIdentity), typeof(InventoryComponent), typeof(InventorySaveParticipant))] +public sealed class LootContainer : MonoBehaviour, ILootSource, IPersistentSaveParticipant +{ + [Serializable] + private sealed class Payload + { + public LootSearchState searchState; + } + + [SerializeField] private LootSourceKind kind = LootSourceKind.Container; + [SerializeField, Min(0f)] private float searchDurationSeconds = 1f; + [SerializeField] private bool startsSearched; + + private PersistentIdentity identity; + private InventoryComponent inventory; + private LootSearchState searchState; + + public event Action SearchStateChanged; + public event Action ContentsChanged; + + public string LootSourceId => identity != null ? identity.ObjectId : string.Empty; + public LootSourceKind Kind => kind; + public LootSearchState SearchState => searchState; + public bool IsAvailable => inventory != null && inventory.TotalItemCount > 0; + public IReadOnlyList Entries => inventory != null ? inventory.Entries : Array.Empty(); + public float SearchDurationSeconds => Mathf.Max(0f, searchDurationSeconds); + public string ParticipantKey => "loot-source"; + public int ParticipantVersion => 1; + + private void Awake() + { + identity = GetComponent(); + inventory = GetComponent(); + searchState = startsSearched ? ResolveVisibleState() : LootSearchState.Unsearched; + inventory.InventoryChanged += HandleContentsChanged; + } + + private void OnDestroy() + { + if (inventory != null) inventory.InventoryChanged -= HandleContentsChanged; + } + + public void MarkSearched() + { + LootSearchState next = ResolveVisibleState(); + if (searchState == next) return; + searchState = next; + SearchStateChanged?.Invoke(searchState); + } + + public bool TryTake(InventoryState destination, string itemId, int amount) + { + if (searchState == LootSearchState.Unsearched || inventory == null || destination == null) return false; + bool transferred = inventory.State.TryTransferTo(destination, itemId, amount); + if (transferred) HandleContentsChanged(); + return transferred; + } + + public bool TryTake(InventoryComponent destination, string itemId, int amount) + { + if (destination == null) return false; + bool transferred = TryTake(destination.State, itemId, amount); + if (transferred) destination.NotifyExternalChange(); + return transferred; + } + + public string CaptureState() => JsonUtility.ToJson(new Payload { searchState = searchState }); + + public void RestoreState(string payload, int version) + { + Payload restored = string.IsNullOrWhiteSpace(payload) ? null : JsonUtility.FromJson(payload); + searchState = restored != null ? restored.searchState : startsSearched ? ResolveVisibleState() : LootSearchState.Unsearched; + if (!IsAvailable) searchState = LootSearchState.Empty; + SearchStateChanged?.Invoke(searchState); + } + + private void HandleContentsChanged() + { + if (!IsAvailable && searchState != LootSearchState.Empty) + { + searchState = LootSearchState.Empty; + SearchStateChanged?.Invoke(searchState); + } + ContentsChanged?.Invoke(); + } + + private LootSearchState ResolveVisibleState() => IsAvailable ? LootSearchState.Searched : LootSearchState.Empty; + + private void OnValidate() => searchDurationSeconds = Mathf.Max(0f, searchDurationSeconds); +} diff --git a/Assets/Script/LootContainer.cs.meta b/Assets/Script/LootContainer.cs.meta new file mode 100644 index 0000000..e84d227 --- /dev/null +++ b/Assets/Script/LootContainer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b7dd22bb0d74aeca348e26af07d6f38 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/WorldItemPickup.cs b/Assets/Script/WorldItemPickup.cs new file mode 100644 index 0000000..535f984 --- /dev/null +++ b/Assets/Script/WorldItemPickup.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using ZoneUA.Inventory; +using ZoneUA.Persistence; + +[RequireComponent(typeof(PersistentIdentity))] +public sealed class WorldItemPickup : MonoBehaviour, ILootSource, IPersistentSaveParticipant +{ + [Serializable] + private sealed class Payload + { + public int amount = 1; + } + + [SerializeField] private ItemDefinition item; + [SerializeField, Min(1)] private int amount = 1; + [SerializeField] private bool pickupOnTrigger = true; + + private PersistentIdentity identity; + private bool consumed; + + public ItemDefinition Item => item; + public int Amount => Mathf.Max(1, amount); + public string LootSourceId => identity != null ? identity.ObjectId : string.Empty; + public LootSourceKind Kind => LootSourceKind.WorldItem; + public LootSearchState SearchState => consumed ? LootSearchState.Empty : LootSearchState.Searched; + public bool IsAvailable => !consumed && item != null && !string.IsNullOrWhiteSpace(item.ItemId); + public IReadOnlyList Entries => IsAvailable + ? new[] { new InventoryEntry(item.ItemId, Amount) } + : Array.Empty(); + public string ParticipantKey => "world-item"; + public int ParticipantVersion => 1; + + private void Awake() => identity = GetComponent(); + + public void Configure(ItemDefinition definition, int itemAmount) + { + item = definition; + amount = Mathf.Max(1, itemAmount); + consumed = false; + } + + public void MarkSearched() { } + + public bool TryTake(InventoryState destination, string itemId, int requestedAmount) + { + if (!IsAvailable || destination == null || requestedAmount != Amount || !string.Equals(item.ItemId, itemId, StringComparison.Ordinal)) return false; + if (!destination.Add(item.ItemId, Amount)) return false; + Consume(); + return true; + } + + public bool TryPickup(InventoryComponent inventory) + { + if (inventory == null || !TryTake(inventory.State, item != null ? item.ItemId : string.Empty, Amount)) return false; + inventory.NotifyExternalChange(); + return true; + } + + public string CaptureState() => JsonUtility.ToJson(new Payload { amount = Amount }); + + public void RestoreState(string payload, int version) + { + Payload restored = string.IsNullOrWhiteSpace(payload) ? new Payload() : JsonUtility.FromJson(payload); + amount = Mathf.Max(1, restored?.amount ?? 1); + consumed = false; + } + + private void Consume() + { + consumed = true; + identity ??= GetComponent(); + identity.MarkDestroyed(); + } + + private void OnTriggerEnter2D(Collider2D other) + { + if (!pickupOnTrigger || other == null) return; + InventoryComponent inventory = other.GetComponentInParent(); + if (inventory != null) TryPickup(inventory); + } + + private void OnValidate() => amount = Mathf.Max(1, amount); +} diff --git a/Assets/Script/WorldItemPickup.cs.meta b/Assets/Script/WorldItemPickup.cs.meta new file mode 100644 index 0000000..4a5616d --- /dev/null +++ b/Assets/Script/WorldItemPickup.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba80c6a69ed146f995653ee5233bd072 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Editor/ZoneUA.EditorValidation.asmdef b/Assets/_ZoneUA/Editor/ZoneUA.EditorValidation.asmdef index d01e07b..f27f7bf 100644 --- a/Assets/_ZoneUA/Editor/ZoneUA.EditorValidation.asmdef +++ b/Assets/_ZoneUA/Editor/ZoneUA.EditorValidation.asmdef @@ -3,7 +3,8 @@ "rootNamespace": "ZoneUA.EditorValidation", "references": [ "ZoneUA.SceneManagement", - "ZoneUA.Persistence" + "ZoneUA.Persistence", + "ZoneUA.Inventory" ], "includePlatforms": [ "Editor" @@ -16,4 +17,4 @@ "defineConstraints": [], "versionDefines": [], "noEngineReferences": false -} \ No newline at end of file +} diff --git a/Assets/_ZoneUA/Editor/ZoneUAInventoryContentValidator.cs b/Assets/_ZoneUA/Editor/ZoneUAInventoryContentValidator.cs new file mode 100644 index 0000000..4db1be2 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAInventoryContentValidator.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.Build; +using UnityEditor.Build.Reporting; +using UnityEngine; +using ZoneUA.Inventory; + +namespace ZoneUA.EditorValidation +{ + public static class ZoneUAInventoryContentValidator + { + [MenuItem("Zone UA/Validation/Validate Inventory and Loot", priority = 45)] + public static void ValidateMenu() + { + bool valid = Validate(logResults: true); + EditorUtility.DisplayDialog("Inventory and loot validation", valid ? "Validation passed." : "Validation failed. See Console.", "OK"); + } + + public static bool Validate(bool logResults) + { + var errors = new List(); + var warnings = new List(); + ValidateItems(errors, warnings); + ValidateLoadedObjects(errors, warnings); + + if (logResults) + { + foreach (string warning in warnings) Debug.LogWarning("[Inventory Validation] " + warning); + foreach (string error in errors) Debug.LogError("[Inventory Validation] " + error); + if (errors.Count == 0) Debug.Log($"Inventory and loot validation passed with {warnings.Count} warning(s)."); + } + return errors.Count == 0; + } + + private static void ValidateItems(ICollection errors, ICollection warnings) + { + var seen = new Dictionary(StringComparer.Ordinal); + foreach (string guid in AssetDatabase.FindAssets("t:ItemDefinition")) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + ItemDefinition item = AssetDatabase.LoadAssetAtPath(path); + if (item == null) continue; + if (string.IsNullOrWhiteSpace(item.ItemId)) errors.Add($"ItemDefinition has an empty item ID: {path}"); + else if (seen.TryGetValue(item.ItemId, out string other)) errors.Add($"Duplicate item ID '{item.ItemId}': {other} and {path}"); + else seen[item.ItemId] = path; + if (item.WorldPrefab == null) warnings.Add($"Item '{item.ItemId}' has no world prefab: {path}"); + if (item.BaseValue == 0) warnings.Add($"Item '{item.ItemId}' has zero base loot value: {path}"); + } + } + + private static void ValidateLoadedObjects(ICollection errors, ICollection warnings) + { + ValidateTypeComposition("InventoryComponent", "InventorySaveParticipant", warnings); + ValidateTypeComposition("WorldItemPickup", "PersistentIdentity", errors); + ValidateTypeComposition("LootContainer", "PersistentIdentity", errors); + ValidateTypeComposition("LootContainer", "InventoryComponent", errors); + ValidateTypeComposition("LootContainer", "InventorySaveParticipant", errors); + ValidateTypeComposition("CorpseLootContainer", "LootContainer", errors); + } + + private static void ValidateTypeComposition(string ownerTypeName, string requiredTypeName, ICollection issues) + { + Type ownerType = RuntimeTypeResolver.Resolve(ownerTypeName); + Type requiredType = RuntimeTypeResolver.Resolve(requiredTypeName); + if (ownerType == null || requiredType == null) return; + foreach (UnityEngine.Object item in Resources.FindObjectsOfTypeAll(ownerType)) + { + if (item is not Component component || EditorUtility.IsPersistent(component)) continue; + if (component.GetComponent(requiredType) == null) + issues.Add($"'{component.name}' contains {ownerTypeName} but is missing {requiredTypeName}."); + } + } + } + + public sealed class ZoneUAInventoryContentBuildValidator : IPreprocessBuildWithReport + { + public int callbackOrder => 90; + public void OnPreprocessBuild(BuildReport report) + { + if (!ZoneUAInventoryContentValidator.Validate(logResults: true)) + throw new BuildFailedException("Inventory or loot content validation failed."); + } + } +} diff --git a/Assets/_ZoneUA/Editor/ZoneUAInventoryContentValidator.cs.meta b/Assets/_ZoneUA/Editor/ZoneUAInventoryContentValidator.cs.meta new file mode 100644 index 0000000..b9a89e3 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAInventoryContentValidator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d575120c9db64612bfaa86337e1d9dba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Inventory.meta b/Assets/_ZoneUA/Runtime/Inventory.meta new file mode 100644 index 0000000..c9b0811 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8b8fb47518984642af6048d0c3c94127 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Inventory/InventoryState.cs b/Assets/_ZoneUA/Runtime/Inventory/InventoryState.cs new file mode 100644 index 0000000..782a1a9 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/InventoryState.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace ZoneUA.Inventory +{ + [Serializable] + public sealed class InventoryEntry + { + public string itemId = string.Empty; + public int amount; + + public InventoryEntry() { } + public InventoryEntry(string itemId, int amount) + { + this.itemId = itemId ?? string.Empty; + this.amount = Math.Max(0, amount); + } + } + + public sealed class InventoryState + { + private readonly Dictionary amounts = new Dictionary(StringComparer.Ordinal); + private readonly int capacity; + + public InventoryState(int capacity = 0) => this.capacity = Math.Max(0, capacity); + public int Capacity => capacity; + public int DistinctItemCount => amounts.Count; + public int TotalItemCount => amounts.Values.Sum(); + public int FreeCapacity => capacity <= 0 ? int.MaxValue : Math.Max(0, capacity - TotalItemCount); + public IReadOnlyList Entries => amounts.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair => new InventoryEntry(pair.Key, pair.Value)).ToList(); + + public int GetAmount(string itemId) => Normalize(itemId) is string id && amounts.TryGetValue(id, out int value) ? value : 0; + + public bool CanAdd(string itemId, int amount) + { + string id = Normalize(itemId); + if (string.IsNullOrEmpty(id) || amount <= 0) return false; + return capacity <= 0 || TotalItemCount + amount <= capacity; + } + + public bool Add(string itemId, int amount) + { + string id = Normalize(itemId); + if (!CanAdd(id, amount)) return false; + amounts[id] = GetAmount(id) + amount; + return true; + } + + public bool Has(string itemId, int amount = 1) => amount > 0 && GetAmount(itemId) >= amount; + + public bool Remove(string itemId, int amount) + { + string id = Normalize(itemId); + if (string.IsNullOrEmpty(id) || amount <= 0 || !amounts.TryGetValue(id, out int current) || current < amount) return false; + int remaining = current - amount; + if (remaining == 0) amounts.Remove(id); else amounts[id] = remaining; + return true; + } + + public bool TryConsume(IEnumerable costs) + { + List normalized = NormalizeEntries(costs); + if (normalized.Any(entry => !Has(entry.itemId, entry.amount))) return false; + foreach (InventoryEntry entry in normalized) Remove(entry.itemId, entry.amount); + return true; + } + + public bool TryTransferTo(InventoryState destination, string itemId, int amount) + { + if (destination == null || ReferenceEquals(destination, this) || amount <= 0) return false; + string id = Normalize(itemId); + if (string.IsNullOrEmpty(id) || !Has(id, amount) || !destination.CanAdd(id, amount)) return false; + if (!Remove(id, amount)) return false; + if (destination.Add(id, amount)) return true; + Add(id, amount); + return false; + } + + public void Replace(IEnumerable entries) + { + amounts.Clear(); + foreach (InventoryEntry entry in NormalizeEntries(entries)) + { + if (capacity > 0 && TotalItemCount + entry.amount > capacity) break; + amounts[entry.itemId] = GetAmount(entry.itemId) + entry.amount; + } + } + + public static List NormalizeEntries(IEnumerable entries) + { + return (entries ?? Array.Empty()) + .Where(entry => entry != null && entry.amount > 0 && !string.IsNullOrWhiteSpace(entry.itemId)) + .GroupBy(entry => entry.itemId.Trim(), StringComparer.Ordinal) + .Select(group => new InventoryEntry(group.Key, group.Sum(entry => entry.amount))) + .OrderBy(entry => entry.itemId, StringComparer.Ordinal) + .ToList(); + } + + private static string Normalize(string value) => string.IsNullOrWhiteSpace(value) ? string.Empty : value.Trim(); + } +} diff --git a/Assets/_ZoneUA/Runtime/Inventory/InventoryState.cs.meta b/Assets/_ZoneUA/Runtime/Inventory/InventoryState.cs.meta new file mode 100644 index 0000000..e76be8b --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/InventoryState.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9312ca7bc66476ea4ed928ec1dd61df +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Inventory/ItemCatalog.cs b/Assets/_ZoneUA/Runtime/Inventory/ItemCatalog.cs new file mode 100644 index 0000000..3b2b523 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/ItemCatalog.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace ZoneUA.Inventory +{ + [CreateAssetMenu(menuName = "Zone UA/Inventory/Item Catalog", fileName = "ItemCatalog")] + public sealed class ItemCatalog : ScriptableObject + { + [SerializeField] private List items = new List(); + + public IReadOnlyList Items => items; + + public bool TryGet(string itemId, out ItemDefinition definition) + { + definition = null; + if (string.IsNullOrWhiteSpace(itemId)) return false; + foreach (ItemDefinition item in items) + { + if (item != null && string.Equals(item.ItemId, itemId.Trim(), StringComparison.Ordinal)) + { + definition = item; + return true; + } + } + return false; + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Inventory/ItemCatalog.cs.meta b/Assets/_ZoneUA/Runtime/Inventory/ItemCatalog.cs.meta new file mode 100644 index 0000000..354aed8 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/ItemCatalog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b8abd425ddc480684bae4fc0a66a6d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Inventory/ItemDefinition.cs b/Assets/_ZoneUA/Runtime/Inventory/ItemDefinition.cs new file mode 100644 index 0000000..19b0833 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/ItemDefinition.cs @@ -0,0 +1,52 @@ +using UnityEngine; + +namespace ZoneUA.Inventory +{ + public enum ItemCategory + { + Miscellaneous = 0, + Weapon = 1, + Ammunition = 2, + Medical = 3, + Armour = 4, + Consumable = 5, + Quest = 6, + Valuable = 7 + } + + [CreateAssetMenu(menuName = "Zone UA/Inventory/Item Definition", fileName = "ItemDefinition")] + public sealed class ItemDefinition : ScriptableObject + { + [SerializeField] private string itemId = string.Empty; + [SerializeField] private string displayName = string.Empty; + [SerializeField, TextArea] private string description = string.Empty; + [SerializeField] private ItemCategory category; + [SerializeField, Min(0)] private int baseValue; + [SerializeField, Min(0f)] private float weight; + [SerializeField] private Sprite icon; + [SerializeField, Min(1)] private int maximumStack = 1; + [SerializeField] private GameObject worldPrefab; + [SerializeField, Tooltip("Prefab catalog ID used when a dropped item must be recreated from a save.")] + private string persistentWorldPrefabId = string.Empty; + + public string ItemId => itemId; + public string DisplayName => string.IsNullOrWhiteSpace(displayName) ? name : displayName; + public string Description => description; + public ItemCategory Category => category; + public int BaseValue => Mathf.Max(0, baseValue); + public float Weight => Mathf.Max(0f, weight); + public Sprite Icon => icon; + public int MaximumStack => Mathf.Max(1, maximumStack); + public GameObject WorldPrefab => worldPrefab; + public string PersistentWorldPrefabId => string.IsNullOrWhiteSpace(persistentWorldPrefabId) ? itemId : persistentWorldPrefabId; + + private void OnValidate() + { + itemId = itemId?.Trim() ?? string.Empty; + persistentWorldPrefabId = persistentWorldPrefabId?.Trim() ?? string.Empty; + baseValue = Mathf.Max(0, baseValue); + weight = Mathf.Max(0f, weight); + maximumStack = Mathf.Max(1, maximumStack); + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Inventory/ItemDefinition.cs.meta b/Assets/_ZoneUA/Runtime/Inventory/ItemDefinition.cs.meta new file mode 100644 index 0000000..f80baf4 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/ItemDefinition.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 252b69fc6d624fd5abce1b3b04aec077 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Inventory/LootContracts.cs b/Assets/_ZoneUA/Runtime/Inventory/LootContracts.cs new file mode 100644 index 0000000..d5206b7 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/LootContracts.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; + +namespace ZoneUA.Inventory +{ + public enum LootSourceKind + { + WorldItem = 0, + Container = 1, + Corpse = 2 + } + + public enum LootSearchState + { + Unsearched = 0, + Searched = 1, + Empty = 2 + } + + public interface ILootSource + { + string LootSourceId { get; } + LootSourceKind Kind { get; } + LootSearchState SearchState { get; } + bool IsAvailable { get; } + IReadOnlyList Entries { get; } + void MarkSearched(); + bool TryTake(InventoryState destination, string itemId, int amount); + } + + [Serializable] + public sealed class LootContainerState + { + private readonly InventoryState inventory; + private LootSearchState searchState; + + public LootContainerState(int capacity = 0, IEnumerable initialItems = null, bool startsSearched = false) + { + inventory = new InventoryState(capacity); + inventory.Replace(initialItems); + searchState = startsSearched ? ResolveVisibleState() : LootSearchState.Unsearched; + } + + public InventoryState Inventory => inventory; + public LootSearchState SearchState => searchState; + public bool IsAvailable => inventory.TotalItemCount > 0; + public IReadOnlyList Entries => inventory.Entries; + + public void MarkSearched() => searchState = ResolveVisibleState(); + + public bool TryTake(InventoryState destination, string itemId, int amount) + { + if (searchState == LootSearchState.Unsearched || destination == null) return false; + bool transferred = inventory.TryTransferTo(destination, itemId, amount); + if (transferred) searchState = ResolveVisibleState(); + return transferred; + } + + public void Restore(IEnumerable entries, LootSearchState restoredState) + { + inventory.Replace(entries); + searchState = inventory.TotalItemCount == 0 + ? LootSearchState.Empty + : restoredState == LootSearchState.Unsearched ? LootSearchState.Unsearched : LootSearchState.Searched; + } + + private LootSearchState ResolveVisibleState() => inventory.TotalItemCount == 0 ? LootSearchState.Empty : LootSearchState.Searched; + } +} diff --git a/Assets/_ZoneUA/Runtime/Inventory/LootContracts.cs.meta b/Assets/_ZoneUA/Runtime/Inventory/LootContracts.cs.meta new file mode 100644 index 0000000..1e742c6 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/LootContracts.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e4f9dc4dbeb4ce5a1cff5d71ae8d7a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Inventory/LootReservationRegistry.cs b/Assets/_ZoneUA/Runtime/Inventory/LootReservationRegistry.cs new file mode 100644 index 0000000..8ec2c6d --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/LootReservationRegistry.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; + +namespace ZoneUA.Inventory +{ + public sealed class LootReservationRegistry + { + private sealed class Reservation + { + public string ownerId; + public double expiresAt; + } + + private readonly Dictionary reservations = new Dictionary(StringComparer.Ordinal); + + public bool TryReserve(string sourceId, string ownerId, double now, double durationSeconds) + { + sourceId = Normalize(sourceId); + ownerId = Normalize(ownerId); + if (string.IsNullOrEmpty(sourceId) || string.IsNullOrEmpty(ownerId) || durationSeconds <= 0d) return false; + PruneExpired(now); + if (reservations.TryGetValue(sourceId, out Reservation existing) && !string.Equals(existing.ownerId, ownerId, StringComparison.Ordinal)) return false; + reservations[sourceId] = new Reservation { ownerId = ownerId, expiresAt = now + durationSeconds }; + return true; + } + + public bool IsReservedByOther(string sourceId, string ownerId, double now) + { + PruneExpired(now); + sourceId = Normalize(sourceId); + ownerId = Normalize(ownerId); + return reservations.TryGetValue(sourceId, out Reservation existing) + && !string.Equals(existing.ownerId, ownerId, StringComparison.Ordinal); + } + + public void Release(string sourceId, string ownerId) + { + sourceId = Normalize(sourceId); + ownerId = Normalize(ownerId); + if (!reservations.TryGetValue(sourceId, out Reservation existing)) return; + if (string.IsNullOrEmpty(ownerId) || string.Equals(existing.ownerId, ownerId, StringComparison.Ordinal)) reservations.Remove(sourceId); + } + + public void ReleaseAll(string ownerId) + { + ownerId = Normalize(ownerId); + if (string.IsNullOrEmpty(ownerId)) return; + var keys = new List(); + foreach (KeyValuePair pair in reservations) + if (string.Equals(pair.Value.ownerId, ownerId, StringComparison.Ordinal)) keys.Add(pair.Key); + foreach (string key in keys) reservations.Remove(key); + } + + public void PruneExpired(double now) + { + var keys = new List(); + foreach (KeyValuePair pair in reservations) + if (pair.Value.expiresAt <= now) keys.Add(pair.Key); + foreach (string key in keys) reservations.Remove(key); + } + + private static string Normalize(string value) => string.IsNullOrWhiteSpace(value) ? string.Empty : value.Trim(); + } +} diff --git a/Assets/_ZoneUA/Runtime/Inventory/LootReservationRegistry.cs.meta b/Assets/_ZoneUA/Runtime/Inventory/LootReservationRegistry.cs.meta new file mode 100644 index 0000000..b089b3a --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/LootReservationRegistry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 91e41e8c598b451fb1f0d3b7cf0a2c2b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Inventory/ZoneUA.Inventory.asmdef b/Assets/_ZoneUA/Runtime/Inventory/ZoneUA.Inventory.asmdef new file mode 100644 index 0000000..bc4b95c --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/ZoneUA.Inventory.asmdef @@ -0,0 +1,14 @@ +{ + "name": "ZoneUA.Inventory", + "rootNamespace": "ZoneUA.Inventory", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Assets/_ZoneUA/Runtime/Inventory/ZoneUA.Inventory.asmdef.meta b/Assets/_ZoneUA/Runtime/Inventory/ZoneUA.Inventory.asmdef.meta new file mode 100644 index 0000000..14d93b6 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Inventory/ZoneUA.Inventory.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6ccd2d06ac9543d99329469715866adb +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/EditMode/InventoryLootTests.cs b/Assets/_ZoneUA/Tests/EditMode/InventoryLootTests.cs new file mode 100644 index 0000000..5df715c --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/InventoryLootTests.cs @@ -0,0 +1,90 @@ +using System.Collections.Generic; +using NUnit.Framework; +using ZoneUA.Inventory; + +namespace ZoneUA.Combat.Tests +{ + public sealed class InventoryLootTests + { + [Test] + public void Inventory_AddRemoveAndCapacity_AreDeterministic() + { + var state = new InventoryState(5); + Assert.That(state.Add("ammo-9x19", 3), Is.True); + Assert.That(state.Add("medkit", 2), Is.True); + Assert.That(state.Add("food", 1), Is.False); + Assert.That(state.Remove("ammo-9x19", 2), Is.True); + Assert.That(state.GetAmount("ammo-9x19"), Is.EqualTo(1)); + Assert.That(state.TotalItemCount, Is.EqualTo(3)); + } + + [Test] + public void Inventory_TryConsume_IsAtomic() + { + var state = new InventoryState(); + state.Add("ammo-9x19", 3); + state.Add("medkit", 1); + + bool failed = state.TryConsume(new[] + { + new InventoryEntry("ammo-9x19", 2), + new InventoryEntry("medkit", 2) + }); + + Assert.That(failed, Is.False); + Assert.That(state.GetAmount("ammo-9x19"), Is.EqualTo(3)); + Assert.That(state.GetAmount("medkit"), Is.EqualTo(1)); + } + + [Test] + public void Inventory_Transfer_IsAtomicWhenDestinationIsFull() + { + var source = new InventoryState(); + var destination = new InventoryState(1); + source.Add("medkit", 2); + destination.Add("ammo-9x19", 1); + + Assert.That(source.TryTransferTo(destination, "medkit", 1), Is.False); + Assert.That(source.GetAmount("medkit"), Is.EqualTo(2)); + Assert.That(destination.GetAmount("medkit"), Is.Zero); + } + + [Test] + public void LootContainer_MustBeSearchedBeforeTransfer() + { + var loot = new LootContainerState(initialItems: new[] { new InventoryEntry("medkit", 1) }); + var destination = new InventoryState(); + + Assert.That(loot.TryTake(destination, "medkit", 1), Is.False); + loot.MarkSearched(); + Assert.That(loot.TryTake(destination, "medkit", 1), Is.True); + Assert.That(loot.SearchState, Is.EqualTo(LootSearchState.Empty)); + Assert.That(destination.GetAmount("medkit"), Is.EqualTo(1)); + } + + [Test] + public void Reservation_RejectsOtherNpcUntilExpiry() + { + var registry = new LootReservationRegistry(); + Assert.That(registry.TryReserve("corpse-1", "npc-a", 10d, 5d), Is.True); + Assert.That(registry.TryReserve("corpse-1", "npc-b", 11d, 5d), Is.False); + Assert.That(registry.IsReservedByOther("corpse-1", "npc-b", 11d), Is.True); + Assert.That(registry.TryReserve("corpse-1", "npc-b", 16d, 5d), Is.True); + } + + [Test] + public void Inventory_Replace_MergesDuplicateIds() + { + var state = new InventoryState(); + state.Replace(new List + { + new InventoryEntry("ammo-9x19", 2), + new InventoryEntry("ammo-9x19", 3), + new InventoryEntry("medkit", 1) + }); + + Assert.That(state.GetAmount("ammo-9x19"), Is.EqualTo(5)); + Assert.That(state.DistinctItemCount, Is.EqualTo(2)); + } + } +} diff --git a/Assets/_ZoneUA/Tests/EditMode/InventoryLootTests.cs.meta b/Assets/_ZoneUA/Tests/EditMode/InventoryLootTests.cs.meta new file mode 100644 index 0000000..b3d319e --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/InventoryLootTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4979ae9e54a447db978c84b7ff36a793 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef index 7999c47..2c525a5 100644 --- a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef +++ b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef @@ -11,7 +11,8 @@ "ZoneUA.Input", "ZoneUA.Performance", "ZoneUA.SceneManagement", - "ZoneUA.Persistence" + "ZoneUA.Persistence", + "ZoneUA.Inventory" ], "includePlatforms": [ "Editor" diff --git a/Docs/RPG_INVENTORY_LOOT.md b/Docs/RPG_INVENTORY_LOOT.md new file mode 100644 index 0000000..9611dbb --- /dev/null +++ b/Docs/RPG_INVENTORY_LOOT.md @@ -0,0 +1,100 @@ +# RPG Inventory and Persistent Loot + +This module provides definition-driven items, deterministic inventories, persistent world pickups, searchable containers and corpse loot for the Zone UA top-down shooter RPG. + +## Item assets + +Create items with: + +`Create -> Zone UA -> Inventory -> Item Definition` + +Each item requires a unique `Item Id`. Configure category, base loot value, weight, stack size, world prefab and persistent world prefab ID. The value/category fields are intended for future NPC loot evaluation. + +Create an `ItemCatalog` and assign it to systems that need to resolve item IDs into definitions or world prefabs. + +## Player and NPC inventories + +A persistent actor should contain: + +- `PersistentIdentity` +- `InventoryComponent` +- `InventorySaveParticipant` + +Both players and raid NPCs use the same inventory state. Initial spawn equipment can be configured through `InventoryComponent.initialItems`; acquired loot is added through normal transfer operations. + +Inventory transfer is atomic. A failed transfer caused by missing source items or destination capacity leaves both inventories unchanged. + +## World pickups + +A persistent world item should contain: + +- `PersistentIdentity` +- `TransformSaveParticipant` +- `WorldItemPickup` +- an interaction or trigger collider + +`WorldItemPickup` implements `ILootSource`, so the player and AI can use the same loot contract. A successful pickup creates a tombstone through `PersistentIdentity.MarkDestroyed()`, preventing the authored or runtime item from reappearing after save/load. + +Dropped item prefabs must be registered in `PersistentPrefabCatalog` using the item's persistent world prefab ID. + +## Searchable containers + +A crate, stash or other searchable container should contain: + +- `PersistentIdentity` +- `TransformSaveParticipant` +- `InventoryComponent` +- `InventorySaveParticipant` +- `LootContainer` + +`LootContainer` stores whether the source is unsearched, searched or empty. Container contents are persisted by `InventorySaveParticipant`; search state is persisted through participant key `loot-source`. + +The configured search duration is presentation/gameplay data for the interaction and future raid-NPC task executor. The container does not own movement or UI. + +## Corpse loot + +A corpse prefab should contain the normal loot-container composition plus `CorpseLootContainer`. + +On death, initialise it from the dead actor's inventory: + +`corpseLootContainer.InitialiseFrom(deadActorInventory)` + +The corpse receives an inventory snapshot containing both spawn equipment and all acquired loot. By default the source inventory is cleared so pooled or disabled actors cannot expose the same items twice. + +## Loot reservations + +`LootReservationRegistry` prevents multiple raid NPCs from selecting the same world item, crate or corpse. Reservations contain a source ID, owner NPC ID and expiry time. + +Reservations are runtime coordination state and should normally not be written into save files. After loading, NPCs re-evaluate available loot and reserve targets again. + +Release reservations when an NPC dies, changes goal, cannot reach the target, completes looting or exceeds the reservation timeout. + +## Validation + +Run: + +`Zone UA -> Validation -> Validate Inventory and Loot` + +The validator checks: + +- empty or duplicate item IDs; +- missing world prefabs and zero-value item warnings; +- inventories without `InventorySaveParticipant`; +- world pickups without `PersistentIdentity`; +- loot containers without identity, inventory or inventory persistence; +- corpse containers without `LootContainer`. + +Errors block Unity builds. + +## Required Play Mode checks + +- collect a world pickup and confirm inventory count changes; +- confirm a full inventory does not consume or tombstone the item; +- drop a stack and confirm a new stable object ID is assigned; +- save/load a dropped stack exactly once; +- search a crate and transfer selected items; +- verify destination capacity cannot delete source loot; +- kill an NPC and initialise a corpse from its complete inventory; +- save/load corpse contents and search state; +- reserve one loot source from two NPCs and verify only one succeeds; +- expire or release a reservation and verify another NPC can claim it. diff --git a/Docs/RPG_INVENTORY_LOOT.md.meta b/Docs/RPG_INVENTORY_LOOT.md.meta new file mode 100644 index 0000000..1745ffa --- /dev/null +++ b/Docs/RPG_INVENTORY_LOOT.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 2661e97e92124af690302dd2c9098f09 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: