diff --git a/Assets/Script/ProductionFacility.cs b/Assets/Script/ProductionFacility.cs new file mode 100644 index 0000000..a92df94 --- /dev/null +++ b/Assets/Script/ProductionFacility.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using ZoneUA.Economy; +using ZoneUA.Inventory; +using ZoneUA.Persistence; + +[RequireComponent(typeof(PersistentIdentity))] +public sealed class ProductionFacility : MonoBehaviour, IPersistentSaveParticipant +{ + [Serializable] + private sealed class Payload + { + public List entries = new List(); + } + + [SerializeField] private InventoryComponent inputInventory; + [SerializeField] private InventoryComponent outputInventory; + [SerializeField] private List allowedRecipes = new List(); + [SerializeField] private bool processAutomatically = true; + + private readonly ProductionQueueState queue = new ProductionQueueState(); + + public string ParticipantKey => "production-facility"; + public int ParticipantVersion => 1; + public IReadOnlyList Queue => queue.entries; + + private void Awake() + { + inputInventory ??= GetComponent(); + outputInventory ??= inputInventory; + } + + private void Update() + { + if (processAutomatically) Tick(Time.deltaTime); + } + + public bool Enqueue(ProductionRecipe recipe, int cycles = 1) + { + if (recipe == null || cycles <= 0 || !allowedRecipes.Contains(recipe) || inputInventory == null) return false; + List totalInputs = recipe.BuildInputs() + .Select(entry => new InventoryEntry(entry.itemId, entry.amount * cycles)) + .ToList(); + if (!inputInventory.TryConsume(totalInputs)) return false; + queue.Enqueue(recipe.RecipeId, cycles); + return true; + } + + public void Tick(float deltaTime) + { + if (queue.entries.Count == 0) return; + ProductionRecipe recipe = FindRecipe(queue.entries[0].recipeId); + if (recipe == null) + { + queue.entries.RemoveAt(0); + return; + } + + InventoryComponent destination = outputInventory != null ? outputInventory : inputInventory; + if (destination == null) return; + List outputs = recipe.BuildOutputs(); + int outputCount = outputs.Sum(entry => entry.amount); + if (destination.Capacity > 0 && destination.TotalItemCount + outputCount > destination.Capacity) return; + + if (!queue.TryAdvance(deltaTime, recipe.DurationSeconds, out _)) return; + foreach (InventoryEntry output in outputs) destination.Add(output.itemId, output.amount); + } + + public string CaptureState() + { + queue.Normalize(); + return JsonUtility.ToJson(new Payload { entries = queue.entries }); + } + + public void RestoreState(string payload, int version) + { + Payload restored = JsonUtility.FromJson(payload ?? string.Empty); + queue.entries = restored?.entries ?? new List(); + queue.Normalize(); + } + + private ProductionRecipe FindRecipe(string recipeId) => allowedRecipes.FirstOrDefault(recipe => + recipe != null && string.Equals(recipe.RecipeId, recipeId, StringComparison.Ordinal)); +} diff --git a/Assets/Script/ProductionFacility.cs.meta b/Assets/Script/ProductionFacility.cs.meta new file mode 100644 index 0000000..e59cefd --- /dev/null +++ b/Assets/Script/ProductionFacility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b68a7ed129344ce8ad7d478faaf76bf4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/ResourceNode.cs b/Assets/Script/ResourceNode.cs new file mode 100644 index 0000000..bfb38c4 --- /dev/null +++ b/Assets/Script/ResourceNode.cs @@ -0,0 +1,98 @@ +using System; +using UnityEngine; +using ZoneUA.Economy; +using ZoneUA.Inventory; +using ZoneUA.Persistence; + +[RequireComponent(typeof(PersistentIdentity))] +public sealed class ResourceNode : MonoBehaviour, IPersistentSaveParticipant +{ + [Serializable] + private sealed class Payload + { + public string resourceId = string.Empty; + public int remainingUnits; + public float accumulatedWork; + public float respawnRemaining; + } + + [SerializeField] private ResourceNodeDefinition definition; + [SerializeField] private GameObject availableRoot; + [SerializeField] private GameObject depletedRoot; + + private HarvestState state; + + public string ParticipantKey => "resource-node"; + public int ParticipantVersion => 1; + public ResourceNodeDefinition Definition => definition; + public int RemainingUnits => state?.remainingUnits ?? 0; + public bool IsDepleted => state == null || state.IsDepleted; + + private void Awake() + { + EnsureState(); + RefreshPresentation(); + } + + private void Update() + { + if (state == null || !state.IsDepleted || definition == null || definition.RespawnSeconds <= 0f) return; + state.respawnRemaining = Mathf.Max(0f, state.respawnRemaining - Time.deltaTime); + if (state.respawnRemaining <= 0f) + { + state.Restore(definition.TotalUnits, 0f, 0f); + RefreshPresentation(); + } + } + + public int ApplyWork(float work, InventoryComponent destination) + { + EnsureState(); + if (definition == null || destination == null || definition.YieldedItem == null) return 0; + + int harvested = state.ApplyWork(work, definition.WorkPerHarvest, definition.UnitsPerHarvest); + if (harvested <= 0) return 0; + + if (!destination.Add(definition.YieldedItem.ItemId, harvested)) + { + state.remainingUnits += harvested; + return 0; + } + + if (state.IsDepleted && definition.RespawnSeconds > 0f) state.respawnRemaining = definition.RespawnSeconds; + RefreshPresentation(); + return harvested; + } + + public string CaptureState() + { + EnsureState(); + return JsonUtility.ToJson(new Payload + { + resourceId = definition != null ? definition.ResourceId : string.Empty, + remainingUnits = state.remainingUnits, + accumulatedWork = state.accumulatedWork, + respawnRemaining = state.respawnRemaining + }); + } + + public void RestoreState(string payload, int version) + { + EnsureState(); + Payload restored = JsonUtility.FromJson(payload ?? string.Empty); + if (restored == null) return; + state.Restore(restored.remainingUnits, restored.accumulatedWork, restored.respawnRemaining); + RefreshPresentation(); + } + + private void EnsureState() + { + if (state == null) state = new HarvestState(definition != null ? definition.TotalUnits : 0); + } + + private void RefreshPresentation() + { + if (availableRoot != null) availableRoot.SetActive(!IsDepleted); + if (depletedRoot != null) depletedRoot.SetActive(IsDepleted); + } +} diff --git a/Assets/Script/ResourceNode.cs.meta b/Assets/Script/ResourceNode.cs.meta new file mode 100644 index 0000000..f49b0c2 --- /dev/null +++ b/Assets/Script/ResourceNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd8aeb6eff294f9fa2d529f26c94b53a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/WorkerJobAgent.cs b/Assets/Script/WorkerJobAgent.cs new file mode 100644 index 0000000..c2cbacf --- /dev/null +++ b/Assets/Script/WorkerJobAgent.cs @@ -0,0 +1,92 @@ +using System; +using UnityEngine; +using ZoneUA.Economy; +using ZoneUA.Persistence; + +[RequireComponent(typeof(PersistentIdentity))] +public sealed class WorkerJobAgent : MonoBehaviour, IPersistentSaveParticipant +{ + [Serializable] + private sealed class Payload + { + public WorkerJobKind kind; + public string targetObjectId = string.Empty; + } + + [SerializeField] private InventoryComponent carryInventory; + [SerializeField, Min(0.01f)] private float workPerSecond = 1f; + [SerializeField, Min(0.01f)] private float interactionRange = 1f; + + private readonly WorkerJobState state = new WorkerJobState(); + private ResourceNode resourceTarget; + private InventoryComponent deliveryTarget; + + public string ParticipantKey => "worker-job"; + public int ParticipantVersion => 1; + public WorkerJobKind CurrentJob => state.kind; + + private void Awake() => carryInventory ??= GetComponent(); + + private void Update() + { + if (state.kind != WorkerJobKind.Harvest || resourceTarget == null || carryInventory == null) return; + if (Vector2.Distance(transform.position, resourceTarget.transform.position) > interactionRange) return; + + resourceTarget.ApplyWork(workPerSecond * Time.deltaTime, carryInventory); + if (resourceTarget.IsDepleted || carryInventory.Capacity > 0 && carryInventory.TotalItemCount >= carryInventory.Capacity) + { + if (deliveryTarget != null) DeliverAll(deliveryTarget); + ClearJob(); + } + } + + public void AssignHarvest(ResourceNode node, InventoryComponent deposit = null) + { + resourceTarget = node; + deliveryTarget = deposit; + PersistentIdentity identity = node != null ? node.GetComponent() : null; + state.Assign(WorkerJobKind.Harvest, identity != null ? identity.ObjectId : string.Empty); + } + + public void ClearJob() + { + resourceTarget = null; + deliveryTarget = null; + state.Clear(); + } + + public int DeliverAll(InventoryComponent destination) + { + if (carryInventory == null || destination == null) return 0; + int delivered = 0; + var snapshot = new System.Collections.Generic.List(carryInventory.Entries); + foreach (ZoneUA.Inventory.InventoryEntry entry in snapshot) + { + if (!destination.Add(entry.itemId, entry.amount)) continue; + carryInventory.Remove(entry.itemId, entry.amount); + delivered += entry.amount; + } + return delivered; + } + + public string CaptureState() => JsonUtility.ToJson(new Payload + { + kind = state.kind, + targetObjectId = state.targetObjectId + }); + + public void RestoreState(string payload, int version) + { + Payload restored = JsonUtility.FromJson(payload ?? string.Empty); + if (restored == null) return; + state.Assign(restored.kind, restored.targetObjectId); + resourceTarget = null; + deliveryTarget = null; + } + + private void OnValidate() + { + workPerSecond = Mathf.Max(0.01f, workPerSecond); + interactionRange = Mathf.Max(0.01f, interactionRange); + } +} diff --git a/Assets/Script/WorkerJobAgent.cs.meta b/Assets/Script/WorkerJobAgent.cs.meta new file mode 100644 index 0000000..5ba4ff5 --- /dev/null +++ b/Assets/Script/WorkerJobAgent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7ddfc5ba15744a2ace6fbc89c6a84d4 +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 f27f7bf..b38f475 100644 --- a/Assets/_ZoneUA/Editor/ZoneUA.EditorValidation.asmdef +++ b/Assets/_ZoneUA/Editor/ZoneUA.EditorValidation.asmdef @@ -4,7 +4,8 @@ "references": [ "ZoneUA.SceneManagement", "ZoneUA.Persistence", - "ZoneUA.Inventory" + "ZoneUA.Inventory", + "ZoneUA.Economy" ], "includePlatforms": [ "Editor" diff --git a/Assets/_ZoneUA/Editor/ZoneUAEconomyContentValidator.cs b/Assets/_ZoneUA/Editor/ZoneUAEconomyContentValidator.cs new file mode 100644 index 0000000..e9912bc --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAEconomyContentValidator.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEditor.Build; +using UnityEditor.Build.Reporting; +using UnityEngine; +using ZoneUA.Economy; + +namespace ZoneUA.EditorValidation +{ + public static class ZoneUAEconomyContentValidator + { + [MenuItem("Zone UA/Validation/Validate Economy Content")] + public static void ValidateFromMenu() + { + IReadOnlyList errors = Validate(); + if (errors.Count == 0) + { + Debug.Log("Zone UA economy validation passed."); + return; + } + foreach (string error in errors) Debug.LogError(error); + Debug.LogError($"Zone UA economy validation failed with {errors.Count} error(s)."); + } + + public static IReadOnlyList Validate() + { + var errors = new List(); + ValidateResources(errors); + ValidateRecipes(errors); + return errors; + } + + private static void ValidateResources(List errors) + { + var ids = new HashSet(StringComparer.Ordinal); + foreach (string guid in AssetDatabase.FindAssets("t:ResourceNodeDefinition")) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + ResourceNodeDefinition definition = AssetDatabase.LoadAssetAtPath(path); + if (definition == null) continue; + if (string.IsNullOrWhiteSpace(definition.ResourceId)) errors.Add($"Resource definition has an empty ID: {path}"); + else if (!ids.Add(definition.ResourceId)) errors.Add($"Duplicate resource ID '{definition.ResourceId}': {path}"); + if (definition.YieldedItem == null) errors.Add($"Resource definition has no yielded item: {path}"); + } + } + + private static void ValidateRecipes(List errors) + { + var ids = new HashSet(StringComparer.Ordinal); + foreach (string guid in AssetDatabase.FindAssets("t:ProductionRecipe")) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + ProductionRecipe recipe = AssetDatabase.LoadAssetAtPath(path); + if (recipe == null) continue; + if (string.IsNullOrWhiteSpace(recipe.RecipeId)) errors.Add($"Production recipe has an empty ID: {path}"); + else if (!ids.Add(recipe.RecipeId)) errors.Add($"Duplicate production recipe ID '{recipe.RecipeId}': {path}"); + if (recipe.Outputs == null || recipe.Outputs.Count == 0) errors.Add($"Production recipe has no outputs: {path}"); + if (recipe.Inputs.Any(value => value == null || value.item == null || value.amount <= 0)) errors.Add($"Production recipe has an invalid input: {path}"); + if (recipe.Outputs.Any(value => value == null || value.item == null || value.amount <= 0)) errors.Add($"Production recipe has an invalid output: {path}"); + } + } + } + + public sealed class ZoneUAEconomyBuildValidator : IPreprocessBuildWithReport + { + public int callbackOrder => 40; + + public void OnPreprocessBuild(BuildReport report) + { + IReadOnlyList errors = ZoneUAEconomyContentValidator.Validate(); + if (errors.Count > 0) throw new BuildFailedException(string.Join("\n", errors)); + } + } +} diff --git a/Assets/_ZoneUA/Editor/ZoneUAEconomyContentValidator.cs.meta b/Assets/_ZoneUA/Editor/ZoneUAEconomyContentValidator.cs.meta new file mode 100644 index 0000000..d4890fa --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAEconomyContentValidator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7eb983244d4c4c64925af0e689a17683 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Economy.meta b/Assets/_ZoneUA/Runtime/Economy.meta new file mode 100644 index 0000000..d59c12d --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 641c91ce49f3479ca761df11b203d6aa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Economy/EconomyStates.cs b/Assets/_ZoneUA/Runtime/Economy/EconomyStates.cs new file mode 100644 index 0000000..2ea8c4a --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/EconomyStates.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using ZoneUA.Inventory; + +namespace ZoneUA.Economy +{ + [Serializable] + public sealed class HarvestState + { + public int remainingUnits; + public float accumulatedWork; + public float respawnRemaining; + + public bool IsDepleted => remainingUnits <= 0; + + public HarvestState(int totalUnits) => remainingUnits = Math.Max(0, totalUnits); + + public int ApplyWork(float work, float requiredWork, int unitsPerHarvest) + { + if (IsDepleted || work <= 0f) return 0; + accumulatedWork += work; + int harvested = 0; + float threshold = Math.Max(0.01f, requiredWork); + int batch = Math.Max(1, unitsPerHarvest); + while (accumulatedWork >= threshold && remainingUnits > 0) + { + accumulatedWork -= threshold; + int amount = Math.Min(batch, remainingUnits); + remainingUnits -= amount; + harvested += amount; + } + return harvested; + } + + public void Restore(int remaining, float work, float respawn) + { + remainingUnits = Math.Max(0, remaining); + accumulatedWork = Math.Max(0f, work); + respawnRemaining = Math.Max(0f, respawn); + } + } + + [Serializable] + public sealed class ProductionQueueEntry + { + public string recipeId = string.Empty; + public int remainingCycles = 1; + public float elapsed; + } + + [Serializable] + public sealed class ProductionQueueState + { + public List entries = new List(); + + public void Enqueue(string recipeId, int cycles) + { + if (string.IsNullOrWhiteSpace(recipeId) || cycles <= 0) return; + entries.Add(new ProductionQueueEntry { recipeId = recipeId.Trim(), remainingCycles = cycles }); + } + + public bool TryAdvance(float deltaTime, float duration, out string completedRecipeId) + { + completedRecipeId = string.Empty; + if (entries.Count == 0 || deltaTime <= 0f) return false; + ProductionQueueEntry current = entries[0]; + current.elapsed += deltaTime; + if (current.elapsed < Math.Max(0.01f, duration)) return false; + current.elapsed = 0f; + current.remainingCycles--; + completedRecipeId = current.recipeId; + if (current.remainingCycles <= 0) entries.RemoveAt(0); + return true; + } + + public void Normalize() + { + entries = entries + .Where(x => x != null && !string.IsNullOrWhiteSpace(x.recipeId) && x.remainingCycles > 0) + .Select(x => new ProductionQueueEntry + { + recipeId = x.recipeId.Trim(), + remainingCycles = x.remainingCycles, + elapsed = Math.Max(0f, x.elapsed) + }) + .ToList(); + } + } + + public enum WorkerJobKind { None, Harvest, Deliver, Produce } + + [Serializable] + public sealed class WorkerJobState + { + public WorkerJobKind kind; + public string targetObjectId = string.Empty; + public bool resourcesReserved; + + public void Assign(WorkerJobKind jobKind, string targetId) + { + kind = jobKind; + targetObjectId = targetId?.Trim() ?? string.Empty; + resourcesReserved = false; + } + + public void Clear() + { + kind = WorkerJobKind.None; + targetObjectId = string.Empty; + resourcesReserved = false; + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Economy/EconomyStates.cs.meta b/Assets/_ZoneUA/Runtime/Economy/EconomyStates.cs.meta new file mode 100644 index 0000000..a7ebf22 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/EconomyStates.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c60f96803c84747a8ffb89e452ffefd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Economy/ProductionRecipe.cs b/Assets/_ZoneUA/Runtime/Economy/ProductionRecipe.cs new file mode 100644 index 0000000..501fe5e --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/ProductionRecipe.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using ZoneUA.Inventory; + +namespace ZoneUA.Economy +{ + [Serializable] + public sealed class ProductionAmount + { + public ItemDefinition item; + [Min(1)] public int amount = 1; + } + + [CreateAssetMenu(menuName = "Zone UA/Economy/Production Recipe", fileName = "ProductionRecipe")] + public sealed class ProductionRecipe : ScriptableObject + { + [SerializeField] private string recipeId = string.Empty; + [SerializeField, Min(0.01f)] private float durationSeconds = 1f; + [SerializeField] private List inputs = new List(); + [SerializeField] private List outputs = new List(); + + public string RecipeId => recipeId; + public float DurationSeconds => Mathf.Max(0.01f, durationSeconds); + public IReadOnlyList Inputs => inputs; + public IReadOnlyList Outputs => outputs; + + public List BuildInputs() => BuildEntries(inputs); + public List BuildOutputs() => BuildEntries(outputs); + + private static List BuildEntries(IEnumerable amounts) + { + var result = new List(); + if (amounts == null) return result; + foreach (ProductionAmount entry in amounts) + { + if (entry?.item == null || string.IsNullOrWhiteSpace(entry.item.ItemId) || entry.amount <= 0) continue; + result.Add(new InventoryEntry(entry.item.ItemId, entry.amount)); + } + return result; + } + + private void OnValidate() + { + recipeId = recipeId?.Trim() ?? string.Empty; + durationSeconds = Mathf.Max(0.01f, durationSeconds); + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Economy/ProductionRecipe.cs.meta b/Assets/_ZoneUA/Runtime/Economy/ProductionRecipe.cs.meta new file mode 100644 index 0000000..9f8574c --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/ProductionRecipe.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5ab8d8a16cf54c91bc790851884a8335 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Economy/ResourceNodeDefinition.cs b/Assets/_ZoneUA/Runtime/Economy/ResourceNodeDefinition.cs new file mode 100644 index 0000000..c3c081f --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/ResourceNodeDefinition.cs @@ -0,0 +1,32 @@ +using UnityEngine; +using ZoneUA.Inventory; + +namespace ZoneUA.Economy +{ + [CreateAssetMenu(menuName = "Zone UA/Economy/Resource Node Definition", fileName = "ResourceNodeDefinition")] + public sealed class ResourceNodeDefinition : ScriptableObject + { + [SerializeField] private string resourceId = string.Empty; + [SerializeField] private ItemDefinition yieldedItem; + [SerializeField, Min(1)] private int totalUnits = 10; + [SerializeField, Min(1)] private int unitsPerHarvest = 1; + [SerializeField, Min(0.01f)] private float workPerHarvest = 1f; + [SerializeField, Min(0f)] private float respawnSeconds; + + public string ResourceId => resourceId; + public ItemDefinition YieldedItem => yieldedItem; + public int TotalUnits => Mathf.Max(1, totalUnits); + public int UnitsPerHarvest => Mathf.Max(1, unitsPerHarvest); + public float WorkPerHarvest => Mathf.Max(0.01f, workPerHarvest); + public float RespawnSeconds => Mathf.Max(0f, respawnSeconds); + + private void OnValidate() + { + resourceId = resourceId?.Trim() ?? string.Empty; + totalUnits = Mathf.Max(1, totalUnits); + unitsPerHarvest = Mathf.Clamp(unitsPerHarvest, 1, totalUnits); + workPerHarvest = Mathf.Max(0.01f, workPerHarvest); + respawnSeconds = Mathf.Max(0f, respawnSeconds); + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Economy/ResourceNodeDefinition.cs.meta b/Assets/_ZoneUA/Runtime/Economy/ResourceNodeDefinition.cs.meta new file mode 100644 index 0000000..078314a --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/ResourceNodeDefinition.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d74452f61f6e42c89491ec16db3901c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Economy/ZoneUA.Economy.asmdef b/Assets/_ZoneUA/Runtime/Economy/ZoneUA.Economy.asmdef new file mode 100644 index 0000000..b4f774e --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/ZoneUA.Economy.asmdef @@ -0,0 +1,17 @@ +{ + "name": "ZoneUA.Economy", + "rootNamespace": "ZoneUA.Economy", + "references": [ + "ZoneUA.Inventory", + "ZoneUA.Persistence" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Assets/_ZoneUA/Runtime/Economy/ZoneUA.Economy.asmdef.meta b/Assets/_ZoneUA/Runtime/Economy/ZoneUA.Economy.asmdef.meta new file mode 100644 index 0000000..b368f9c --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Economy/ZoneUA.Economy.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a3b9b34f62454c2c93fa36b4d35dd1e3 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/EditMode/EconomyProductionTests.cs b/Assets/_ZoneUA/Tests/EditMode/EconomyProductionTests.cs new file mode 100644 index 0000000..9ec4156 --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/EconomyProductionTests.cs @@ -0,0 +1,74 @@ +using NUnit.Framework; +using ZoneUA.Economy; + +namespace ZoneUA.Combat.Tests +{ + public sealed class EconomyProductionTests + { + [Test] + public void HarvestState_AccumulatesWorkAndDepletesDeterministically() + { + var state = new HarvestState(5); + + Assert.That(state.ApplyWork(0.5f, 1f, 2), Is.EqualTo(0)); + Assert.That(state.ApplyWork(0.5f, 1f, 2), Is.EqualTo(2)); + Assert.That(state.remainingUnits, Is.EqualTo(3)); + Assert.That(state.ApplyWork(2f, 1f, 2), Is.EqualTo(3)); + Assert.That(state.IsDepleted, Is.True); + } + + [Test] + public void HarvestState_RestoreClampsInvalidValues() + { + var state = new HarvestState(10); + state.Restore(-10, -5f, -3f); + + Assert.That(state.remainingUnits, Is.Zero); + Assert.That(state.accumulatedWork, Is.Zero); + Assert.That(state.respawnRemaining, Is.Zero); + } + + [Test] + public void ProductionQueue_AdvancesOneCycleAtATime() + { + var queue = new ProductionQueueState(); + queue.Enqueue("plank", 2); + + Assert.That(queue.TryAdvance(0.5f, 1f, out _), Is.False); + Assert.That(queue.TryAdvance(0.5f, 1f, out string first), Is.True); + Assert.That(first, Is.EqualTo("plank")); + Assert.That(queue.entries[0].remainingCycles, Is.EqualTo(1)); + Assert.That(queue.TryAdvance(1f, 1f, out string second), Is.True); + Assert.That(second, Is.EqualTo("plank")); + Assert.That(queue.entries, Is.Empty); + } + + [Test] + public void ProductionQueue_NormalizeRemovesInvalidEntries() + { + var queue = new ProductionQueueState(); + queue.entries.Add(new ProductionQueueEntry { recipeId = "", remainingCycles = 1 }); + queue.entries.Add(new ProductionQueueEntry { recipeId = " valid ", remainingCycles = 2, elapsed = -1f }); + + queue.Normalize(); + + Assert.That(queue.entries.Count, Is.EqualTo(1)); + Assert.That(queue.entries[0].recipeId, Is.EqualTo("valid")); + Assert.That(queue.entries[0].elapsed, Is.Zero); + } + + [Test] + public void WorkerJobState_AssignAndClearAreExplicit() + { + var state = new WorkerJobState(); + state.Assign(WorkerJobKind.Harvest, " node-1 "); + + Assert.That(state.kind, Is.EqualTo(WorkerJobKind.Harvest)); + Assert.That(state.targetObjectId, Is.EqualTo("node-1")); + + state.Clear(); + Assert.That(state.kind, Is.EqualTo(WorkerJobKind.None)); + Assert.That(state.targetObjectId, Is.Empty); + } + } +} diff --git a/Assets/_ZoneUA/Tests/EditMode/EconomyProductionTests.cs.meta b/Assets/_ZoneUA/Tests/EditMode/EconomyProductionTests.cs.meta new file mode 100644 index 0000000..cc2f318 --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/EconomyProductionTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b8ec0a28e2f441b7a756e9cc358806f4 +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 d50d492..1195bad 100644 --- a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef +++ b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef @@ -12,7 +12,8 @@ "ZoneUA.Performance", "ZoneUA.SceneManagement", "ZoneUA.Persistence", - "ZoneUA.Inventory" + "ZoneUA.Inventory", + "ZoneUA.Economy" ], "includePlatforms": [ "Editor" diff --git a/Docs/RESOURCE_JOBS_PRODUCTION.md b/Docs/RESOURCE_JOBS_PRODUCTION.md new file mode 100644 index 0000000..4d96200 --- /dev/null +++ b/Docs/RESOURCE_JOBS_PRODUCTION.md @@ -0,0 +1,84 @@ +# Resource Gathering, Jobs and Production + +This module adds deterministic economy loops on top of inventory, construction and stable-ID persistence. + +## Content definitions + +Create assets through: + +- `Create -> Zone UA -> Economy -> Resource Node Definition` +- `Create -> Zone UA -> Economy -> Production Recipe` + +Resource definitions require a unique resource ID, yielded item, total units, units per harvest and work per harvest. Optional respawn time restores the node after depletion. + +Recipes require a unique recipe ID, duration, valid inputs and at least one output. + +## Resource node prefab + +Recommended composition: + +- `PersistentIdentity` +- `TransformSaveParticipant` +- `ResourceNode` +- collider used by selection or worker interaction +- optional available/depleted presentation roots + +`ResourceNode` persists remaining units, partial accumulated work and respawn time through participant key `resource-node`. + +Harvest output is committed to an `InventoryComponent`. When the destination inventory cannot accept the harvested batch, the node restores the removed units, so resources are never silently lost. + +## Worker job agent + +Add `WorkerJobAgent` and an `InventoryComponent` to a worker prefab. Jobs are assigned through: + +```csharp +worker.AssignHarvest(resourceNode, storageInventory); +worker.ClearJob(); +``` + +The current implementation deliberately owns job state and work execution, but does not replace the existing movement/pathfinding system. The unit command layer should move the worker into `interactionRange`; once in range, the agent applies deterministic work. + +Worker job state is persisted through participant key `worker-job`. After load, target IDs remain available for a higher-level job registry to rebind scene references. + +## Production facility + +Recommended composition: + +- `PersistentIdentity` +- `TransformSaveParticipant` +- one or two `InventoryComponent` instances +- `InventorySaveParticipant` for every persistent inventory +- `ProductionFacility` + +A facility consumes all required inputs atomically when a recipe is queued. It then advances production over time. If output storage is full, progress pauses before completing the cycle, preventing lost output. + +The queue stores recipe IDs, remaining cycles and current elapsed time through participant key `production-facility`. + +## Validation + +Run: + +`Zone UA -> Validation -> Validate Economy Content` + +Validation blocks builds for: + +- empty resource IDs; +- duplicate resource IDs; +- resource definitions without yielded items; +- empty recipe IDs; +- duplicate recipe IDs; +- recipes without outputs; +- invalid input or output entries. + +## Required Play Mode checks + +1. Assign a worker to a resource node and move it into interaction range. +2. Confirm partial work accumulates deterministically. +3. Confirm a full carry inventory does not delete resource units. +4. Save during partial harvest and reload. +5. Deplete and respawn a renewable node. +6. Queue multiple production cycles. +7. Save during an active production cycle and reload. +8. Fill output storage and confirm production pauses. +9. Free storage capacity and confirm production resumes exactly once. +10. Unload and reload scenes and verify stable-ID participants restore without duplicates. diff --git a/Docs/RESOURCE_JOBS_PRODUCTION.md.meta b/Docs/RESOURCE_JOBS_PRODUCTION.md.meta new file mode 100644 index 0000000..c8dbb88 --- /dev/null +++ b/Docs/RESOURCE_JOBS_PRODUCTION.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 60cb87b3216b44428c24d6e9e14b2590 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: