From c61b3eb0fa211caf536b4f9642b375a37cb539cc Mon Sep 17 00:00:00 2001 From: mcocdaa Date: Sat, 21 Nov 2026 11:39:57 +0100 Subject: [PATCH] refactor(actions): adopt Core CompositeToolCallBase, dynamic buildable catalog, and rotated blueprint fidelity refactor(actions): extract shared construction chainer and dynamic buildable catalog Split oversized composite tool base and spatial solver into focused modules, and replace hardcoded structure lists with dynamic DefDatabase discovery. - Move generic composite plumbing (ExecuteAtomicAsync, argument parsing, Classify, Manifest, ToolScopes) into Core CompositeToolCallBase; Actions base now only layers ownership and localized permission guards. - Extract ConstructionIntentChainer shared by PlaceBlueprint and PlanRoomProject, removing duplicated intent-session and work-giver logic. - Split ColonySpatialClusterSolver into SpatialGridModels, SpatialBuildingClassifier, and SpatialAsciiRenderer; add footprint min-offset support so center-anchored multi-cell buildings are placed using their real occupied rect and interaction cell. - Add BuildableStructureCatalogPolicy and discover buildable structures from DefDatabase (vanilla + modded) with category classification, cost formatting, affordability, and bounded ranking. - Delegate actor/map resolution to Core ActorMapResolver and resource counting to MapResourceCounter; parse arguments once per call. - Stop mutating player work priorities (no workSettings.SetPriority) in DesignateResources, ManageZone, and TriagePatient. - Add ToolScopes to all composite tools and enforce it in tests. --- .../Actions/AddWorktableBillCompositeTool.cs | 16 +- Source/Actions/CompositeToolCallBase.cs | 341 ++--------------- Source/Actions/ConstructionIntentChainer.cs | 195 ++++++++++ .../DesignateResourcesCompositeTool.cs | 332 ++++++++--------- .../Actions/EatAndRecreationCompositeTool.cs | 8 +- Source/Actions/EmergencyFleeCompositeTool.cs | 6 +- .../Actions/ManageEquipmentCompositeTool.cs | 14 +- Source/Actions/ManageZoneCompositeTool.cs | 34 +- Source/Actions/PlaceBlueprintCompositeTool.cs | 224 ++---------- .../Actions/PlanRoomProjectCompositeTool.cs | 133 ++----- .../QueryBuildableStructuresCompositeTool.cs | 293 +++++++++------ Source/Actions/StabilizeRestCompositeTool.cs | 6 +- Source/Actions/TriagePatientCompositeTool.cs | 16 +- Source/Debug/ActionsBehaviorAutotestSuite.cs | 2 +- Source/Policies/ActionPermissionGuard.cs | 59 +-- .../BuildableStructureCatalogPolicy.cs | 254 +++++++++++++ Source/Policies/ResourceSafetyGuard.cs | 31 +- Source/Policies/ResourceSafetyPolicy.cs | 17 +- Source/Spatial/ColonySpatialClusterSolver.cs | 346 ++++-------------- Source/Spatial/SpatialAsciiRenderer.cs | 78 ++++ Source/Spatial/SpatialBuildingClassifier.cs | 45 +++ Source/Spatial/SpatialGridModels.cs | 152 ++++++++ Tests/ColonySpatialClusterSolverTests.cs | 32 ++ Tests/CompositeToolRegistrationTests.cs | 14 + .../CompositeToolSelfDescriptionContracts.cs | 3 + Tests/DesignateResourcesToolTests.cs | 12 + Tests/PlaceBlueprintCompositeToolTests.cs | 15 +- Tests/PlanRoomProjectToolTests.cs | 10 +- ...ryBuildableStructuresCompositeToolTests.cs | 102 +++++- Tests/RimMindActions.Tests.csproj | 10 +- Tests/TriagePatientCompositeToolTests.cs | 1 + Tests/VerseStubs.cs | 5 + 32 files changed, 1489 insertions(+), 1317 deletions(-) create mode 100644 Source/Actions/ConstructionIntentChainer.cs create mode 100644 Source/Policies/BuildableStructureCatalogPolicy.cs create mode 100644 Source/Spatial/SpatialAsciiRenderer.cs create mode 100644 Source/Spatial/SpatialBuildingClassifier.cs create mode 100644 Source/Spatial/SpatialGridModels.cs diff --git a/Source/Actions/AddWorktableBillCompositeTool.cs b/Source/Actions/AddWorktableBillCompositeTool.cs index c5d6611..1222627 100644 --- a/Source/Actions/AddWorktableBillCompositeTool.cs +++ b/Source/Actions/AddWorktableBillCompositeTool.cs @@ -38,6 +38,7 @@ public sealed class AddWorktableBillCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.WorktableBills; + protected override ToolScope? ToolScopes => ToolScope.ColonyBuild; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => false; protected override string? DisplayName => "Add Worktable Bill"; @@ -69,7 +70,8 @@ public override Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - if (!TryGetArgument(args.ArgumentsJson, "recipe_def", out var recipeDefName) + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + if (!TryGetArgument(argsRoot, "recipe_def", out var recipeDefName) || string.IsNullOrWhiteSpace(recipeDefName)) { return Task.FromResult(Result.Err( @@ -77,9 +79,9 @@ public override Task> ExecuteAsync( } #if RIMMIND_ACTIONS_TESTS - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.WorktableBills; - if (TryGetArgument(args.ArgumentsJson, "pawn_id", out int testPawnId) && testPawnId > 0) + if (TryGetArgument(argsRoot, "pawn_id", out int testPawnId) && testPawnId > 0) { var guard = GuardColonistTarget(testPawnId, domain, args); if (guard.IsErr) @@ -90,7 +92,7 @@ public override Task> ExecuteAsync( return Task.FromResult(Result.Ok( ToolResult.Ok($"Added bill {recipeDefName}", args.ToolCallId, Id))); #else - var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true); + var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true, parsedArgs: argsRoot); if (actorResolution.Error != null) { return Task.FromResult(Result.Err( @@ -135,7 +137,7 @@ public override Task> ExecuteAsync( } // 3. Resolve Target WorkTable - TryGetArgument(args.ArgumentsJson, "worktable_def", out var worktableDefName); + TryGetArgument(argsRoot, "worktable_def", out var worktableDefName); Building_WorkTable? targetWorktable = null; var playerWorktables = map.listerBuildings?.allBuildingsColonist @@ -232,10 +234,10 @@ public override Task> ExecuteAsync( } // 5. Parse Options and Create Bill - TryGetArgument(args.ArgumentsJson, "target_count", out var targetCount); + TryGetArgument(argsRoot, "target_count", out var targetCount); if (targetCount <= 0) targetCount = 10; - TryGetArgument(args.ArgumentsJson, "repeat_mode", out var repeatModeStr); + TryGetArgument(argsRoot, "repeat_mode", out var repeatModeStr); bool isRepeatCount = string.Equals(repeatModeStr, "RepeatCount", StringComparison.OrdinalIgnoreCase); var newBill = recipeDef.MakeNewBill() as Bill_Production ?? new Bill_Production(recipeDef); diff --git a/Source/Actions/CompositeToolCallBase.cs b/Source/Actions/CompositeToolCallBase.cs index 3a685e4..b77845b 100644 --- a/Source/Actions/CompositeToolCallBase.cs +++ b/Source/Actions/CompositeToolCallBase.cs @@ -1,220 +1,46 @@ using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models.Tools; -using RimMind.Application.Features.Tools; using RimMind.Domain.Agent.Policies; using RimMind.Domain.Common; -using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; -using RimMind.Presentation.Api; namespace RimMind.Actions.Actions { - public abstract class CompositeToolCallBase : ICompositeToolCall, IToolPolicyClassifier + /// + /// Actions-module base class for composite ToolCalls. + /// Inherits Core's + /// (ExecuteAtomicAsync, single-pass TryParseArgumentsObject, Classify, + /// Manifest, and ToolScopes), layering Actions-specific ownership and localized + /// permission guards on top. + /// + public abstract class CompositeToolCallBase : RimMind.Presentation.Api.CompositeToolCallBase, ICompositeToolCall { - public abstract string Id { get; } - - private ToolDefinition? _cachedDefinition; - - public virtual string OwnerModId => "RimMindActions"; - - protected virtual ToolKind ToolKind => ToolKind.Mutation; - - protected virtual AutonomyDomain? DefaultAutonomyDomain => null; - - protected virtual RiskLevel DefaultRiskLevel => MapDomainToRisk(DefaultAutonomyDomain, ToolKind); - - protected virtual bool DefaultRequiresApproval => false; - - protected virtual IReadOnlyList ToolAliases => Array.Empty(); - - protected virtual bool IsSelfTargetedTool => false; - - protected virtual string? DisplayName => null; - - protected virtual IReadOnlyList SummaryArgKeys => Array.Empty(); - - public virtual ToolManifest Manifest => new ToolManifest - { - OwnerModId = OwnerModId, - Kind = ToolKind, - DefaultDomain = DefaultAutonomyDomain, - AutonomyDomainId = DefaultAutonomyDomain?.ToString(), - RiskLevel = DefaultRiskLevel, - RequiresApproval = DefaultRequiresApproval, - Aliases = ToolAliases, - IsSelfTargeted = IsSelfTargetedTool, - DisplayName = DisplayName, - SummaryArgKeys = SummaryArgKeys - }; - - public virtual ToolDefinition Definition => _cachedDefinition ??= BuildDefinition() with - { - Manifest = Manifest - }; - - protected virtual ToolDefinition BuildDefinition() => new ToolDefinition - { - Id = Id, - Manifest = Manifest - }; - - public abstract IReadOnlyList RequiredToolIds { get; } - - public abstract Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct); - - protected virtual AutonomyDomain? ResolveAutonomyDomain(JObject? root, ToolCallArgs args) - => DefaultAutonomyDomain; - - public virtual ToolPolicyDecision Classify(ToolCallArgs args) - { - var effectiveArgs = args ?? new ToolCallArgs - { - ToolName = Id, - ArgumentsJson = "{}" - }; - var root = TryParseArgumentsObject(effectiveArgs.ArgumentsJson); - var domain = ResolveAutonomyDomain(root, effectiveArgs); - return new ToolPolicyDecision - { - Domain = domain, - DomainId = domain?.ToString() ?? Manifest.AutonomyDomainId, - Risk = MapDomainToRisk(domain, ToolKind), - RequiresApproval = Manifest.RequiresApproval - }; - } - - protected static JObject? TryParseArgumentsObject(string? argumentsJson) - { - if (string.IsNullOrWhiteSpace(argumentsJson)) return null; - try - { - return JToken.Parse(argumentsJson!) as JObject; - } - catch - { - return null; - } - } - - private static RiskLevel MapDomainToRisk(AutonomyDomain? domain, ToolKind kind) - { - if (!domain.HasValue) - { - return kind == ToolKind.Query ? RiskLevel.Low : RiskLevel.Medium; - } - - return domain.Value switch - { - AutonomyDomain.EmergencySurvival => RiskLevel.Low, - AutonomyDomain.ResourceMarking => RiskLevel.Low, - AutonomyDomain.WorktableBills => RiskLevel.Medium, - AutonomyDomain.BlueprintPlacement => RiskLevel.Medium, - AutonomyDomain.WorkPriorityModification => RiskLevel.Medium, - AutonomyDomain.HighRiskOperations => RiskLevel.High, - _ => RiskLevel.Medium - }; - } - - protected virtual IToolHandler? FindTool(string toolId) => RimMindAPI.Tools.FindById(toolId); - - /// - /// Checks whether all are currently registered. - /// Composite tools can call this for early validation before execution. - /// - protected virtual bool AreRequiredToolsRegistered() - { - foreach (var toolId in RequiredToolIds) - { - if (FindTool(toolId) == null) return false; - } - return true; - } - - protected async Task ExecuteAtomicAsync( - string toolId, - string argumentsJson, - ToolCallArgs parentArgs, - CancellationToken ct) - { - var childCallId = $"{parentArgs.ToolCallId}:{toolId}"; - var handler = FindTool(toolId); - if (handler == null) - { - return ToolResult.Fail($"Required tool not registered: {toolId}", childCallId, toolId); - } - - var childArgs = new ToolCallArgs - { - ToolCallId = childCallId, - ToolName = toolId, - ArgumentsJson = argumentsJson, - PawnId = parentArgs.PawnId, - NpcId = parentArgs.NpcId, - TraceId = parentArgs.TraceId, - Ct = ct, - IsPlayerApproved = parentArgs.IsPlayerApproved - }; - - var result = await handler.ExecuteAsync(childArgs, ct); - return result.IsOk - ? result.Value with { ToolCallId = childCallId, ToolName = toolId } - : ToolResult.Fail($"[{result.Error.Code}] {result.Error.Message}", childCallId, toolId); - } - - internal protected static bool TryParsePawnIdString(string? raw, out int parsedId) - => PawnIdParser.TryParse(raw, out parsedId); - - /// - /// Checks whether trusted host code (e.g. an advisor approval card the player clicked) approved this call. - /// Approval is read only from ; LLM-supplied JSON fields such as - /// "pre_approved" / "is_approved" are deliberately ignored so a model cannot approve its own actions. - /// - public static bool IsPreApproved(ToolCallArgs args) => args != null && args.IsPlayerApproved; + public override string OwnerModId => "RimMindActions"; #if RIMMIND_ACTIONS_TESTS /// Test hook replacing the Verse-backed colonist target guard. - internal static Func>? TestColonistGuard; + internal static Func>? TestColonistGuard; #endif - /// - /// Verifies that is an active spawned player colonist (not dead, off-map, - /// kidnapped, prisoner, slave, guest or hostile) and that the autonomy domain allows the action. - /// Must be called before any atomic call that targets an LLM-supplied pawn id. - /// - protected Result GuardColonistTarget( + protected override Result GuardColonistTarget( int pawnId, - RimMind.Domain.Agent.Policies.AutonomyDomain domain, + AutonomyDomain domain, ToolCallArgs args, string argumentKey = "pawn_id") { #if RIMMIND_ACTIONS_TESTS return TestColonistGuard?.Invoke(pawnId, domain, args) ?? Result.Ok(Unit.Value); #else - var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); - if (pawn == null || !RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) - { - return Result.Err( - new RimMindError( - RimMindErrorCode.MechanismInvalidAction, - $"{argumentKey} {pawnId} is not an active spawned colonist") - { - TraceId = args.TraceId - }); - } - return CheckPermission(pawn, domain, args); + return base.GuardColonistTarget(pawnId, domain, args, argumentKey); #endif } - /// - /// Checks autonomy permissions against the colonist and autonomy domain, safely honoring pre-approvals. - /// - protected Result CheckPermission(Verse.Pawn? pawn, RimMind.Domain.Agent.Policies.AutonomyDomain domain, ToolCallArgs args) + protected override Result CheckPermission( + Verse.Pawn? pawn, + AutonomyDomain domain, + ToolCallArgs? args) { #if RIMMIND_ACTIONS_TESTS return Result.Ok(Unit.Value); @@ -223,133 +49,16 @@ protected Result CheckPermission(Verse.Pawn? pawn, RimMind.D #endif } - /// - /// Tries to read a typed argument from the composite tool's JSON arguments. - /// Returns false on missing key, null token, or conversion failure. - /// - internal protected static bool TryGetArgument(string argumentsJson, string key, out T value) - { - value = default!; - if (argumentsJson == null) return false; - try - { - var token = JObject.Parse(argumentsJson)[key]; - if (token == null || token.Type == JTokenType.Null) - { - return false; - } - if (typeof(T) == typeof(int) && token.Type == JTokenType.String) - { - if (PawnIdParser.TryParse(token.ToString(), out int parsedInt)) - { - value = (T)(object)parsedInt; - return true; - } - return false; - } - var converted = token.Value(); - if (converted == null) - { - return false; - } - value = converted; - return true; - } - catch (JsonException) - { - return false; - } - catch (FormatException) - { - return false; - } - catch (OverflowException) - { - return false; - } - catch (InvalidCastException) - { - return false; - } - catch (ArgumentException) - { - return false; - } - } + internal static JObject? ParseArgumentsObject(string? argumentsJson) + => TryParseArgumentsObject(argumentsJson); - /// - /// Tries to read a typed argument, returning a with - /// on failure. DRYs the common - /// validate-or-return-error pattern used by composite tools. - /// - protected static Result TryGetArgumentOrError( - string argumentsJson, string key, string? traceId) - { - if (TryGetArgument(argumentsJson, key, out T value)) - { - return Result.Ok(value); - } - return Result.Err( - new RimMindError(RimMindErrorCode.MechanismInvalidAction, $"Missing or invalid {key}") - { - TraceId = traceId - }); - } + internal static bool TryReadArgument(JObject? root, string key, out T value) + => TryGetArgument(root, key, out value); - protected static Result TryGetPawnIdOrError( - ToolCallArgs args, string key = "pawn_id") - { - int contextFallbackId = (args.PawnId.HasValue && args.PawnId.Value > 0) - ? args.PawnId.Value - : (PawnIdParser.TryParse(args.NpcId, out int parsedNpcId) && parsedNpcId > 0 ? parsedNpcId : 0); + internal static bool TryReadArgument(string? argumentsJson, string key, out T value) + => TryGetArgument(argumentsJson, key, out value); - if (TryGetArgument(args.ArgumentsJson, key, out int id) && id > 0) - { - return Result.Ok(id); - } - if (key != "pawn_id" && TryGetArgument(args.ArgumentsJson, "pawn_id", out int fallbackId) && fallbackId > 0) - { - return Result.Ok(fallbackId); - } - if (contextFallbackId > 0) - { - return Result.Ok(contextFallbackId); - } - return Result.Err( - new RimMindError(RimMindErrorCode.MechanismInvalidAction, $"Missing or invalid {key}") - { - TraceId = args.TraceId - }); - } - - /// - /// Builds a compact JSON argument payload for a child atomic tool call. - /// - protected static string BuildArgumentsJson(params (string Key, object? Value)[] pairs) - { - var obj = new JObject(); - foreach (var (key, val) in pairs) - { - obj[key] = val == null ? JValue.CreateNull() : JToken.FromObject(val); - } - return obj.ToString(Formatting.None); - } - - /// - /// Builds the standard per-step summary JSON: each step gets {"ok":bool,"content":string}. - /// - protected static string BuildStepSummary(params (string Name, ToolResult Result)[] steps) - { - var obj = new JObject(); - foreach (var (name, result) in steps) - { - obj[name] = new JObject - { - ["ok"] = !result.IsError, - ["content"] = result.Content - }; - } - return obj.ToString(Formatting.None); - } + internal static bool TryParsePawnId(string? raw, out int parsedId) + => TryParsePawnIdString(raw, out parsedId); } } diff --git a/Source/Actions/ConstructionIntentChainer.cs b/Source/Actions/ConstructionIntentChainer.cs new file mode 100644 index 0000000..124a591 --- /dev/null +++ b/Source/Actions/ConstructionIntentChainer.cs @@ -0,0 +1,195 @@ +#if !RIMMIND_ACTIONS_TESTS +using System; +using System.Collections.Generic; +using System.Linq; +using RimMind.Presentation.Api; +using RimWorld; +using Verse; +using Verse.AI; + +namespace RimMind.Actions.Actions +{ + /// + /// Shared construction intent-lease chainer and RimWorld ThingDef/StuffDef lookup helper + /// used by both and . + /// Respects player work priorities (never calls workSettings.SetPriority). + /// + internal static class ConstructionIntentChainer + { + public static ThingDef? ResolveThingDef(string? rawName) + { + if (string.IsNullOrWhiteSpace(rawName)) + return null; + + string trimmed = rawName!.Trim(); + var exact = DefDatabase.GetNamedSilentFail(trimmed); + if (exact != null) + return exact; + + return DefDatabase.AllDefsListForReading + .FirstOrDefault(d => d != null + && (string.Equals(d.defName, trimmed, StringComparison.OrdinalIgnoreCase) + || string.Equals(d.label, trimmed, StringComparison.OrdinalIgnoreCase))); + } + + public static ThingDef? ResolveStuffForBuilding(ThingDef buildingDef, string? requestedStuffName, Map map) + { + if (buildingDef == null || !buildingDef.MadeFromStuff) + return null; + + ThingDef? selectedStuff = ResolveThingDef(requestedStuffName); + if (selectedStuff != null && !GenStuff.AllowedStuffsFor(buildingDef).Contains(selectedStuff)) + { + selectedStuff = null; + } + + if (selectedStuff != null) + return selectedStuff; + + var validStuffs = GenStuff.AllowedStuffsFor(buildingDef).ToList(); + selectedStuff = validStuffs + .OrderByDescending(s => MapResourceCounter.GetAvailableCount(map, s)) + .FirstOrDefault(); + + if (selectedStuff == null || MapResourceCounter.GetAvailableCount(map, selectedStuff) <= 0) + { + selectedStuff = GenStuff.DefaultStuffFor(buildingDef) ?? ThingDefOf.WoodLog ?? ThingDefOf.Steel; + } + + return selectedStuff; + } + + public static bool TryChainSingleBlueprint( + Pawn? builderPawn, + Map? map, + Blueprint_Build? blueprint, + IntVec3 targetCell, + string intentId, + int durationTicks = 2500, + float priority = 7.8f) + { + if (builderPawn == null || map == null || blueprint == null) + return false; + + var blueprints = new List { blueprint }; + var targetCells = new List { targetCell }; + return TryChainProject(builderPawn, map, blueprints, targetCells, intentId, durationTicks, priority); + } + + public static bool TryChainProject( + Pawn? builderPawn, + Map? map, + IReadOnlyList blueprints, + IReadOnlyList targetCells, + string intentId, + int durationTicks = 5000, + float priority = 7.8f) + { + if (builderPawn == null || map == null || blueprints == null || blueprints.Count == 0) + return false; + + Blueprint firstTarget = blueprints[0]; + int startTick = Find.TickManager?.TicksGame ?? 0; + + return RimMindAPI.Agent.StartIntentSession( + pawn: builderPawn, + intentId: intentId, + startTick: startTick, + durationTicks: durationTicks, + priority: priority, + target: firstTarget, + jobProvider: p => IssueConstructionSubJob(p, map, blueprints, targetCells), + completionPredicate: _ => IsProjectCompleted(map, blueprints, targetCells)); + } + + public static Job? IssueConstructionSubJob( + Pawn? pawn, + Map? map, + IReadOnlyList blueprints, + IReadOnlyList targetCells) + { + if (pawn == null || map == null) + return null; + + // Respect the player's work tab: never rewrite priorities. + if (pawn.WorkTypeIsDisabled(WorkTypeDefOf.Construction) + || (pawn.workSettings != null && !pawn.workSettings.WorkIsActive(WorkTypeDefOf.Construction))) + { + return null; + } + + try + { + var deliverBpGiver = DefDatabase.GetNamedSilentFail("ConstructDeliverResourcesToBlueprints")?.Worker as WorkGiver_Scanner + ?? new WorkGiver_ConstructDeliverResourcesToBlueprints(); + var deliverFrameGiver = DefDatabase.GetNamedSilentFail("ConstructDeliverResourcesToFrames")?.Worker as WorkGiver_Scanner + ?? new WorkGiver_ConstructDeliverResourcesToFrames(); + var finishGiver = DefDatabase.GetNamedSilentFail("ConstructFinishFrames")?.Worker as WorkGiver_Scanner + ?? new WorkGiver_ConstructFinishFrames(); + + for (int i = 0; i < blueprints.Count; i++) + { + var bp = blueprints[i]; + if (bp == null || bp.Destroyed || !bp.Spawned) continue; + if (!pawn.CanReserveAndReach(bp, PathEndMode.Touch, Danger.Some)) continue; + + var haulJob = deliverBpGiver.JobOnThing(pawn, bp, true); + if (haulJob != null) return haulJob; + + var finishBpJob = finishGiver.JobOnThing(pawn, bp, true); + if (finishBpJob != null) return finishBpJob; + } + + for (int i = 0; i < targetCells.Count; i++) + { + var cell = targetCells[i]; + if (!cell.IsValid || !cell.InBounds(map)) continue; + + var frame = cell.GetThingList(map).OfType().FirstOrDefault(f => !f.Destroyed && f.Spawned); + if (frame == null || !pawn.CanReserveAndReach(frame, PathEndMode.Touch, Danger.Some)) continue; + + var deliverJob = deliverFrameGiver.JobOnThing(pawn, frame, true); + if (deliverJob != null) return deliverJob; + + var finishJob = finishGiver.JobOnThing(pawn, frame, true); + if (finishJob != null) return finishJob; + } + } + catch + { + return null; + } + + return null; + } + + private static bool IsProjectCompleted( + Map? map, + IReadOnlyList blueprints, + IReadOnlyList targetCells) + { + if (map == null) + return true; + + for (int i = 0; i < blueprints.Count; i++) + { + var bp = blueprints[i]; + if (bp != null && !bp.Destroyed && bp.Spawned) + return false; + } + + for (int i = 0; i < targetCells.Count; i++) + { + var cell = targetCells[i]; + if (cell.IsValid && cell.InBounds(map) + && cell.GetThingList(map).OfType().Any(f => !f.Destroyed && f.Spawned)) + { + return false; + } + } + + return true; + } + } +} +#endif diff --git a/Source/Actions/DesignateResourcesCompositeTool.cs b/Source/Actions/DesignateResourcesCompositeTool.cs index 5276384..429165a 100644 --- a/Source/Actions/DesignateResourcesCompositeTool.cs +++ b/Source/Actions/DesignateResourcesCompositeTool.cs @@ -6,7 +6,6 @@ using RimMind.Actions.Policies; using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Agent.Policies; -using RimMind.Domain.Common; using RimMind.Domain.ValueObjects; #if !RIMMIND_ACTIONS_TESTS using RimWorld; @@ -38,6 +37,7 @@ public sealed class DesignateResourcesCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.ResourceMarking; + protected override ToolScope? ToolScopes => ToolScope.ColonyManage; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => false; protected override string? DisplayName => "Designate Resources"; @@ -57,7 +57,8 @@ public override Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - if (!TryGetArgument(args.ArgumentsJson, "designation_type", out var designationTypeStr) + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + if (!TryGetArgument(argsRoot, "designation_type", out var designationTypeStr) || string.IsNullOrWhiteSpace(designationTypeStr)) { return Task.FromResult(Result.Err( @@ -65,9 +66,9 @@ public override Task> ExecuteAsync( } #if RIMMIND_ACTIONS_TESTS - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.ResourceMarking; - if (TryGetArgument(args.ArgumentsJson, "pawn_id", out int testPawnId) && testPawnId > 0) + if (TryGetArgument(argsRoot, "pawn_id", out int testPawnId) && testPawnId > 0) { var guard = GuardColonistTarget(testPawnId, domain, args); if (guard.IsErr) @@ -78,7 +79,7 @@ public override Task> ExecuteAsync( return Task.FromResult(Result.Ok( ToolResult.Ok($"Designated {designationTypeStr}", args.ToolCallId, Id))); #else - var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true); + var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true, parsedArgs: argsRoot); if (actorResolution.Error != null) { return Task.FromResult(Result.Err( @@ -95,7 +96,7 @@ public override Task> ExecuteAsync( // 1. Resolve Colonist Pawn and Permission Check Pawn? pawn = actorResolution.Pawn; - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.ResourceMarking; var permCheck = ActionPermissionGuard.CheckPermission(pawn, Id, domain, args); if (!permCheck.IsOk) @@ -103,25 +104,24 @@ public override Task> ExecuteAsync( return Task.FromResult(Result.Err(permCheck.Error)); } - // 2. Resolve Center Cell + // 2. Resolve Center Cell, Radius, Count Limit, and Filter IntVec3 centerCell = pawn?.Position ?? map.Center; - // 3. Resolve Radius and Count Limit - TryGetArgument(args.ArgumentsJson, "radius", out var radius); + TryGetArgument(argsRoot, "radius", out var radius); if (radius <= 0) radius = 60; - radius = Math.Clamp(radius, 5, 120); + radius = Math.Max(5, Math.Min(120, radius)); - TryGetArgument(args.ArgumentsJson, "max_count", out var maxCount); + TryGetArgument(argsRoot, "max_count", out var maxCount); if (maxCount <= 0) maxCount = 15; - maxCount = Math.Clamp(maxCount, 1, 50); + maxCount = Math.Max(1, Math.Min(50, maxCount)); - TryGetArgument(args.ArgumentsJson, "target_name", out var targetNameFilter); + TryGetArgument(argsRoot, "target_name", out var targetNameFilter); if (string.IsNullOrWhiteSpace(targetNameFilter)) { - TryGetArgument(args.ArgumentsJson, "target", out targetNameFilter); + TryGetArgument(argsRoot, "target", out targetNameFilter); } targetNameFilter = targetNameFilter?.Trim(); - string rawTarget = targetNameFilter ?? ""; + string rawTarget = targetNameFilter ?? string.Empty; bool targetImpliesTrees = rawTarget.IndexOf("tree", StringComparison.OrdinalIgnoreCase) >= 0 || rawTarget.IndexOf("wood", StringComparison.OrdinalIgnoreCase) >= 0 || @@ -133,107 +133,70 @@ public override Task> ExecuteAsync( targetNameFilter = null; } - // 4. Resolve DesignationDef and Filter + // 3. Resolve DesignationDef and Base Eligibility Predicate (without targetNameFilter) string mode = designationTypeStr.Trim().ToLowerInvariant(); DesignationDef desDef; - Func candidatePredicate; + bool isMineMode = false; + bool isHarvestNonTreeMode = false; + Func basePredicate; if (mode.Contains("harvest") && !targetImpliesTrees) { desDef = DesignationDefOf.HarvestPlant; - candidatePredicate = t => - { - if (t is not Plant plant) return false; - if (plant.def.plant == null || plant.def.plant.IsTree || !plant.def.plant.Harvestable) return false; - if (!plant.HarvestableNow) return false; - if (map.designationManager.DesignationOn(plant, desDef) != null) return false; - if (!string.IsNullOrWhiteSpace(targetNameFilter)) - { - if ((plant.def?.defName == null || !plant.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) - && (plant.Label == null || !plant.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase))) - return false; - } - return true; - }; + isHarvestNonTreeMode = true; + basePredicate = t => + t is Plant plant + && plant.def?.plant != null + && !plant.def.plant.IsTree + && plant.def.plant.Harvestable + && plant.HarvestableNow + && map.designationManager.DesignationOn(plant, desDef) == null; } else if (mode.Contains("chop") || mode.Contains("wood") || mode.Contains("tree") || targetImpliesTrees) { - // In RimWorld, mature trees for wood harvest are designated with HarvestPlant desDef = DesignationDefOf.HarvestPlant; - candidatePredicate = t => - { - if (t is not Plant plant) return false; - if (plant.def.plant == null || !plant.def.plant.IsTree) return false; - if (!plant.HarvestableNow) return false; - if (map.designationManager.DesignationOn(plant, desDef) != null) return false; - if (!string.IsNullOrWhiteSpace(targetNameFilter)) - { - if ((plant.def?.defName == null || !plant.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) - && (plant.Label == null || !plant.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase))) - return false; - } - return true; - }; + basePredicate = t => + t is Plant plant + && plant.def?.plant != null + && plant.def.plant.IsTree + && plant.HarvestableNow + && map.designationManager.DesignationOn(plant, desDef) == null; } else if (mode.Contains("cut") || mode.Contains("clear")) { desDef = DesignationDefOf.CutPlant; - candidatePredicate = t => - { - if (t is not Plant plant) return false; - // Never cut the colony's own crops (growing zones or hydroponics/plant pots). - if (map.zoneManager?.ZoneAt(plant.Position) is Zone_Growing) return false; - if (plant.Position.GetEdifice(map) is Building_PlantGrower) return false; - if (map.designationManager.DesignationOn(plant, desDef) != null) return false; - if (!string.IsNullOrWhiteSpace(targetNameFilter)) - { - if ((plant.def?.defName == null || !plant.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) - && (plant.Label == null || !plant.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase))) - return false; - } - return true; - }; + basePredicate = t => + t is Plant plant + && !(map.zoneManager?.ZoneAt(plant.Position) is Zone_Growing) + && !(plant.Position.GetEdifice(map) is Building_PlantGrower) + && map.designationManager.DesignationOn(plant, desDef) == null; } else if (mode.Contains("mine") || mode.Contains("ore") || mode.Contains("mineral")) { desDef = DesignationDefOf.Mine; - candidatePredicate = t => - { - if (t.def.mineable != true && t is not Mineable) return false; - // Without an explicit target, only mine resource rock (ores), never plain stone that may be a base wall. - if (string.IsNullOrWhiteSpace(targetNameFilter) && t.def.building?.isResourceRock != true) return false; - if ((desDef.targetType == TargetType.Cell ? map.designationManager.DesignationAt(t.Position, desDef) : map.designationManager.DesignationOn(t, desDef)) != null) return false; - if (!string.IsNullOrWhiteSpace(targetNameFilter)) - { - if ((t.def?.defName == null || !t.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) - && (t.Label == null || !t.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase))) - return false; - } - return true; - }; + isMineMode = true; + basePredicate = t => + (t.def?.mineable == true || t is Mineable) + && (desDef.targetType == TargetType.Cell + ? map.designationManager.DesignationAt(t.Position, desDef) + : map.designationManager.DesignationOn(t, desDef)) == null; } else if (mode.Contains("hunt") || mode.Contains("meat") || mode.Contains("animal")) { desDef = DesignationDefOf.Hunt; - candidatePredicate = t => - { - if (t is not Pawn animal || animal.Dead || animal.Downed) return false; - if (animal.RaceProps == null || !animal.RaceProps.Animal || animal.RaceProps.Humanlike) return false; - // Only wild animals: never colony pets/livestock or other factions' animals. - if (animal.Faction != null) return false; - // Safety: skip predators, manhunters, and animals likely to retaliate as manhunters. - if (animal.RaceProps.predator || animal.InAggroMentalState) return false; - // Hunting large or vengeful animals with starter weapons killed colonists in live playthroughs. - if (animal.RaceProps.manhunterOnDamageChance > 0.1f || animal.RaceProps.baseBodySize > 1.5f) return false; - if (map.designationManager.DesignationOn(animal, desDef) != null) return false; - if (!string.IsNullOrWhiteSpace(targetNameFilter)) - { - if ((animal.def?.defName == null || !animal.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) - && (animal.Label == null || !animal.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase))) - return false; - } - return true; - }; + basePredicate = t => + t is Pawn animal + && !animal.Dead + && !animal.Downed + && animal.RaceProps != null + && animal.RaceProps.Animal + && !animal.RaceProps.Humanlike + && animal.Faction == null + && !animal.RaceProps.predator + && !animal.InAggroMentalState + && animal.RaceProps.manhunterOnDamageChance <= 0.1f + && animal.RaceProps.baseBodySize <= 1.5f + && map.designationManager.DesignationOn(animal, desDef) == null; } else { @@ -241,69 +204,72 @@ public override Task> ExecuteAsync( RimMindErrors.InvalidAction(Id, $"Unknown designation type '{designationTypeStr}'. Supported: 'Harvest', 'ChopWood', 'Mine', 'Hunt'."))); } - // 5. Query Candidates within Radius (with automatic expansion up to map-wide 120 tiles if none within initial radius) - var candidates = new List(); - var allSpawnedThings = map.listerThings?.AllThings ?? new List(); - - foreach (var thing in allSpawnedThings) - { - if (thing == null || !thing.Spawned || thing.Destroyed) continue; - if (thing.Position.Fogged(map)) continue; - if (!thing.Position.InHorDistOf(centerCell, radius)) continue; - - if (candidatePredicate(thing)) - { - candidates.Add(thing); - } - } - - if (candidates.Count == 0 && radius < 120) + // 4. Single-pass bucketed scan over map.listerThings.AllThings + // Bucket 1: within requested radius + matches targetNameFilter + // Bucket 2: within expanded 120-tile radius + matches targetNameFilter + // Bucket 3: within expanded 120-tile radius + unfiltered fallback (when targetNameFilter matched nothing) + // Bucket 4: winter harvest fallback (mature trees when 0 wild edible plants exist) + var inRadiusFiltered = new List(); + var mapWideFiltered = new List(); + var mapWideUnfiltered = new List(); + var winterTreeFallback = new List(); + + bool hasFilter = !string.IsNullOrWhiteSpace(targetNameFilter); + int expandedRadius = Math.Max(radius, 120); + var allSpawnedThings = map.listerThings?.AllThings; + + if (allSpawnedThings != null) { - foreach (var thing in allSpawnedThings) + for (int i = 0; i < allSpawnedThings.Count; i++) { + var thing = allSpawnedThings[i]; if (thing == null || !thing.Spawned || thing.Destroyed) continue; if (thing.Position.Fogged(map)) continue; - if (!thing.Position.InHorDistOf(centerCell, 120)) continue; - if (candidatePredicate(thing)) + bool inExpanded = thing.Position.InHorDistOf(centerCell, expandedRadius); + if (inExpanded && basePredicate(thing)) { - candidates.Add(thing); - } - } - } - - // Fallback: if LLM provided a descriptive target_name filter (e.g. "berries_and_edible_wild_plants" or "成熟作物") - // that matched 0 exact ThingDefs, clear the filter and scan for any valid target of the requested designation type. - if (candidates.Count == 0 && targetNameFilter != null) - { - targetNameFilter = null; - foreach (var thing in allSpawnedThings) - { - if (thing == null || !thing.Spawned || thing.Destroyed) continue; - if (thing.Position.Fogged(map)) continue; - if (!thing.Position.InHorDistOf(centerCell, Math.Max(radius, 120))) continue; + bool inPrimary = thing.Position.InHorDistOf(centerCell, radius); + bool unfilteredMineAllowed = !isMineMode || thing.def?.building?.isResourceRock == true; - if (candidatePredicate(thing)) + if (!hasFilter) + { + if (unfilteredMineAllowed) + { + if (inPrimary) inRadiusFiltered.Add(thing); + else mapWideFiltered.Add(thing); + } + } + else + { + if (MatchesTargetFilter(thing, targetNameFilter)) + { + if (inPrimary) inRadiusFiltered.Add(thing); + else mapWideFiltered.Add(thing); + } + else if (unfilteredMineAllowed) + { + mapWideUnfiltered.Add(thing); + } + } + } + else if (isHarvestNonTreeMode + && thing is Plant tree + && tree.def?.plant != null + && tree.def.plant.IsTree + && tree.HarvestableNow + && map.designationManager.DesignationOn(tree, DesignationDefOf.HarvestPlant) == null) { - candidates.Add(thing); + winterTreeFallback.Add(tree); } } } - // Seasonal fallback: in winter when 0 edible wild plants/crops exist on the map for 'harvest', - // check if mature trees can be harvested for essential survival wood/fuel. - if (candidates.Count == 0 && mode.Contains("harvest")) - { - foreach (var thing in allSpawnedThings) - { - if (thing is not Plant tree || !tree.Spawned || tree.Destroyed) continue; - if (tree.Position.Fogged(map)) continue; - if (tree.def?.plant == null || !tree.def.plant.IsTree) continue; - if (!tree.HarvestableNow) continue; - if (map.designationManager.DesignationOn(tree, DesignationDefOf.HarvestPlant) != null) continue; - candidates.Add(tree); - } - } + List candidates = inRadiusFiltered.Count > 0 ? inRadiusFiltered + : mapWideFiltered.Count > 0 ? mapWideFiltered + : (hasFilter && mapWideUnfiltered.Count > 0) ? mapWideUnfiltered + : (isHarvestNonTreeMode && winterTreeFallback.Count > 0) ? winterTreeFallback + : inRadiusFiltered; // Note: this tool intentionally never unforbids items. Forbid state is a player decision. if (candidates.Count == 0) @@ -335,12 +301,11 @@ public override Task> ExecuteAsync( centerCell.z)))); } - // 6. Sort by Edible Food Priority & Distance and Apply Designation - bool prioritizeEdible = mode.Contains("harvest") && !targetImpliesTrees; + // 5. Sort by Edible Food Priority & Distance and Apply Designation var selected = candidates .OrderByDescending(t => { - if (!prioritizeEdible || t is not Plant p) return 0; + if (!isHarvestNonTreeMode || t is not Plant p) return 0; var hDef = p.def?.plant?.harvestedThingDef; return (hDef != null && hDef.IsNutritionGivingIngestible && hDef.ingestible?.HumanEdible == true) ? 1 : 0; }) @@ -351,49 +316,29 @@ public override Task> ExecuteAsync( int addedCount = 0; foreach (var target in selected) { - map.designationManager.AddDesignation(desDef.targetType == TargetType.Cell ? new Designation(target.Position, desDef) : new Designation(target, desDef)); + map.designationManager.AddDesignation(desDef.targetType == TargetType.Cell + ? new Designation(target.Position, desDef) + : new Designation(target, desDef)); addedCount++; } - if (desDef == DesignationDefOf.Hunt) - { - // Hunting only happens if someone has the Hunting work type enabled. - var hunters = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map); - for (int i = 0; i < hunters.Count; i++) - { - var c = hunters[i]; - if (c?.workSettings != null && c.workSettings.EverWork && !c.WorkTypeIsDisabled(WorkTypeDefOf.Hunting)) - { - c.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); - if (c.workSettings.GetPriority(WorkTypeDefOf.Hunting) == 0 || c.workSettings.GetPriority(WorkTypeDefOf.Hunting) > 2) - { - c.workSettings.SetPriority(WorkTypeDefOf.Hunting, 2); - } - } - } - } - - if (desDef == DesignationDefOf.HarvestPlant || desDef == DesignationDefOf.CutPlant) + // Respect player work tab: NEVER call workSettings.SetPriority. + // If the acting colonist is already assigned to PlantCutting, immediately dispatch the first edible harvest job. + if (isHarvestNonTreeMode + && pawn != null + && !pawn.Dead + && !pawn.Downed + && !pawn.Drafted + && !pawn.WorkTypeIsDisabled(WorkTypeDefOf.PlantCutting) + && (pawn.workSettings == null || pawn.workSettings.WorkIsActive(WorkTypeDefOf.PlantCutting)) + && selected.Count > 0 + && selected[0] is Plant firstPlant + && firstPlant.HarvestableNow) { - var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map); - for (int i = 0; i < colonists.Count; i++) - { - var c = colonists[i]; - if (c?.workSettings != null && c.workSettings.EverWork && !c.WorkTypeIsDisabled(WorkTypeDefOf.PlantCutting)) - { - c.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); - c.workSettings.SetPriority(WorkTypeDefOf.PlantCutting, 1); - } - } - - if (prioritizeEdible && pawn != null && !pawn.Dead && !pawn.Downed && !pawn.Drafted - && !pawn.WorkTagIsDisabled(WorkTags.PlantWork) && selected.Count > 0 && selected[0] is Plant firstPlant && firstPlant.HarvestableNow) - { - var plantsCutGiver = DefDatabase.GetNamedSilentFail("PlantsCut"); - var harvestJob = JobMaker.MakeJob(JobDefOf.HarvestDesignated, new LocalTargetInfo(firstPlant)); - harvestJob.workGiverDef = plantsCutGiver; - pawn.jobs?.StartJob(harvestJob, Verse.AI.JobCondition.InterruptForced); - } + var plantsCutGiver = DefDatabase.GetNamedSilentFail("PlantsCut"); + var harvestJob = JobMaker.MakeJob(JobDefOf.HarvestDesignated, new LocalTargetInfo(firstPlant)); + harvestJob.workGiverDef = plantsCutGiver; + pawn.jobs?.StartJob(harvestJob, Verse.AI.JobCondition.InterruptForced); } string targetSample = string.Join(", ", selected.Take(3).Select(t => t.LabelShort)); @@ -413,6 +358,19 @@ public override Task> ExecuteAsync( } #if !RIMMIND_ACTIONS_TESTS + private static bool MatchesTargetFilter(Thing thing, string? targetNameFilter) + { + if (string.IsNullOrWhiteSpace(targetNameFilter)) + return true; + + string filter = targetNameFilter!; + bool matchesDef = thing.def?.defName != null + && thing.def.defName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0; + bool matchesLabel = thing.Label != null + && thing.Label.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0; + return matchesDef || matchesLabel; + } + private static bool IsGenericResourceFilter(string? filter) { if (string.IsNullOrWhiteSpace(filter)) return true; diff --git a/Source/Actions/EatAndRecreationCompositeTool.cs b/Source/Actions/EatAndRecreationCompositeTool.cs index 562dded..5af6632 100644 --- a/Source/Actions/EatAndRecreationCompositeTool.cs +++ b/Source/Actions/EatAndRecreationCompositeTool.cs @@ -36,6 +36,7 @@ public sealed class EatAndRecreationCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.EmergencySurvival; + protected override ToolScope? ToolScopes => ToolScope.ColonistSelf; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => true; protected override string? DisplayName => "Eat & Recreation"; @@ -56,14 +57,15 @@ public override async Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - var pawnIdResult = TryGetPawnIdOrError(args, "pawn_id"); + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + var pawnIdResult = TryGetPawnIdOrError(argsRoot, args, "pawn_id"); if (pawnIdResult.IsErr) { return Result.Err(pawnIdResult.Error); } int pawnId = pawnIdResult.Value; - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.EmergencySurvival; var guard = GuardColonistTarget(pawnId, domain, args); if (guard.IsErr) @@ -77,7 +79,7 @@ public override async Task> ExecuteAsync( ct.ThrowIfCancellationRequested(); // 2. Direct pawn to eat food if hunger-driven, otherwise rest and regenerate vital energies - TryGetArgument(args.ArgumentsJson, "reason", out var reasonText); + TryGetArgument(argsRoot, "reason", out var reasonText); bool wantsFood = !string.IsNullOrWhiteSpace(reasonText) && (reasonText.IndexOf("eat", System.StringComparison.OrdinalIgnoreCase) >= 0 || reasonText.IndexOf("food", System.StringComparison.OrdinalIgnoreCase) >= 0 || diff --git a/Source/Actions/EmergencyFleeCompositeTool.cs b/Source/Actions/EmergencyFleeCompositeTool.cs index 55ac022..3af0c6e 100644 --- a/Source/Actions/EmergencyFleeCompositeTool.cs +++ b/Source/Actions/EmergencyFleeCompositeTool.cs @@ -34,6 +34,7 @@ public sealed class EmergencyFleeCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.EmergencySurvival; + protected override ToolScope? ToolScopes => ToolScope.ColonistSelf; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => true; protected override string? DisplayName => "Emergency Flee"; @@ -54,14 +55,15 @@ public override async Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - var pawnIdResult = TryGetPawnIdOrError(args, "pawn_id"); + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + var pawnIdResult = TryGetPawnIdOrError(argsRoot, args, "pawn_id"); if (pawnIdResult.IsErr) { return Result.Err(pawnIdResult.Error); } int pawnId = pawnIdResult.Value; - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.EmergencySurvival; var guard = GuardColonistTarget(pawnId, domain, args); if (guard.IsErr) diff --git a/Source/Actions/ManageEquipmentCompositeTool.cs b/Source/Actions/ManageEquipmentCompositeTool.cs index 7ee9800..0152b95 100644 --- a/Source/Actions/ManageEquipmentCompositeTool.cs +++ b/Source/Actions/ManageEquipmentCompositeTool.cs @@ -39,6 +39,7 @@ public sealed class ManageEquipmentCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.EmergencySurvival; + protected override ToolScope? ToolScopes => ToolScope.ColonistSelf; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => true; protected override string? DisplayName => "Manage Equipment"; @@ -58,13 +59,14 @@ public override Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); #if RIMMIND_ACTIONS_TESTS - var pawnIdResult = TryGetPawnIdOrError(args, "pawn_id"); + var pawnIdResult = TryGetPawnIdOrError(argsRoot, args, "pawn_id"); if (pawnIdResult.IsErr) { return Task.FromResult(Result.Err(pawnIdResult.Error)); } - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.EmergencySurvival; var guard = GuardColonistTarget(pawnIdResult.Value, domain, args); if (guard.IsErr) @@ -73,7 +75,7 @@ public override Task> ExecuteAsync( } return Task.FromResult(Result.Ok(ToolResult.Ok("ok", args.ToolCallId, Id))); #else - var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true); + var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true, parsedArgs: argsRoot); if (actorResolution.Error != null) { return Task.FromResult(Result.Err( @@ -96,7 +98,7 @@ public override Task> ExecuteAsync( RimMindErrors.InvalidAction(Id, "Colonist pawn not found or invalid."))); } - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.EmergencySurvival; var permCheck = ActionPermissionGuard.CheckPermission(pawn, Id, domain, args); if (!permCheck.IsOk) @@ -116,10 +118,10 @@ public override Task> ExecuteAsync( } // 2. Evaluate Purpose and Conditions - TryGetArgument(args.ArgumentsJson, "purpose", out var purposeStr); + TryGetArgument(argsRoot, "purpose", out var purposeStr); if (string.IsNullOrWhiteSpace(purposeStr)) purposeStr = "Auto"; - TryGetArgument(args.ArgumentsJson, "target_apparel_def", out var targetApparelDefName); + TryGetArgument(argsRoot, "target_apparel_def", out var targetApparelDefName); float ambientTemp = pawn.Position.GetTemperature(map); float minComfy = pawn.GetStatValue(StatDefOf.ComfyTemperatureMin); diff --git a/Source/Actions/ManageZoneCompositeTool.cs b/Source/Actions/ManageZoneCompositeTool.cs index 13ec08a..db8d656 100644 --- a/Source/Actions/ManageZoneCompositeTool.cs +++ b/Source/Actions/ManageZoneCompositeTool.cs @@ -37,6 +37,7 @@ public sealed class ManageZoneCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.ResourceMarking; + protected override ToolScope? ToolScopes => ToolScope.ColonyManage; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => false; protected override string? DisplayName => "Manage Zone"; @@ -56,7 +57,8 @@ public override Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - if (!TryGetArgument(args.ArgumentsJson, "zone_type", out var zoneTypeStr) + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + if (!TryGetArgument(argsRoot, "zone_type", out var zoneTypeStr) || string.IsNullOrWhiteSpace(zoneTypeStr)) { return Task.FromResult(Result.Err( @@ -64,9 +66,9 @@ public override Task> ExecuteAsync( } #if RIMMIND_ACTIONS_TESTS - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.ResourceMarking; - if (TryGetArgument(args.ArgumentsJson, "pawn_id", out int testPawnId) && testPawnId > 0) + if (TryGetArgument(argsRoot, "pawn_id", out int testPawnId) && testPawnId > 0) { var guard = GuardColonistTarget(testPawnId, domain, args); if (guard.IsErr) @@ -77,7 +79,7 @@ public override Task> ExecuteAsync( return Task.FromResult(Result.Ok( ToolResult.Ok($"Zone {zoneTypeStr}", args.ToolCallId, Id))); #else - var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true); + var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true, parsedArgs: argsRoot); if (actorResolution.Error != null) { return Task.FromResult(Result.Err( @@ -94,7 +96,7 @@ public override Task> ExecuteAsync( // 1. Resolve Anchor Colonist & Autonomy Permission Guard Pawn? pawn = actorResolution.Pawn; - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.ResourceMarking; var permCheck = ActionPermissionGuard.CheckPermission(pawn, Id, domain, args); if (!permCheck.IsOk) @@ -103,13 +105,13 @@ public override Task> ExecuteAsync( } // 2. Parse Dimensions - TryGetArgument(args.ArgumentsJson, "width", out var width); + TryGetArgument(argsRoot, "width", out var width); if (width <= 0) width = 5; - width = Math.Clamp(width, 2, 15); + width = Math.Max(2, Math.Min(15, width)); - TryGetArgument(args.ArgumentsJson, "height", out var height); + TryGetArgument(argsRoot, "height", out var height); if (height <= 0) height = 5; - height = Math.Clamp(height, 2, 15); + height = Math.Max(2, Math.Min(15, height)); IntVec3 origin = (pawn != null && pawn.Position.InHorDistOf(map.Center, 28f)) ? pawn.Position : map.Center; string zoneTypeLower = zoneTypeStr.Trim().ToLowerInvariant(); @@ -138,7 +140,7 @@ public override Task> ExecuteAsync( if (isGrowing) { - TryGetArgument(args.ArgumentsJson, "crop_def", out var cropDefName); + TryGetArgument(argsRoot, "crop_def", out var cropDefName); if (string.IsNullOrWhiteSpace(cropDefName)) cropDefName = "Plant_Rice"; var trimmedCrop = cropDefName.Trim(); @@ -184,17 +186,7 @@ public override Task> ExecuteAsync( "RimMind.Actions.Zone.GrowZoneDetail", "Growing Zone (crop: {0}, cells: {1})", plantDef.label, growZone.cells.Count); - - var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map); - for (int i = 0; i < colonists.Count; i++) - { - var c = colonists[i]; - if (c?.workSettings != null && c.workSettings.EverWork && !c.WorkTypeIsDisabled(WorkTypeDefOf.Growing)) - { - c.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); - c.workSettings.SetPriority(WorkTypeDefOf.Growing, 1); - } - } + // Respect player work tab: colonists sow according to their existing Growing work priorities. } else { diff --git a/Source/Actions/PlaceBlueprintCompositeTool.cs b/Source/Actions/PlaceBlueprintCompositeTool.cs index ac6e55b..b149507 100644 --- a/Source/Actions/PlaceBlueprintCompositeTool.cs +++ b/Source/Actions/PlaceBlueprintCompositeTool.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; @@ -8,20 +7,17 @@ using RimMind.Actions.Policies; using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Agent.Policies; -using RimMind.Domain.Common; using RimMind.Domain.ValueObjects; -using RimMind.Presentation.Api; #if !RIMMIND_ACTIONS_TESTS using RimMind.Actions.Spatial; using RimWorld; -using Verse.AI; #endif using Verse; namespace RimMind.Actions.Actions { /// - /// Composite action tool that places a building blueprint with smart obstacle clearance, + /// Composite action tool that places a building blueprint with smart footprint/interaction-cell placement, /// automatic stockpile material detection, and immediate colonist construction intent chaining. /// public sealed class PlaceBlueprintCompositeTool : CompositeToolCallBase @@ -41,6 +37,7 @@ public sealed class PlaceBlueprintCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.BlueprintPlacement; + protected override ToolScope? ToolScopes => ToolScope.ColonyBuild; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => false; protected override string? DisplayName => "Place Blueprint"; @@ -57,20 +54,14 @@ public sealed class PlaceBlueprintCompositeTool : CompositeToolCallBase public override IReadOnlyList RequiredToolIds => Array.Empty(); protected override AutonomyDomain? ResolveAutonomyDomain(JObject? root, ToolCallArgs args) - { - string? buildingDefName = root?["building_def"]?.ToString(); - if (string.IsNullOrWhiteSpace(buildingDefName) && args != null) - { - TryGetArgument(args.ArgumentsJson, "building_def", out buildingDefName); - } - return AutonomyDomain.BlueprintPlacement; - } + => AutonomyDomain.BlueprintPlacement; public override Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - if (!TryGetArgument(args.ArgumentsJson, "building_def", out var buildingDefName) + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + if (!TryGetArgument(argsRoot, "building_def", out var buildingDefName) || string.IsNullOrWhiteSpace(buildingDefName)) { return Task.FromResult(Result.Err( @@ -78,9 +69,9 @@ public override Task> ExecuteAsync( } #if RIMMIND_ACTIONS_TESTS - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.BlueprintPlacement; - if (TryGetArgument(args.ArgumentsJson, "pawn_id", out int testPawnId) && testPawnId > 0) + if (TryGetArgument(argsRoot, "pawn_id", out int testPawnId) && testPawnId > 0) { var guard = GuardColonistTarget(testPawnId, domain, args); if (guard.IsErr) @@ -91,7 +82,7 @@ public override Task> ExecuteAsync( return Task.FromResult(Result.Ok( ToolResult.Ok($"Placed {buildingDefName}", args.ToolCallId, Id))); #else - var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true); + var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: true, parsedArgs: argsRoot); if (actorResolution.Error != null) { return Task.FromResult(Result.Err( @@ -106,25 +97,14 @@ public override Task> ExecuteAsync( } // 1. Resolve BuildableDef - var trimmedBuildingName = buildingDefName.Trim(); - var thingDef = DefDatabase.GetNamedSilentFail(trimmedBuildingName); - if (thingDef == null) - { - // Fallback: null-safe case-insensitive search - thingDef = DefDatabase.AllDefsListForReading - .FirstOrDefault(d => d != null - && (string.Equals(d.defName, trimmedBuildingName, StringComparison.OrdinalIgnoreCase) - || string.Equals(d.label, trimmedBuildingName, StringComparison.OrdinalIgnoreCase))); - } - + var thingDef = ConstructionIntentChainer.ResolveThingDef(buildingDefName); if (thingDef == null) { return Task.FromResult(Result.Err( RimMindErrors.InvalidDefName($"Building '{buildingDefName}' not found. Call actions_query_buildable_structures to see valid buildable defs."))); } - // The label fallback above searches every ThingDef (items, plants...): only accept player-buildable, - // research-unlocked buildings. + // Only accept player-buildable, research-unlocked buildings. if (thingDef.category != ThingCategory.Building || !thingDef.BuildableByPlayer || !thingDef.IsResearchFinished) { return Task.FromResult(Result.Err( @@ -132,50 +112,14 @@ public override Task> ExecuteAsync( } // 2. Auto-Stuff Selection (Stockpile-Aware) - ThingDef? selectedStuff = null; - TryGetArgument(args.ArgumentsJson, "stuff_def", out var stuffDefName); - if (!string.IsNullOrWhiteSpace(stuffDefName)) - { - var trimmedStuffName = stuffDefName.Trim(); - selectedStuff = DefDatabase.GetNamedSilentFail(trimmedStuffName) - ?? DefDatabase.AllDefsListForReading - .FirstOrDefault(d => d != null - && (string.Equals(d.defName, trimmedStuffName, StringComparison.OrdinalIgnoreCase) - || string.Equals(d.label, trimmedStuffName, StringComparison.OrdinalIgnoreCase))); - // Discard LLM-supplied stuff that this building cannot be made from; auto-selection below takes over. - if (selectedStuff != null && (!thingDef.MadeFromStuff || !GenStuff.AllowedStuffsFor(thingDef).Contains(selectedStuff))) - { - selectedStuff = null; - } - } - - if (thingDef.MadeFromStuff) - { - if (selectedStuff == null) - { - // Scan valid stuffs for this building and pick the one with highest available count on map - var validStuffs = GenStuff.AllowedStuffsFor(thingDef).ToList(); - selectedStuff = validStuffs - .OrderByDescending(s => ResourceSafetyGuard.GetAvailableCount(map, s)) - .FirstOrDefault(); - - if (selectedStuff == null || ResourceSafetyGuard.GetAvailableCount(map, selectedStuff) <= 0) - { - selectedStuff = GenStuff.DefaultStuffFor(thingDef) ?? ThingDefOf.WoodLog ?? ThingDefOf.Steel; - } - } - } - else - { - selectedStuff = null; - } + TryGetArgument(argsRoot, "stuff_def", out var stuffDefName); + ThingDef? selectedStuff = ConstructionIntentChainer.ResolveStuffForBuilding(thingDef, stuffDefName, map); // 3. Anchor and Placement Position Pawn? anchorPawn = actorResolution.Pawn; // Autonomy Permission & Resource Safety Guards - var autonomyDomain = AutonomyDomain.BlueprintPlacement; - var permCheck = ActionPermissionGuard.CheckPermission(anchorPawn, Id, autonomyDomain, args); + var permCheck = ActionPermissionGuard.CheckPermission(anchorPawn, Id, AutonomyDomain.BlueprintPlacement, args); if (!permCheck.IsOk) { return Task.FromResult(Result.Err(permCheck.Error)); @@ -188,7 +132,7 @@ public override Task> ExecuteAsync( } IntVec3 anchorPos = (anchorPawn != null && anchorPawn.Position.InHorDistOf(map.Center, 28f)) ? anchorPawn.Position : map.Center; - TryGetArgument(args.ArgumentsJson, "location_hint", out var locationHint); + TryGetArgument(argsRoot, "location_hint", out var locationHint); locationHint = string.IsNullOrWhiteSpace(locationHint) ? "near_base" : locationHint.ToLowerInvariant().Trim(); var rot = Rot4.North; @@ -239,32 +183,22 @@ public override Task> ExecuteAsync( RimMindErrors.Internal($"Blueprint for '{thingDef.defName}' could not be spawned at {targetCell}."))); } - // 5. Immediate Construction Chaining via Intent Lease (Shortcoming 2 Solution) - TryGetArgument(args.ArgumentsJson, "auto_construct", out var autoConstruct); - // Default to true if not explicitly set to false - if (args.ArgumentsJson == null || !args.ArgumentsJson.Contains("auto_construct")) - { - autoConstruct = true; - } + // 5. Immediate Construction Chaining via Shared ConstructionIntentChainer + bool autoConstruct = !TryGetArgument(argsRoot, "auto_construct", out var parsedAutoConstruct) || parsedAutoConstruct; bool sessionStarted = false; string builderName = "None"; if (autoConstruct && anchorPawn != null) { - int startTick = Find.TickManager?.TicksGame ?? 0; - sessionStarted = RimMindAPI.Agent.StartIntentSession( - pawn: anchorPawn, + sessionStarted = ConstructionIntentChainer.TryChainSingleBlueprint( + anchorPawn, + map, + blueprint, + targetCell, intentId: $"Construct_{thingDef.defName}", - startTick: startTick, - durationTicks: 2500, // 1 in-game hour lease - priority: 7.8f, - target: blueprint, - jobProvider: p => IssueConstructionSubJob(p, map, blueprint, targetCell), - completionPredicate: p => - map == null - || ((blueprint == null || blueprint.Destroyed || !blueprint.Spawned) - && !targetCell.GetThingList(map).OfType().Any(f => !f.Destroyed && f.Spawned))); + durationTicks: 2500, + priority: 7.8f); if (sessionStarted) { builderName = anchorPawn.Name?.ToStringShort ?? anchorPawn.Label; @@ -332,19 +266,21 @@ private static IntVec3 FindValidPlacementCell( ? new[] { Rot4.North, Rot4.East, Rot4.South, Rot4.West } : new[] { Rot4.North }; - // 1. Spatial topology + peer-furniture clustering solver (replaces random spawn-adjacent placement) + // 1. Spatial topology + peer-furniture clustering solver using real footprint & interaction cell try { ColonySpatialSnapshot snapshot = MapSpatialSnapshotBuilder.Build(map, anchor.x, anchor.z, radius: 26); bool isBed = def.thingClass != null && typeof(Building_Bed).IsAssignableFrom(def.thingClass); bool isWorkTable = def.thingClass != null && typeof(Building_WorkTable).IsAssignableFrom(def.thingClass); bool isTable = def.surfaceType == SurfaceType.Eat; + bool isJoy = def.building?.joyKind != null; bool isDefense = (def.building != null && def.building.IsTurret) || def.passability == Traversability.PassThroughOnly; - SpatialBuildingCategory category = ColonySpatialClusterSolver.ClassifyBuilding( + SpatialBuildingCategory category = SpatialBuildingClassifier.Classify( def.defName, isBed: isBed, isWorkTable: isWorkTable, isTable: isTable, + isJoy: isJoy, isDefense: isDefense); SpatialCandidateScore? bestOverall = null; @@ -352,13 +288,22 @@ private static IntVec3 FindValidPlacementCell( foreach (Rot4 candidateRot in rotations) { + CellRect occupied = GenAdj.OccupiedRect(IntVec3.Zero, candidateRot, def.Size); + IntVec3 interactionOffset = def.hasInteractionCell + ? def.interactionCellOffset.RotatedBy(candidateRot) + : IntVec3.Zero; + var req = new SpatialPlacementRequest { BuildingDefName = def.defName ?? string.Empty, Category = category, - SizeX = 1, - SizeZ = 1, - HasInteractionCell = false, + SizeX = Math.Max(1, occupied.Width), + SizeZ = Math.Max(1, occupied.Height), + FootprintMinOffsetX = occupied.minX, + FootprintMinOffsetZ = occupied.minZ, + HasInteractionCell = def.hasInteractionCell, + InteractionOffsetX = interactionOffset.x, + InteractionOffsetZ = interactionOffset.z, LocationHint = hint, AnchorX = anchor.x, AnchorZ = anchor.z @@ -437,97 +382,6 @@ private static IntVec3 FindValidPlacementCell( clusterRoomId = 0; return IntVec3.Invalid; } - - private static Job? IssueConstructionSubJob(Pawn pawn, Map map, Blueprint_Build blueprint, IntVec3 targetCell) - { - if (pawn == null || map == null || !targetCell.IsValid || !targetCell.InBounds(map)) return null; - - // Respect the player's work tab: never rewrite priorities. Pawns that cannot or are not assigned to - // construct are skipped; vanilla construction workers will still pick up the placed blueprint. - if (pawn.WorkTypeIsDisabled(WorkTypeDefOf.Construction) - || (pawn.workSettings != null && !pawn.workSettings.WorkIsActive(WorkTypeDefOf.Construction))) - { - return null; - } - - try - { - // Step 1: If blueprint is still active, try delivering resources then finishing frame - if (blueprint != null && !blueprint.Destroyed && blueprint.Spawned) - { - if (pawn.CanReserveAndReach(blueprint, PathEndMode.Touch, Danger.Some)) - { - var deliverBpGiver = DefDatabase.GetNamedSilentFail("ConstructDeliverResourcesToBlueprints")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructDeliverResourcesToBlueprints(); - var haulJob = deliverBpGiver.JobOnThing(pawn, blueprint, true); - if (haulJob != null) return haulJob; - - var finishBpGiver = DefDatabase.GetNamedSilentFail("ConstructFinishFrames")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructFinishFrames(); - var finishBpJob = finishBpGiver.JobOnThing(pawn, blueprint, true); - if (finishBpJob != null) return finishBpJob; - } - return null; - } - - // Step 2: Blueprint was replaced by a Frame at targetCell - Frame? frame = targetCell.GetThingList(map).OfType().FirstOrDefault(f => !f.Destroyed && f.Spawned); - if (frame != null && pawn.CanReserveAndReach(frame, PathEndMode.Touch, Danger.Some)) - { - var deliverFrameGiver = DefDatabase.GetNamedSilentFail("ConstructDeliverResourcesToFrames")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructDeliverResourcesToFrames(); - var deliverJob = deliverFrameGiver.JobOnThing(pawn, frame, true); - if (deliverJob != null) return deliverJob; - - var finishGiver = DefDatabase.GetNamedSilentFail("ConstructFinishFrames")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructFinishFrames(); - var finishJob = finishGiver.JobOnThing(pawn, frame, true); - if (finishJob != null) return finishJob; - } - } - catch - { - return null; - } - - return null; - } #endif - - private static bool IsEssentialSurvivalStructure(string? defName) - { - if (string.IsNullOrWhiteSpace(defName)) return false; - return defName!.Equals("Bed", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Bedroll", StringComparison.OrdinalIgnoreCase) - || defName.Equals("DoubleBed", StringComparison.OrdinalIgnoreCase) - || defName.Equals("RoyalBed", StringComparison.OrdinalIgnoreCase) - || defName.Equals("HospitalBed", StringComparison.OrdinalIgnoreCase) - || defName.Equals("SleepingSpot", StringComparison.OrdinalIgnoreCase) - || defName.Equals("DoubleSleepingSpot", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Campfire", StringComparison.OrdinalIgnoreCase) - || defName.Equals("TorchLamp", StringComparison.OrdinalIgnoreCase) - || defName.Equals("PassiveCooler", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Heater", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Wall", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Door", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Autodoor", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Sandbags", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Barricade", StringComparison.OrdinalIgnoreCase) - || defName.Equals("TableShort", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Table1x2c", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Table2x2c", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Table2x4c", StringComparison.OrdinalIgnoreCase) - || defName.Equals("DiningChair", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Stool", StringComparison.OrdinalIgnoreCase) - || defName.Equals("Armchair", StringComparison.OrdinalIgnoreCase) - || defName.Equals("HoopstoneRing", StringComparison.OrdinalIgnoreCase) - || defName.Equals("HorseshoesPin", StringComparison.OrdinalIgnoreCase) - || defName.Equals("ChessTable", StringComparison.OrdinalIgnoreCase) - || defName.Equals("FueledStove", StringComparison.OrdinalIgnoreCase) - || defName.Equals("ElectricStove", StringComparison.OrdinalIgnoreCase) - || defName.Equals("ButcherSpot", StringComparison.OrdinalIgnoreCase) - || defName.Equals("TableButcher", StringComparison.OrdinalIgnoreCase) - || defName.Equals("SimpleResearchBench", StringComparison.OrdinalIgnoreCase); - } } } diff --git a/Source/Actions/PlanRoomProjectCompositeTool.cs b/Source/Actions/PlanRoomProjectCompositeTool.cs index f2f46ac..265edaa 100644 --- a/Source/Actions/PlanRoomProjectCompositeTool.cs +++ b/Source/Actions/PlanRoomProjectCompositeTool.cs @@ -3,17 +3,14 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RimMind.Actions.Policies; using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Agent.Policies; -using RimMind.Domain.Common; using RimMind.Domain.ValueObjects; -using RimMind.Presentation.Api; #if !RIMMIND_ACTIONS_TESTS +using RimMind.Presentation.Api; using RimWorld; -using Verse.AI; #endif using Verse; @@ -22,7 +19,7 @@ namespace RimMind.Actions.Actions /// /// Composite tool that autonomously plans and executes an integrated micro-room construction project /// (e.g. 5x5 emergency shelter: 4 walls + 1 door + 1 bed + 1 torch) - /// binding all sub-blueprints into a unified AgentIntentSession. + /// binding all sub-blueprints into a unified AgentIntentSession via . /// public sealed class PlanRoomProjectCompositeTool : CompositeToolCallBase { @@ -40,6 +37,7 @@ public sealed class PlanRoomProjectCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.BlueprintPlacement; + protected override ToolScope? ToolScopes => ToolScope.ColonyBuild; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => false; protected override string? DisplayName => "Plan Room Project"; @@ -56,28 +54,17 @@ public sealed class PlanRoomProjectCompositeTool : CompositeToolCallBase public override IReadOnlyList RequiredToolIds => Array.Empty(); protected override AutonomyDomain? ResolveAutonomyDomain(JObject? root, ToolCallArgs args) - { - string? roomType = root?["room_type"]?.ToString(); - if (string.IsNullOrWhiteSpace(roomType) && args != null) - { - TryGetArgument(args.ArgumentsJson, "room_type", out roomType); - } - if (string.IsNullOrWhiteSpace(roomType)) - { - roomType = "Shelter"; - } - - return AutonomyDomain.BlueprintPlacement; - } + => AutonomyDomain.BlueprintPlacement; public override Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); #if RIMMIND_ACTIONS_TESTS - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.BlueprintPlacement; - if (TryGetArgument(args.ArgumentsJson, "pawn_id", out int testPawnId) && testPawnId > 0) + if (TryGetArgument(argsRoot, "pawn_id", out int testPawnId) && testPawnId > 0) { var guard = GuardColonistTarget(testPawnId, domain, args); if (guard.IsErr) @@ -88,7 +75,7 @@ public override Task> ExecuteAsync( return Task.FromResult(Result.Ok( ToolResult.Ok("Planned room", args.ToolCallId, Id))); #else - var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: false); + var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, "pawn_id", fallbackToAnyActiveColonist: false, parsedArgs: argsRoot); if (actorResolution.Error != null) { return Task.FromResult(Result.Err( @@ -106,45 +93,37 @@ public override Task> ExecuteAsync( Pawn? builderPawn = actorResolution.Pawn; if (builderPawn == null) { - // Pick active colonist with highest construction skill - builderPawn = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map) - .Where(p => RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(p) && !p.Downed) + builderPawn = RimMindPawnLookup.GetSpawnedColonistsSafe(map) + .Where(p => RimMindPawnLookup.IsActiveSpawnedColonist(p) && !p.Downed) .OrderByDescending(p => p.skills?.GetSkill(SkillDefOf.Construction)?.Level ?? 0) .FirstOrDefault(); } // 2. Resolve Room Type & Autonomy Permission Guard - TryGetArgument(args.ArgumentsJson, "room_type", out var roomType); + TryGetArgument(argsRoot, "room_type", out var roomType); if (string.IsNullOrWhiteSpace(roomType)) roomType = "Shelter"; - var roomAutonomyDomain = AutonomyDomain.BlueprintPlacement; - - var permCheck = ActionPermissionGuard.CheckPermission(builderPawn, Id, roomAutonomyDomain, args); + var permCheck = ActionPermissionGuard.CheckPermission(builderPawn, Id, AutonomyDomain.BlueprintPlacement, args); if (!permCheck.IsOk) { return Task.FromResult(Result.Err(permCheck.Error)); } // 3. Resolve Size and Materials - TryGetArgument(args.ArgumentsJson, "size", out var size); + TryGetArgument(argsRoot, "size", out var size); if (size <= 0) size = 5; - size = Math.Clamp(size, 4, 9); + size = Math.Max(4, Math.Min(9, size)); - TryGetArgument(args.ArgumentsJson, "stuff_def", out var stuffDefName); - ThingDef? selectedStuff = null; - if (!string.IsNullOrWhiteSpace(stuffDefName)) + TryGetArgument(argsRoot, "stuff_def", out var stuffDefName); + ThingDef? selectedStuff = ConstructionIntentChainer.ResolveThingDef(stuffDefName); + if (selectedStuff != null && !GenStuff.AllowedStuffsFor(ThingDefOf.Wall).Contains(selectedStuff)) { - var trimmedStuff = stuffDefName.Trim(); - selectedStuff = DefDatabase.GetNamedSilentFail(trimmedStuff) - ?? DefDatabase.AllDefsListForReading - .FirstOrDefault(d => d != null - && (string.Equals(d.defName, trimmedStuff, StringComparison.OrdinalIgnoreCase) - || string.Equals(d.label, trimmedStuff, StringComparison.OrdinalIgnoreCase))); + selectedStuff = null; } if (selectedStuff == null) { - int woodCount = ResourceSafetyGuard.GetAvailableCount(map, ThingDefOf.WoodLog); - int steelCount = ResourceSafetyGuard.GetAvailableCount(map, ThingDefOf.Steel); + int woodCount = MapResourceCounter.GetAvailableCount(map, ThingDefOf.WoodLog); + int steelCount = MapResourceCounter.GetAvailableCount(map, ThingDefOf.Steel); selectedStuff = woodCount >= steelCount ? ThingDefOf.WoodLog : ThingDefOf.Steel; } @@ -196,11 +175,9 @@ public override Task> ExecuteAsync( } // Interior Bed - TryGetArgument(args.ArgumentsJson, "include_bed", out var includeBed); - if (!args.ArgumentsJson.Contains("\"include_bed\"")) - { - includeBed = !string.Equals(roomType, "Storage", StringComparison.OrdinalIgnoreCase); - } + bool includeBed = TryGetArgument(argsRoot, "include_bed", out var parsedIncludeBed) + ? parsedIncludeBed + : !string.Equals(roomType, "Storage", StringComparison.OrdinalIgnoreCase); if (includeBed) { IntVec3 bedCell = new IntVec3(bestRect.minX + 1, 0, bestRect.maxZ - 1); @@ -220,71 +197,21 @@ public override Task> ExecuteAsync( if (torchBp != null) placedBlueprints.Add(torchBp); } - // 7. Chain Unified AgentIntentSession on Builder Colonist + // 7. Chain Unified AgentIntentSession via Shared ConstructionIntentChainer bool sessionChained = false; string builderName = builderPawn?.LabelShort ?? "Colonist"; if (builderPawn != null && placedBlueprints.Count > 0) { - var firstBp = placedBlueprints[0]; - Map projectMap = map; var targetCells = placedBlueprints.Select(b => b.Position).Distinct().ToList(); - sessionChained = RimMindAPI.Agent.StartIntentSession( - pawn: builderPawn, + sessionChained = ConstructionIntentChainer.TryChainProject( + builderPawn, + map, + placedBlueprints, + targetCells, intentId: $"Project_Shelter_{bestRect.CenterCell.x}_{bestRect.CenterCell.z}", - startTick: Find.TickManager?.TicksGame ?? 0, durationTicks: 5000, - priority: 7.8f, - target: firstBp, - jobProvider: p => - { - if (p == null || projectMap == null) return null; - // Respect the player's work tab: never rewrite priorities. - if (p.WorkTypeIsDisabled(WorkTypeDefOf.Construction) - || (p.workSettings != null && !p.workSettings.WorkIsActive(WorkTypeDefOf.Construction))) - { - return null; - } - - var deliverBpGiver = DefDatabase.GetNamedSilentFail("ConstructDeliverResourcesToBlueprints")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructDeliverResourcesToBlueprints(); - var deliverFrameGiver = DefDatabase.GetNamedSilentFail("ConstructDeliverResourcesToFrames")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructDeliverResourcesToFrames(); - var finishGiver = DefDatabase.GetNamedSilentFail("ConstructFinishFrames")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructFinishFrames(); - - foreach (var bp in placedBlueprints) - { - if (bp == null || bp.Destroyed || !bp.Spawned) continue; - if (!p.CanReserveAndReach(bp, PathEndMode.Touch, Danger.Some)) continue; - - var haulJob = deliverBpGiver.JobOnThing(p, bp, true); - if (haulJob != null) return haulJob; - - var finishBpJob = finishGiver.JobOnThing(p, bp, true); - if (finishBpJob != null) return finishBpJob; - } - - foreach (var cell in targetCells) - { - if (!cell.InBounds(projectMap)) continue; - var frame = cell.GetThingList(projectMap).OfType().FirstOrDefault(f => !f.Destroyed && f.Spawned); - if (frame == null || !p.CanReserveAndReach(frame, PathEndMode.Touch, Danger.Some)) continue; - - var deliverJob = deliverFrameGiver.JobOnThing(p, frame, true); - if (deliverJob != null) return deliverJob; - - var finishJob = finishGiver.JobOnThing(p, frame, true); - if (finishJob != null) return finishJob; - } - - return null; - }, - completionPredicate: p => - projectMap == null - || (placedBlueprints.All(b => b == null || b.Destroyed || !b.Spawned) - && !targetCells.Any(cell => cell.InBounds(projectMap) - && cell.GetThingList(projectMap).OfType().Any(f => !f.Destroyed && f.Spawned)))); + priority: 7.8f); } string planMsg = ActionPermissionGuard.TranslateOrFallback( diff --git a/Source/Actions/QueryBuildableStructuresCompositeTool.cs b/Source/Actions/QueryBuildableStructuresCompositeTool.cs index 774fc7f..d01f91e 100644 --- a/Source/Actions/QueryBuildableStructuresCompositeTool.cs +++ b/Source/Actions/QueryBuildableStructuresCompositeTool.cs @@ -4,11 +4,13 @@ using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; +using RimMind.Actions.Policies; using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Agent.Policies; using RimMind.Domain.ValueObjects; #if !RIMMIND_ACTIONS_TESTS using RimMind.Actions.Spatial; +using RimMind.Presentation.Api; using RimWorld; #endif using Verse; @@ -16,8 +18,9 @@ namespace RimMind.Actions.Actions { /// - /// Composite query tool allowing AI Agents to inspect available buildable structures, - /// researched technologies, material costs, stockpile reserves, and urgent infrastructure bottlenecks. + /// Composite query tool allowing AI Agents to dynamically inspect player-buildable structures + /// discovered from DefDatabase<ThingDef> (covering both vanilla and modded buildings), + /// material costs, stockpile reserves, spatial layout, and urgent infrastructure bottlenecks. /// public sealed class QueryBuildableStructuresCompositeTool : CompositeToolCallBase { @@ -36,6 +39,7 @@ public sealed class QueryBuildableStructuresCompositeTool : CompositeToolCallBas protected override ToolKind ToolKind => ToolKind.Query; protected override AutonomyDomain? DefaultAutonomyDomain => null; + protected override ToolScope? ToolScopes => ToolScope.ColonyBuild | ToolScope.ColonyManage; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => false; protected override string? DisplayName => "Query Buildable Structures"; @@ -45,8 +49,8 @@ public sealed class QueryBuildableStructuresCompositeTool : CompositeToolCallBas { Id = Id, Category = "query", - Description = "Query buildable structures unlocked by the colony's research, material costs, map stockpile availability, and urgent infrastructure bottlenecks (beds, temperature, recreation).", - ParametersSchema = "{\"type\":\"object\",\"properties\":{\"category\":{\"type\":\"string\",\"description\":\"Optional category filter: 'furniture', 'temperature', 'production', 'recreation', 'defense', 'livestock', or 'all' (default).\"}},\"required\":[]}" + Description = "Dynamically queries player-buildable structures unlocked by colony research (vanilla and modded), material costs, stockpile availability, spatial layout, and urgent infrastructure bottlenecks.", + ParametersSchema = "{\"type\":\"object\",\"properties\":{\"category\":{\"type\":\"string\",\"description\":\"Optional category filter: 'furniture', 'temperature', 'production', 'recreation', 'defense', 'livestock', 'power', 'structure', or 'all' (default).\"}},\"required\":[]}" }; public override IReadOnlyList RequiredToolIds => Array.Empty(); @@ -55,7 +59,8 @@ public override Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - TryGetArgument(args.ArgumentsJson, "category", out var categoryFilter); + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + TryGetArgument(argsRoot, "category", out var categoryFilter); categoryFilter = string.IsNullOrWhiteSpace(categoryFilter) ? "all" : categoryFilter.ToLowerInvariant().Trim(); #if RIMMIND_ACTIONS_TESTS @@ -68,7 +73,7 @@ public override Task> ExecuteAsync( })); #else // Read-only query: prefer the acting colonist's map, fall back to the viewed map. - var actorResolution = RimMind.Actions.Policies.ActionPermissionGuard.ResolveActorAndMap(args); + var actorResolution = ActionPermissionGuard.ResolveActorAndMap(args, parsedArgs: argsRoot); var map = actorResolution.Map ?? Find.CurrentMap; if (map == null) { @@ -103,55 +108,53 @@ public override Task> ExecuteAsync( tables = r.TableCount }) .ToList(); - string spatialAsciiMap = ColonySpatialClusterSolver.RenderCompactAsciiGrid( + string spatialAsciiMap = SpatialAsciiRenderer.RenderCompactAsciiGrid( spatialSnapshot, spatialSnapshot.ColonyAnchorX, spatialSnapshot.ColonyAnchorZ, radius: 10); - int woodCount = RimMind.Actions.Policies.ResourceSafetyGuard.GetAvailableCount(map, ThingDefOf.WoodLog); - int steelCount = RimMind.Actions.Policies.ResourceSafetyGuard.GetAvailableCount(map, ThingDefOf.Steel); + int woodCount = MapResourceCounter.GetAvailableCount(map, ThingDefOf.WoodLog); + int steelCount = MapResourceCounter.GetAvailableCount(map, ThingDefOf.Steel); var compDef = DefDatabase.GetNamedSilentFail("ComponentIndustrial") ?? DefDatabase.GetNamedSilentFail("ComponentsIndustrial"); - int componentCount = compDef != null ? RimMind.Actions.Policies.ResourceSafetyGuard.GetAvailableCount(map, compDef) : 0; + int componentCount = compDef != null ? MapResourceCounter.GetAvailableCount(map, compDef) : 0; float outdoorTemp = map.mapTemperature.OutdoorTemp; bool hasPower = HasActivePowerGrid(map); var bottlenecks = DetectBottlenecks(map, outdoorTemp, hasPower); - var catalog = GetCuratedStructures(); - var filteredStructures = new List(); - - foreach (var s in catalog) + var availableByDefName = new Dictionary(StringComparer.OrdinalIgnoreCase); + int LookupAvailableCount(string defName) { - if (categoryFilter != "all" && !s.Category.Equals(categoryFilter, StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - var def = DefDatabase.GetNamedSilentFail(s.DefName); - if (def == null) continue; - - // Check research requirements - if (def.researchPrerequisites != null && def.researchPrerequisites.Any(r => !r.IsFinished)) - { - continue; - } + if (string.IsNullOrWhiteSpace(defName)) return 0; + if (availableByDefName.TryGetValue(defName, out int cached)) return cached; + var resolved = DefDatabase.GetNamedSilentFail(defName); + int count = resolved != null ? MapResourceCounter.GetAvailableCount(map, resolved) : 0; + availableByDefName[defName] = count; + return count; + } - bool canAfford = CheckCanAfford(def, s.BaseCostWood, s.BaseCostSteel, s.BaseCostComp, woodCount, steelCount, componentCount); + var dynamicDescriptors = DiscoverBuildableStructures(map, LookupAvailableCount); + var catalogItems = BuildableStructureCatalogPolicy.FilterAndProject( + dynamicDescriptors, + categoryFilter, + LookupAvailableCount, + BuildableStructureCatalogPolicy.DefaultMaxResults); - filteredStructures.Add(new + var filteredStructures = catalogItems + .Select(s => new { def_name = s.DefName, - label = def.label, + label = s.Label, category = s.Category, requires_power = s.RequiresPower, - cost_summary = s.CostDescription, - can_afford = canAfford, + cost_summary = s.CostSummary, + can_afford = s.CanAfford, purpose = s.Purpose - }); - } + }) + .ToList(); var responsePayload = new { @@ -190,6 +193,138 @@ public override Task> ExecuteAsync( } #if !RIMMIND_ACTIONS_TESTS + private static List DiscoverBuildableStructures( + Map map, + Func lookupAvailableCount) + { + var results = new List(); + var allDefs = DefDatabase.AllDefsListForReading; + + for (int i = 0; i < allDefs.Count; i++) + { + var def = allDefs[i]; + if (def == null + || def.category != ThingCategory.Building + || def.IsFrame + || def.IsBlueprint + || !def.BuildableByPlayer + || !def.IsResearchFinished + || def.designationCategory == null) + { + continue; + } + + var powerComp = def.GetCompProperties(); + bool requiresPower = powerComp != null && powerComp.PowerConsumption > 0f; + bool generatesPower = powerComp != null && powerComp.PowerConsumption < 0f; + + bool isBed = def.thingClass != null && typeof(Building_Bed).IsAssignableFrom(def.thingClass); + bool isWorkTable = def.thingClass != null && typeof(Building_WorkTable).IsAssignableFrom(def.thingClass); + bool isTable = def.surfaceType == SurfaceType.Eat; + bool isJoy = def.building?.joyKind != null; + bool isDefense = (def.building != null && def.building.IsTurret) + || (def.thingClass != null && typeof(Building_Trap).IsAssignableFrom(def.thingClass)) + || string.Equals(def.designationCategory.defName, "Security", StringComparison.OrdinalIgnoreCase); + bool isFenceOrPen = (def.building != null && def.building.isFence) + || def.GetCompProperties() != null + || (def.defName != null && (def.defName.IndexOf("Fence", StringComparison.OrdinalIgnoreCase) >= 0 + || def.defName.IndexOf("PenMarker", StringComparison.OrdinalIgnoreCase) >= 0)); + bool isTempControl = def.GetCompProperties() != null + || def.GetCompProperties() != null; + + string category = BuildableStructureCatalogPolicy.ClassifyCategory( + def.designationCategory.defName, + def.defName, + isBed: isBed, + isWorkTable: isWorkTable, + isTable: isTable, + isJoy: isJoy, + isDefense: isDefense, + isFenceOrPen: isFenceOrPen, + isTempControl: isTempControl, + generatesPower: generatesPower); + + int stuffCount = def.MadeFromStuff ? def.costStuffCount : 0; + string? bestStuffLabel = null; + int bestStuffAvailable = 0; + if (stuffCount > 0) + { + ThingDef? bestStuff = null; + foreach (var allowed in GenStuff.AllowedStuffsFor(def)) + { + if (allowed == null) continue; + int have = lookupAvailableCount(allowed.defName); + if (bestStuff == null || have > bestStuffAvailable) + { + bestStuff = allowed; + bestStuffAvailable = have; + } + } + + if (bestStuff == null) + { + bestStuff = GenStuff.DefaultStuffFor(def); + bestStuffAvailable = bestStuff != null ? lookupAvailableCount(bestStuff.defName) : 0; + } + + bestStuffLabel = bestStuff?.defName ?? bestStuff?.label ?? "Stuff"; + } + + var fixedCosts = new List(); + if (def.costList != null) + { + for (int c = 0; c < def.costList.Count; c++) + { + var item = def.costList[c]; + if (item?.thingDef != null && item.count > 0) + { + fixedCosts.Add(new BuildableMaterialCost( + item.thingDef.defName, + item.thingDef.defName, + item.count)); + } + } + } + + int priorityWeight = ComputePriorityWeight(category, isBed, isWorkTable, isTempControl, isJoy, requiresPower); + + results.Add(new BuildableStructureDescriptor + { + DefName = def.defName ?? string.Empty, + Label = def.label ?? def.defName ?? string.Empty, + Category = category, + RequiresPower = requiresPower, + CostStuffCount = stuffCount, + BestStuffLabel = bestStuffLabel, + BestStuffAvailable = bestStuffAvailable, + FixedCosts = fixedCosts, + Purpose = def.description ?? string.Empty, + PriorityWeight = priorityWeight + }); + } + + return results; + } + + private static int ComputePriorityWeight( + string category, + bool isBed, + bool isWorkTable, + bool isTempControl, + bool isJoy, + bool requiresPower) + { + int weight = 0; + if (isBed) weight += 30; + if (isWorkTable) weight += 25; + if (isTempControl) weight += 25; + if (isJoy) weight += 20; + if (!requiresPower) weight += 10; + if (category == "furniture" || category == "production" || category == "temperature") + weight += 10; + return weight; + } + private static bool HasActivePowerGrid(Map map) { if (map.powerNetManager == null) return false; @@ -203,8 +338,8 @@ private static bool HasActivePowerGrid(Map map) private static List DetectBottlenecks(Map map, float outdoorTemp, bool hasPower) { var list = new List(); - var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map) - .Where(p => RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(p) && !p.Downed) + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map) + .Where(p => RimMindPawnLookup.IsActiveSpawnedColonist(p) && !p.Downed) .ToList(); bool sleepingOutside = false; @@ -253,92 +388,6 @@ private static List DetectBottlenecks(Map map, float outdoorTemp, bool h return list; } - - private static bool CheckCanAfford(ThingDef def, int wood, int steel, int comp, int woodHave, int steelHave, int compHave) - { - if (wood > 0 && woodHave < wood) return false; - if (steel > 0 && steelHave < steel) return false; - if (comp > 0 && compHave < comp) return false; - return true; - } #endif - - private static List GetCuratedStructures() - { - return new List - { - // Furniture - new StructureEntry("Bed", "furniture", false, "45 WoodLog or Steel", 45, 0, 0, "Comfortable sleeping; prevents SleptOnGround and SleptOutside debuffs"), - new StructureEntry("Bedroll", "furniture", false, "40 Cloth or Leather", 0, 0, 0, "Portable light sleeping bed"), - new StructureEntry("TableShort", "furniture", false, "28 WoodLog or Steel", 28, 0, 0, "Small dining/recreation table; prevents AteOnGround debuff"), - new StructureEntry("Table2x2c", "furniture", false, "40 WoodLog or Steel", 40, 0, 0, "Medium 2x2 dining and recreation table"), - new StructureEntry("Chair", "furniture", false, "20 WoodLog or Steel", 20, 0, 0, "Comfortable seating at tables and workbenches"), - new StructureEntry("Stool", "furniture", false, "15 WoodLog or Steel", 15, 0, 0, "Simple fast seating"), - - // Temperature - new StructureEntry("PassiveCooler", "temperature", false, "50 WoodLog", 50, 0, 0, "Zero-electricity evaporative cooler; cools rooms down to 15°C; perfect for early game heat"), - new StructureEntry("Campfire", "temperature", false, "20 WoodLog", 20, 0, 0, "Zero-electricity heat source, light, and simple meal cooking"), - new StructureEntry("Cooler", "temperature", true, "90 Steel + 3 Components", 0, 90, 3, "Powered refrigeration unit; required for food freezers"), - new StructureEntry("Heater", "temperature", true, "50 Steel + 1 Component", 0, 50, 1, "Powered thermostatically controlled indoor heater"), - new StructureEntry("Vent", "temperature", false, "30 Steel", 0, 30, 0, "Equalizes temperature between adjacent enclosed rooms"), - - // Production - new StructureEntry("FueledStove", "production", false, "80 WoodLog + 20 Steel", 80, 20, 0, "Wood-fueled cooking stove to cook fine, simple, or lavish meals"), - new StructureEntry("TableButcher", "production", false, "75 WoodLog or Steel", 75, 0, 0, "Butchering table to process animal corpses into meat and leather"), - new StructureEntry("CraftingSpot", "production", false, "Free", 0, 0, 0, "Designated floor spot for simple crafting without material cost"), - new StructureEntry("TableStonecutter", "production", false, "70 WoodLog or Steel", 70, 0, 0, "Cuts raw stone chunks into building blocks"), - new StructureEntry("HandTailoringBench", "production", false, "50 WoodLog", 50, 0, 0, "Manual tailoring bench for parkas, dusters, and apparel"), - new StructureEntry("FueledSmithy", "production", false, "100 Steel", 0, 100, 0, "Fueled forge for melee weapons and armor"), - new StructureEntry("ResearchBench", "production", false, "50 WoodLog + 20 Steel", 50, 20, 0, "Simple bench for unlocking new colony technologies"), - - // Recreation - new StructureEntry("HorseshoePin", "recreation", false, "15 WoodLog or Steel", 15, 0, 0, "Outdoor dexterity recreation game"), - new StructureEntry("ChessTable", "recreation", false, "70 WoodLog", 70, 0, 0, "Indoor cerebral recreation and social gathering spot"), - - // Defense & Security - new StructureEntry("TrapSpike", "defense", false, "45 WoodLog or Steel", 45, 0, 0, "Deadly spring-loaded deadfall spike trap"), - new StructureEntry("Sandbags", "defense", false, "5 Steel or Cloth per tile", 0, 5, 0, "Low-cover fortification against enemy ballistic fire"), - new StructureEntry("Barricade", "defense", false, "5 WoodLog or Metal per tile", 5, 0, 0, "Quick defensive cover built from wood or stone"), - new StructureEntry("Wall", "defense", false, "5 WoodLog or Stone per tile", 5, 0, 0, "Encloses rooms, provides roof support, and blocks enemies"), - new StructureEntry("Door", "defense", false, "25 WoodLog or Steel", 25, 0, 0, "Provides passage through walls while maintaining room insulation"), - - // Livestock - new StructureEntry("PenMarker", "livestock", false, "20 WoodLog", 20, 0, 0, "Marks an enclosed pasture/pen for domestic herd animals"), - new StructureEntry("Fence", "livestock", false, "2 WoodLog per tile", 2, 0, 0, "Low wooden barrier that encloses pen animals"), - new StructureEntry("FenceGate", "livestock", false, "10 WoodLog", 10, 0, 0, "Passage gate for colonists into animal pens") - }; - } - - private class StructureEntry - { - public string DefName { get; } - public string Category { get; } - public bool RequiresPower { get; } - public string CostDescription { get; } - public int BaseCostWood { get; } - public int BaseCostSteel { get; } - public int BaseCostComp { get; } - public string Purpose { get; } - - public StructureEntry( - string defName, - string category, - bool requiresPower, - string costDescription, - int baseCostWood, - int baseCostSteel, - int baseCostComp, - string purpose) - { - DefName = defName; - Category = category; - RequiresPower = requiresPower; - CostDescription = costDescription; - BaseCostWood = baseCostWood; - BaseCostSteel = baseCostSteel; - BaseCostComp = baseCostComp; - Purpose = purpose; - } - } } } diff --git a/Source/Actions/StabilizeRestCompositeTool.cs b/Source/Actions/StabilizeRestCompositeTool.cs index 11cd80d..bc96911 100644 --- a/Source/Actions/StabilizeRestCompositeTool.cs +++ b/Source/Actions/StabilizeRestCompositeTool.cs @@ -29,6 +29,7 @@ public sealed class StabilizeRestCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.EmergencySurvival; + protected override ToolScope? ToolScopes => ToolScope.ColonistSelf; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => true; protected override string? DisplayName => "Force Rest"; @@ -49,14 +50,15 @@ public override async Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - var pawnIdResult = TryGetPawnIdOrError(args, "pawn_id"); + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + var pawnIdResult = TryGetPawnIdOrError(argsRoot, args, "pawn_id"); if (pawnIdResult.IsErr) { return Result.Err(pawnIdResult.Error); } int pawnId = pawnIdResult.Value; - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.EmergencySurvival; var guard = GuardColonistTarget(pawnId, domain, args); if (guard.IsErr) diff --git a/Source/Actions/TriagePatientCompositeTool.cs b/Source/Actions/TriagePatientCompositeTool.cs index 1759121..1ec032a 100644 --- a/Source/Actions/TriagePatientCompositeTool.cs +++ b/Source/Actions/TriagePatientCompositeTool.cs @@ -33,6 +33,7 @@ public sealed class TriagePatientCompositeTool : CompositeToolCallBase }; protected override AutonomyDomain? DefaultAutonomyDomain => AutonomyDomain.EmergencySurvival; + protected override ToolScope? ToolScopes => ToolScope.ColonistSelf; protected override IReadOnlyList ToolAliases => Aliases; protected override bool IsSelfTargetedTool => true; protected override string? DisplayName => "Triage Patient"; @@ -53,14 +54,15 @@ public override async Task> ExecuteAsync( ToolCallArgs args, CancellationToken ct) { - var patientIdResult = TryGetPawnIdOrError(args, "patient_id"); + var argsRoot = TryParseArgumentsObject(args.ArgumentsJson); + var patientIdResult = TryGetPawnIdOrError(argsRoot, args, "patient_id"); if (patientIdResult.IsErr) { return Result.Err(patientIdResult.Error); } int patientId = patientIdResult.Value; - var domain = ResolveAutonomyDomain(TryParseArgumentsObject(args.ArgumentsJson), args) + var domain = ResolveAutonomyDomain(argsRoot, args) ?? AutonomyDomain.EmergencySurvival; var patientGuard = GuardColonistTarget(patientId, domain, args, "patient_id"); if (patientGuard.IsErr) @@ -69,7 +71,7 @@ public override async Task> ExecuteAsync( } int doctorId = 0; - bool hasDoctor = TryGetArgument(args.ArgumentsJson, "doctor_id", out doctorId) && doctorId > 0; + bool hasDoctor = TryGetArgument(argsRoot, "doctor_id", out doctorId) && doctorId > 0; if (hasDoctor) { var doctorGuard = GuardColonistTarget(doctorId, domain, args, "doctor_id"); @@ -105,13 +107,7 @@ public override async Task> ExecuteAsync( if (hasDoctor) { #if !RIMMIND_ACTIONS_TESTS - var docPawn = RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber(doctorId); - if (docPawn?.workSettings != null && docPawn.workSettings.EverWork && !docPawn.WorkTypeIsDisabled(RimWorld.WorkTypeDefOf.Doctor)) - { - docPawn.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); - docPawn.workSettings.SetPriority(RimWorld.WorkTypeDefOf.Doctor, 1); - } - + // Respect player work priorities: never mutate workSettings.SetPriority; dispatch direct rescue/tend job. if (patientPawn != null && patientPawn.Downed && !RimWorld.RestUtility.InBed(patientPawn)) { var rescueArgs = BuildArgumentsJson(("pawn_id", doctorId), ("action", "rescue_pawn"), ("target_pawn_id", patientId)); diff --git a/Source/Debug/ActionsBehaviorAutotestSuite.cs b/Source/Debug/ActionsBehaviorAutotestSuite.cs index 95c337c..1240bd2 100644 --- a/Source/Debug/ActionsBehaviorAutotestSuite.cs +++ b/Source/Debug/ActionsBehaviorAutotestSuite.cs @@ -25,7 +25,7 @@ public sealed class ActionsBehaviorAutotestSuite : BehaviorAutotestSuiteBase public override void RunSuite(IInGameBehaviorSuiteContext context) { - var registry = RimMindAPI.Tools; + var registry = RimMindAPI.ToolSet.Registry; // 1. Check Tool Registration context.Assert(registry != null, "Tool registry is accessible from RimMindAPI.ToolSet.Registry"); diff --git a/Source/Policies/ActionPermissionGuard.cs b/Source/Policies/ActionPermissionGuard.cs index ab1a84e..f153d5c 100644 --- a/Source/Policies/ActionPermissionGuard.cs +++ b/Source/Policies/ActionPermissionGuard.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json.Linq; using RimMind.Actions.Actions; using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Agent.Policies; @@ -5,11 +6,13 @@ using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; using Verse; +using CompositeToolCallBase = RimMind.Actions.Actions.CompositeToolCallBase; namespace RimMind.Actions.Policies { /// - /// Guard that enforces colonist tri-state autonomy permissions before executing autonomous composite tools. + /// Guard that enforces colonist tri-state autonomy permissions and resolves actor/map targets + /// via Core and . /// public static class ActionPermissionGuard { @@ -27,7 +30,7 @@ public static bool IsChineseLanguageActive() } public static string TranslateOrFallback(string key, string fallbackEn, params object[] args) - => ResourceSafetyPolicy.TranslateOrFallback(key, fallbackEn, args); + => RimMindAPI.Text.TrOr(key, fallbackEn, args); public static Result CheckPermission( Pawn? pawn, @@ -100,38 +103,45 @@ public ActorResolution(Pawn? pawn, Map? map, string? error) } /// - /// Resolves the acting colonist across all maps and returns that colonist's map, so actions never - /// land on whatever map the player happens to be viewing. Lookup order: - /// argument, , . - /// If any id is supplied but none resolves to an active standing colonist, an error is returned instead - /// of silently substituting another colonist. Only when no id is supplied at all does it fall back to - /// (and optionally any active colonist on it). + /// Resolves the acting colonist across all maps via Core and returns + /// that colonist's map, so actions never land on whatever map the player happens to be viewing. + /// Lookup order: argument, , + /// . /// public static ActorResolution ResolveActorAndMap( ToolCallArgs args, string pawnIdKey = "pawn_id", - bool fallbackToAnyActiveColonist = false) + bool fallbackToAnyActiveColonist = false, + JObject? parsedArgs = null) { + var root = parsedArgs ?? CompositeToolCallBase.ParseArgumentsObject(args.ArgumentsJson); bool anyIdSupplied = false; - Pawn? TryResolve(int id) + Pawn? TryResolve(int id, out Map? resolvedMap) { + resolvedMap = null; if (id <= 0) return null; anyIdSupplied = true; - var p = RimMindPawnLookup.FindPawnByNumber(id); - return p != null && RimMindPawnLookup.IsActiveSpawnedColonist(p) && !p.Downed ? p : null; + if (ActorMapResolver.ResolveColonistAndMap(id, allowDowned: false, out var pawn, out var map, out _, args.TraceId)) + { + resolvedMap = map; + return pawn; + } + return null; } Pawn? actor = null; - if (CompositeToolCallBase.TryGetArgument(args.ArgumentsJson, pawnIdKey, out int argPawnId)) - actor = TryResolve(argPawnId); + Map? actorMap = null; + + if (CompositeToolCallBase.TryReadArgument(root, pawnIdKey, out int argPawnId)) + actor = TryResolve(argPawnId, out actorMap); if (actor == null && args.PawnId.HasValue) - actor = TryResolve(args.PawnId.Value); - if (actor == null && CompositeToolCallBase.TryParsePawnIdString(args.NpcId, out int npcPawnId)) - actor = TryResolve(npcPawnId); + actor = TryResolve(args.PawnId.Value, out actorMap); + if (actor == null && CompositeToolCallBase.TryParsePawnId(args.NpcId, out int npcPawnId)) + actor = TryResolve(npcPawnId, out actorMap); if (actor != null) - return new ActorResolution(actor, actor.Map, null); + return new ActorResolution(actor, actorMap ?? actor.Map, null); if (anyIdSupplied) { @@ -141,9 +151,9 @@ public static ActorResolution ResolveActorAndMap( "Requested colonist is not an active, standing colonist on any map (dead, downed, off-map, prisoner or not a colonist).")); } - var map = Find.CurrentMap; + var map = ActorMapResolver.ResolveMap(null); return new ActorResolution( - fallbackToAnyActiveColonist ? ResolveColonistOnMap(map, args, pawnIdKey, true) : null, + fallbackToAnyActiveColonist ? ResolveColonistOnMap(map, args, pawnIdKey, true, root) : null, map, null); } @@ -157,12 +167,15 @@ public static ActorResolution ResolveActorAndMap( Map? map, ToolCallArgs args, string pawnIdKey = "pawn_id", - bool fallbackToAnyActiveColonist = false) + bool fallbackToAnyActiveColonist = false, + JObject? parsedArgs = null) { var spawnedColonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map); if (spawnedColonists.Count == 0) return null; + var root = parsedArgs ?? CompositeToolCallBase.ParseArgumentsObject(args.ArgumentsJson); + Pawn? FindActiveColonistById(int id) { if (id <= 0) return null; @@ -175,7 +188,7 @@ public static ActorResolution ResolveActorAndMap( return null; } - if (CompositeToolCallBase.TryGetArgument(args.ArgumentsJson, pawnIdKey, out int argPawnId) && argPawnId > 0) + if (CompositeToolCallBase.TryReadArgument(root, pawnIdKey, out int argPawnId) && argPawnId > 0) { var byArg = FindActiveColonistById(argPawnId); if (byArg != null) return byArg; @@ -187,7 +200,7 @@ public static ActorResolution ResolveActorAndMap( if (byContext != null) return byContext; } - if (CompositeToolCallBase.TryParsePawnIdString(args.NpcId, out int npcPawnId) && npcPawnId > 0) + if (CompositeToolCallBase.TryParsePawnId(args.NpcId, out int npcPawnId) && npcPawnId > 0) { var byNpc = FindActiveColonistById(npcPawnId); if (byNpc != null) return byNpc; diff --git a/Source/Policies/BuildableStructureCatalogPolicy.cs b/Source/Policies/BuildableStructureCatalogPolicy.cs new file mode 100644 index 0000000..e1389e9 --- /dev/null +++ b/Source/Policies/BuildableStructureCatalogPolicy.cs @@ -0,0 +1,254 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RimMind.Actions.Policies +{ + /// + /// Pure material requirement entry extracted from a RimWorld ThingDef.costList. + /// + public readonly struct BuildableMaterialCost + { + public BuildableMaterialCost(string defName, string label, int count) + { + DefName = defName ?? string.Empty; + Label = string.IsNullOrWhiteSpace(label) ? DefName : label; + Count = count; + } + + public string DefName { get; } + public string Label { get; } + public int Count { get; } + } + + /// + /// Pure Verse-independent snapshot of a dynamically discovered player-buildable structure + /// (covers vanilla buildings AND any modded buildings in DefDatabase<ThingDef>). + /// + public sealed class BuildableStructureDescriptor + { + public string DefName { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + public string Category { get; set; } = "misc"; + public bool RequiresPower { get; set; } + public int CostStuffCount { get; set; } + public string? BestStuffLabel { get; set; } + public int BestStuffAvailable { get; set; } + public IReadOnlyList FixedCosts { get; set; } = Array.Empty(); + public string Purpose { get; set; } = string.Empty; + public int PriorityWeight { get; set; } + } + + /// + /// Projected catalog item serialized back to the LLM. + /// + public sealed class BuildableStructureCatalogItem + { + public string DefName { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + public string Category { get; set; } = "misc"; + public bool RequiresPower { get; set; } + public string CostSummary { get; set; } = "Free"; + public bool CanAfford { get; set; } + public string Purpose { get; set; } = string.Empty; + } + + /// + /// Pure dynamic classification, cost formatting, affordability evaluation, and bounded ranking + /// for player-buildable structures discovered from RimWorld's DefDatabase<ThingDef>. + /// + public static class BuildableStructureCatalogPolicy + { + public const int DefaultMaxResults = 40; + + /// + /// Maps RimWorld architect designation categories and building metadata into normalized query categories + /// (furniture, temperature, production, recreation, defense, + /// livestock, power, structure, misc). + /// + public static string ClassifyCategory( + string? designationCategoryDefName, + string? defName, + bool isBed = false, + bool isWorkTable = false, + bool isTable = false, + bool isJoy = false, + bool isDefense = false, + bool isFenceOrPen = false, + bool isTempControl = false, + bool generatesPower = false) + { + if (isFenceOrPen) + return "livestock"; + + string des = (designationCategoryDefName ?? string.Empty).Trim(); + if (des.Equals("Furniture", StringComparison.OrdinalIgnoreCase)) + return "furniture"; + if (des.Equals("Temperature", StringComparison.OrdinalIgnoreCase)) + return "temperature"; + if (des.Equals("Production", StringComparison.OrdinalIgnoreCase)) + return "production"; + if (des.Equals("Joy", StringComparison.OrdinalIgnoreCase)) + return "recreation"; + if (des.Equals("Security", StringComparison.OrdinalIgnoreCase)) + return "defense"; + if (des.Equals("Power", StringComparison.OrdinalIgnoreCase)) + return "power"; + if (des.Equals("Structure", StringComparison.OrdinalIgnoreCase)) + { + if (isDefense) return "defense"; + return "structure"; + } + + if (isBed || isTable) return "furniture"; + if (isWorkTable) return "production"; + if (isJoy) return "recreation"; + if (isDefense) return "defense"; + if (isTempControl) return "temperature"; + if (generatesPower) return "power"; + + string key = (defName ?? string.Empty).Trim().ToLowerInvariant(); + if (key.Contains("fence") || key.Contains("penmarker") || key.Contains("animalflap")) + return "livestock"; + if (key.Contains("bed") || key.Contains("table") || key.Contains("chair") || key.Contains("stool")) + return "furniture"; + if (key.Contains("cooler") || key.Contains("heater") || key.Contains("campfire") || key.Contains("vent")) + return "temperature"; + if (key.Contains("stove") || key.Contains("bench") || key.Contains("butcher") || key.Contains("smith") || key.Contains("tailor") || key.Contains("research")) + return "production"; + if (key.Contains("horseshoe") || key.Contains("chess") || key.Contains("hoopstone")) + return "recreation"; + if (key.Contains("turret") || key.Contains("trap") || key.Contains("sandbag") || key.Contains("barricade")) + return "defense"; + if (key.Contains("wall") || key.Contains("door")) + return "structure"; + + return "misc"; + } + + public static string BuildCostSummary( + int costStuffCount, + string? stuffLabel, + IReadOnlyList? fixedCosts) + { + var parts = new List(); + if (costStuffCount > 0) + { + string mat = string.IsNullOrWhiteSpace(stuffLabel) ? "Stuff" : stuffLabel!.Trim(); + parts.Add($"{costStuffCount} {mat}"); + } + + if (fixedCosts != null) + { + for (int i = 0; i < fixedCosts.Count; i++) + { + var cost = fixedCosts[i]; + if (cost.Count > 0) + { + parts.Add($"{cost.Count} {cost.Label}"); + } + } + } + + return parts.Count == 0 ? "Free" : string.Join(" + ", parts); + } + + public static bool CanAfford( + int costStuffCount, + int bestStuffAvailable, + IReadOnlyList? fixedCosts, + Func availableCountLookup) + { + if (costStuffCount > 0 && bestStuffAvailable < costStuffCount) + return false; + + if (fixedCosts != null) + { + for (int i = 0; i < fixedCosts.Count; i++) + { + var cost = fixedCosts[i]; + if (cost.Count <= 0) continue; + int have = availableCountLookup != null ? availableCountLookup(cost.DefName) : 0; + if (have < cost.Count) + return false; + } + } + + return true; + } + + public static string TrimPurpose(string? description, int maxLength = 120) + { + if (string.IsNullOrWhiteSpace(description)) + return string.Empty; + + string singleLine = description!.Replace("\r", " ").Replace("\n", " ").Trim(); + while (singleLine.Contains(" ")) + singleLine = singleLine.Replace(" ", " "); + + if (singleLine.Length <= maxLength) + return singleLine; + + int sentenceEnd = singleLine.IndexOf('.', 0, Math.Min(singleLine.Length, maxLength)); + if (sentenceEnd >= 20) + return singleLine.Substring(0, sentenceEnd + 1); + + return singleLine.Substring(0, maxLength - 3).TrimEnd() + "..."; + } + + public static List FilterAndProject( + IEnumerable candidates, + string? categoryFilter, + Func availableCountLookup, + int maxResults = DefaultMaxResults) + { + if (candidates == null) + return new List(); + + string filter = string.IsNullOrWhiteSpace(categoryFilter) + ? "all" + : categoryFilter!.Trim().ToLowerInvariant(); + + bool matchesFilter(BuildableStructureDescriptor d) + { + if (filter == "all") return true; + if (string.Equals(d.Category, filter, StringComparison.OrdinalIgnoreCase)) return true; + // Keep 'defense' inclusive of walls/doors when explicitly querying defensive structures + if (filter == "defense" && string.Equals(d.Category, "structure", StringComparison.OrdinalIgnoreCase)) + return true; + return false; + } + + int cap = Math.Max(1, maxResults); + + return candidates + .Where(d => d != null && !string.IsNullOrWhiteSpace(d.DefName) && matchesFilter(d)) + .Select(d => + { + bool affordable = CanAfford(d.CostStuffCount, d.BestStuffAvailable, d.FixedCosts, availableCountLookup); + return new + { + Descriptor = d, + Affordable = affordable, + CostSummary = BuildCostSummary(d.CostStuffCount, d.BestStuffLabel, d.FixedCosts) + }; + }) + .OrderByDescending(x => x.Affordable) + .ThenByDescending(x => x.Descriptor.PriorityWeight) + .ThenBy(x => x.Descriptor.Category, StringComparer.OrdinalIgnoreCase) + .ThenBy(x => x.Descriptor.DefName, StringComparer.OrdinalIgnoreCase) + .Take(cap) + .Select(x => new BuildableStructureCatalogItem + { + DefName = x.Descriptor.DefName, + Label = string.IsNullOrWhiteSpace(x.Descriptor.Label) ? x.Descriptor.DefName : x.Descriptor.Label, + Category = x.Descriptor.Category, + RequiresPower = x.Descriptor.RequiresPower, + CostSummary = x.CostSummary, + CanAfford = x.Affordable, + Purpose = TrimPurpose(x.Descriptor.Purpose) + }) + .ToList(); + } + } +} diff --git a/Source/Policies/ResourceSafetyGuard.cs b/Source/Policies/ResourceSafetyGuard.cs index c2c4ecb..760b992 100644 --- a/Source/Policies/ResourceSafetyGuard.cs +++ b/Source/Policies/ResourceSafetyGuard.cs @@ -1,7 +1,7 @@ -using System; using System.Linq; using RimMind.Domain.Common; using RimMind.Domain.ValueObjects; +using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -9,7 +9,7 @@ namespace RimMind.Actions.Policies { /// /// Circuit-breaker guard ensuring autonomous agent actions never breach colony survival baselines. - /// Bridges in-game Map state with pure ResourceSafetyPolicy. + /// Bridges in-game Map state with pure ResourceSafetyPolicy and Core MapResourceCounter. /// public static class ResourceSafetyGuard { @@ -24,29 +24,10 @@ public static Result EvaluateBlueprintCapacity(int activeBlu => ResourceSafetyPolicy.EvaluateBlueprintCapacity(activeBlueprintCount); /// - /// Counts total available unforbidden units of a resource on the map (including both stockpile and unhauled map stacks). + /// Counts total available unforbidden units of a resource on the map via Core . /// public static int GetAvailableCount(Map? map, ThingDef? def) - { - if (map == null || def == null) return 0; - int counted = map.resourceCounter?.GetCount(def) ?? 0; - var spawnedList = map.listerThings?.ThingsOfDef(def); - if (spawnedList != null && spawnedList.Count > 0) - { - int unforbiddenTotal = 0; - for (int i = 0; i < spawnedList.Count; i++) - { - var t = spawnedList[i]; - if (t != null && t.Spawned && !t.Destroyed && !t.Position.Fogged(map) && !t.IsForbidden(Faction.OfPlayer)) - { - unforbiddenTotal += t.stackCount; - } - } - if (unforbiddenTotal > counted) - counted = unforbiddenTotal; - } - return counted; - } + => MapResourceCounter.GetAvailableCount(map, def); /// /// In-game evaluation of map conditions against safety guard. @@ -68,8 +49,8 @@ public static Result CheckConstructionSafety(Map? map, Thing } // 2. Resource reserve check - int currentWood = GetAvailableCount(map, ThingDefOf.WoodLog); - int currentSteel = GetAvailableCount(map, ThingDefOf.Steel); + int currentWood = MapResourceCounter.GetAvailableCount(map, ThingDefOf.WoodLog); + int currentSteel = MapResourceCounter.GetAvailableCount(map, ThingDefOf.Steel); string? stuffName = stuffDef?.defName; return ResourceSafetyPolicy.EvaluateReserves(currentWood, currentSteel, stuffName); diff --git a/Source/Policies/ResourceSafetyPolicy.cs b/Source/Policies/ResourceSafetyPolicy.cs index 444894f..1e08a16 100644 --- a/Source/Policies/ResourceSafetyPolicy.cs +++ b/Source/Policies/ResourceSafetyPolicy.cs @@ -2,7 +2,7 @@ using RimMind.Domain.Common; using RimMind.Domain.ValueObjects; #if !RIMMIND_ACTIONS_TESTS -using Verse; +using RimMind.Presentation.Api; #endif namespace RimMind.Actions.Policies @@ -19,19 +19,10 @@ public static class ResourceSafetyPolicy public static string TranslateOrFallback(string key, string fallbackEn, params object[] args) { #if !RIMMIND_ACTIONS_TESTS - try - { - if (!string.IsNullOrEmpty(key) && key.CanTranslate()) - { - string template = key.TranslateSimple(); - return args != null && args.Length > 0 ? string.Format(template, args) : template; - } - } - catch - { - } -#endif + return RimMindAPI.Text.TrOr(key, fallbackEn, args); +#else return args != null && args.Length > 0 ? string.Format(fallbackEn, args) : fallbackEn; +#endif } /// diff --git a/Source/Spatial/ColonySpatialClusterSolver.cs b/Source/Spatial/ColonySpatialClusterSolver.cs index b45f6ad..24705de 100644 --- a/Source/Spatial/ColonySpatialClusterSolver.cs +++ b/Source/Spatial/ColonySpatialClusterSolver.cs @@ -1,150 +1,12 @@ using System; using System.Collections.Generic; -using System.Text; namespace RimMind.Actions.Spatial { - public enum SpatialCellKind - { - OutOfBounds = 0, - Impassable = 1, - Wall = 2, - Door = 3, - OutdoorFloor = 4, - IndoorRoom = 5, - OccupiedFurniture = 6, - Blueprint = 7 - } - - public enum SpatialBuildingCategory - { - General = 0, - Sleeping = 1, - Production = 2, - DiningRecreation = 3, - TemperatureLight = 4, - Storage = 5, - Defense = 6, - Structure = 7 - } - - public sealed class SpatialRoomSummary - { - public int RoomId { get; set; } - public string Role { get; set; } = "Indoor"; - public int CellCount { get; set; } - public int BedCount { get; set; } - public int WorktableCount { get; set; } - public int TableCount { get; set; } - public int CenterX { get; set; } - public int CenterZ { get; set; } - public bool IsEnclosed { get; set; } - } - - public sealed class SpatialPeerItem - { - public string DefName { get; set; } = string.Empty; - public SpatialBuildingCategory Category { get; set; } - public int X { get; set; } - public int Z { get; set; } - public int RoomId { get; set; } - public bool IsBlueprint { get; set; } - } - - public sealed class SpatialPlacementRequest - { - public string BuildingDefName { get; set; } = string.Empty; - public SpatialBuildingCategory Category { get; set; } - public int SizeX { get; set; } = 1; - public int SizeZ { get; set; } = 1; - public bool HasInteractionCell { get; set; } - public int InteractionOffsetX { get; set; } - public int InteractionOffsetZ { get; set; } - public string LocationHint { get; set; } = "near_base"; - public int AnchorX { get; set; } - public int AnchorZ { get; set; } - } - - public sealed class SpatialCandidateScore - { - public int X { get; set; } - public int Z { get; set; } - public double Score { get; set; } - public int RoomId { get; set; } - public string Reason { get; set; } = string.Empty; - } - - public sealed class ColonySpatialSnapshot - { - private readonly SpatialCellKind[,] _cells; - private readonly int[,] _roomIds; - private readonly bool[,] _roofed; - private readonly bool[,] _storageZone; - private readonly Dictionary _roomMap = new Dictionary(); - - public ColonySpatialSnapshot(int minX, int minZ, int width, int height) - { - MinX = minX; - MinZ = minZ; - Width = Math.Max(1, width); - Height = Math.Max(1, height); - _cells = new SpatialCellKind[Width, Height]; - _roomIds = new int[Width, Height]; - _roofed = new bool[Width, Height]; - _storageZone = new bool[Width, Height]; - } - - public int MinX { get; } - public int MinZ { get; } - public int Width { get; } - public int Height { get; } - public int MaxX => MinX + Width - 1; - public int MaxZ => MinZ + Height - 1; - - public int ColonyAnchorX { get; set; } - public int ColonyAnchorZ { get; set; } - public bool HasBaseAnchor { get; set; } - - public List Rooms { get; } = new List(); - public List Peers { get; } = new List(); - - public bool InBounds(int x, int z) - => x >= MinX && x <= MaxX && z >= MinZ && z <= MaxZ; - - public void SetCell(int x, int z, SpatialCellKind kind, int roomId = 0, bool roofed = false, bool storageZone = false) - { - if (!InBounds(x, z)) return; - int ix = x - MinX; - int iz = z - MinZ; - _cells[ix, iz] = kind; - _roomIds[ix, iz] = roomId; - _roofed[ix, iz] = roofed; - _storageZone[ix, iz] = storageZone; - } - - public SpatialCellKind GetCellKind(int x, int z) - => InBounds(x, z) ? _cells[x - MinX, z - MinZ] : SpatialCellKind.OutOfBounds; - - public int GetRoomId(int x, int z) - => InBounds(x, z) ? _roomIds[x - MinX, z - MinZ] : 0; - - public bool IsRoofed(int x, int z) - => InBounds(x, z) && _roofed[x - MinX, z - MinZ]; - - public bool IsStorageZone(int x, int z) - => InBounds(x, z) && _storageZone[x - MinX, z - MinZ]; - - public void AddRoom(SpatialRoomSummary room) - { - if (room == null) return; - Rooms.Add(room); - _roomMap[room.RoomId] = room; - } - - public bool TryGetRoom(int roomId, out SpatialRoomSummary room) - => _roomMap.TryGetValue(roomId, out room!); - } - + /// + /// Scores and ranks candidate placement coordinates inside a + /// using room affinity, wall/door adjacency, interaction-cell passability, and peer clustering heuristics. + /// public static class ColonySpatialClusterSolver { public static SpatialBuildingCategory ClassifyBuilding( @@ -154,35 +16,14 @@ public static SpatialBuildingCategory ClassifyBuilding( bool isTable = false, bool isJoy = false, bool isDefense = false) - { - if (isBed) return SpatialBuildingCategory.Sleeping; - if (isWorkTable) return SpatialBuildingCategory.Production; - if (isTable || isJoy) return SpatialBuildingCategory.DiningRecreation; - if (isDefense) return SpatialBuildingCategory.Defense; - - string key = (defName ?? string.Empty).Trim().ToLowerInvariant(); - if (key.Contains("bed") || key.Contains("sleep")) - return SpatialBuildingCategory.Sleeping; - if (key.Contains("stove") || key.Contains("bench") || key.Contains("table_") - || key.Contains("butcher") || key.Contains("research") || key.Contains("smith") - || key.Contains("tailor") || key.Contains("machining") || key.Contains("fabrication") - || key.Contains("brewery") || key.Contains("stonecutter")) - return SpatialBuildingCategory.Production; - if (key.Contains("table") || key.Contains("chair") || key.Contains("stool") - || key.Contains("horseshoe") || key.Contains("chess") || key.Contains("poker")) - return SpatialBuildingCategory.DiningRecreation; - if (key.Contains("cooler") || key.Contains("heater") || key.Contains("campfire") - || key.Contains("torch") || key.Contains("lamp") || key.Contains("brazier")) - return SpatialBuildingCategory.TemperatureLight; - if (key.Contains("shelf") || key.Contains("storage") || key.Contains("hopper")) - return SpatialBuildingCategory.Storage; - if (key.Contains("turret") || key.Contains("sandbag") || key.Contains("barricade") || key.Contains("trap")) - return SpatialBuildingCategory.Defense; - if (key.Contains("wall") || key.Contains("door")) - return SpatialBuildingCategory.Structure; - - return SpatialBuildingCategory.General; - } + => SpatialBuildingClassifier.Classify(defName, isBed, isWorkTable, isTable, isJoy, isDefense); + + public static string RenderCompactAsciiGrid( + ColonySpatialSnapshot snapshot, + int centerX, + int centerZ, + int radius = 10) + => SpatialAsciiRenderer.RenderCompactAsciiGrid(snapshot, centerX, centerZ, radius); public static List RankCandidates( ColonySpatialSnapshot snapshot, @@ -194,6 +35,8 @@ public static List RankCandidates( int sizeX = Math.Max(1, request.SizeX); int sizeZ = Math.Max(1, request.SizeZ); + int minOffX = request.FootprintMinOffsetX; + int minOffZ = request.FootprintMinOffsetZ; string hint = (request.LocationHint ?? "near_base").Trim().ToLowerInvariant(); int targetX = hint == "near_pawn" || !snapshot.HasBaseAnchor @@ -209,7 +52,10 @@ public static List RankCandidates( { for (int z = snapshot.MinZ; z <= snapshot.MaxZ; z++) { - if (!IsFootprintFree(snapshot, x, z, sizeX, sizeZ)) + int fpMinX = x + minOffX; + int fpMinZ = z + minOffZ; + + if (!IsFootprintFree(snapshot, fpMinX, fpMinZ, sizeX, sizeZ)) continue; if (request.HasInteractionCell) @@ -223,7 +69,8 @@ public static List RankCandidates( if (extraValidator != null && !extraValidator(x, z)) continue; - SpatialCandidateScore scored = ScoreCandidate(snapshot, request, hint, x, z, sizeX, sizeZ, targetX, targetZ); + SpatialCandidateScore scored = ScoreCandidate( + snapshot, request, hint, x, z, fpMinX, fpMinZ, sizeX, sizeZ, targetX, targetZ); candidates.Add(scored); } } @@ -243,13 +90,13 @@ public static List RankCandidates( return candidates; } - private static bool IsFootprintFree(ColonySpatialSnapshot snapshot, int x, int z, int sizeX, int sizeZ) + private static bool IsFootprintFree(ColonySpatialSnapshot snapshot, int minX, int minZ, int sizeX, int sizeZ) { for (int dx = 0; dx < sizeX; dx++) { for (int dz = 0; dz < sizeZ; dz++) { - SpatialCellKind kind = snapshot.GetCellKind(x + dx, z + dz); + SpatialCellKind kind = snapshot.GetCellKind(minX + dx, minZ + dz); if (kind != SpatialCellKind.IndoorRoom && kind != SpatialCellKind.OutdoorFloor) return false; } @@ -266,6 +113,8 @@ private static SpatialCandidateScore ScoreCandidate( string hint, int x, int z, + int fpMinX, + int fpMinZ, int sizeX, int sizeZ, int targetX, @@ -278,8 +127,8 @@ private static SpatialCandidateScore ScoreCandidate( bool isRoofed = snapshot.IsRoofed(x, z); bool inStorage = snapshot.IsStorageZone(x, z); - int adjWalls = CountAdjacentKind(snapshot, x, z, sizeX, sizeZ, SpatialCellKind.Wall); - int adjDoors = CountAdjacentKind(snapshot, x, z, sizeX, sizeZ, SpatialCellKind.Door); + int adjWalls = CountAdjacentKind(snapshot, fpMinX, fpMinZ, sizeX, sizeZ, SpatialCellKind.Wall); + int adjDoors = CountAdjacentKind(snapshot, fpMinX, fpMinZ, sizeX, sizeZ, SpatialCellKind.Door); double score = 0d; string reason = "open_ground"; @@ -332,7 +181,42 @@ private static SpatialCandidateScore ScoreCandidate( if (inStorage && request.Category != SpatialBuildingCategory.Storage) score -= 18d; - if (request.Category == SpatialBuildingCategory.Sleeping) + score += ScoreCategoryAffinity(snapshot, request.Category, room, inEnclosedRoom, adjWalls, x, z, ref reason); + + if (hint == "near_pawn") + { + int pawnDist = Math.Abs(x - request.AnchorX) + Math.Abs(z - request.AnchorZ); + score -= pawnDist * 1.2d; + } + else + { + int anchorDist = Math.Abs(x - targetX) + Math.Abs(z - targetZ); + score -= anchorDist * 0.45d; + } + + return new SpatialCandidateScore + { + X = x, + Z = z, + Score = score, + RoomId = roomId, + Reason = reason + }; + } + + private static double ScoreCategoryAffinity( + ColonySpatialSnapshot snapshot, + SpatialBuildingCategory category, + SpatialRoomSummary? room, + bool inEnclosedRoom, + int adjWalls, + int x, + int z, + ref string reason) + { + double score = 0d; + + if (category == SpatialBuildingCategory.Sleeping) { if (room != null && room.IsEnclosed) { @@ -361,7 +245,7 @@ private static SpatialCandidateScore ScoreCandidate( score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.Sleeping, x, z, maxDist: 4, bonus: 22d); } - else if (request.Category == SpatialBuildingCategory.Production) + else if (category == SpatialBuildingCategory.Production) { if (room != null && room.IsEnclosed && room.WorktableCount > 0) { @@ -379,7 +263,7 @@ private static SpatialCandidateScore ScoreCandidate( score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.Production, x, z, maxDist: 5, bonus: 20d); score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.Storage, x, z, maxDist: 6, bonus: 12d); } - else if (request.Category == SpatialBuildingCategory.DiningRecreation) + else if (category == SpatialBuildingCategory.DiningRecreation) { if (room != null && room.IsEnclosed && room.TableCount > 0) { @@ -390,7 +274,7 @@ private static SpatialCandidateScore ScoreCandidate( score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.DiningRecreation, x, z, maxDist: 4, bonus: 20d); score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.Production, x, z, maxDist: 7, bonus: 8d); } - else if (request.Category == SpatialBuildingCategory.Storage) + else if (category == SpatialBuildingCategory.Storage) { if (inEnclosedRoom) { @@ -400,7 +284,7 @@ private static SpatialCandidateScore ScoreCandidate( if (adjWalls >= 1) score += 10d; score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.Storage, x, z, maxDist: 4, bonus: 20d); } - else if (request.Category == SpatialBuildingCategory.TemperatureLight) + else if (category == SpatialBuildingCategory.TemperatureLight) { if (inEnclosedRoom) { @@ -413,25 +297,7 @@ private static SpatialCandidateScore ScoreCandidate( } } - if (hint == "near_pawn") - { - int pawnDist = Math.Abs(x - request.AnchorX) + Math.Abs(z - request.AnchorZ); - score -= pawnDist * 1.2d; - } - else - { - int anchorDist = Math.Abs(x - targetX) + Math.Abs(z - targetZ); - score -= anchorDist * 0.45d; - } - - return new SpatialCandidateScore - { - X = x, - Z = z, - Score = score, - RoomId = roomId, - Reason = reason - }; + return score; } private static double PeerClusterBonus( @@ -458,8 +324,8 @@ private static double PeerClusterBonus( private static int CountAdjacentKind( ColonySpatialSnapshot snapshot, - int x, - int z, + int minX, + int minZ, int sizeX, int sizeZ, SpatialCellKind targetKind) @@ -467,81 +333,15 @@ private static int CountAdjacentKind( int count = 0; for (int dx = 0; dx < sizeX; dx++) { - if (snapshot.GetCellKind(x + dx, z - 1) == targetKind) count++; - if (snapshot.GetCellKind(x + dx, z + sizeZ) == targetKind) count++; + if (snapshot.GetCellKind(minX + dx, minZ - 1) == targetKind) count++; + if (snapshot.GetCellKind(minX + dx, minZ + sizeZ) == targetKind) count++; } for (int dz = 0; dz < sizeZ; dz++) { - if (snapshot.GetCellKind(x - 1, z + dz) == targetKind) count++; - if (snapshot.GetCellKind(x + sizeX, z + dz) == targetKind) count++; + if (snapshot.GetCellKind(minX - 1, minZ + dz) == targetKind) count++; + if (snapshot.GetCellKind(minX + sizeX, minZ + dz) == targetKind) count++; } return count; } - - public static string RenderCompactAsciiGrid( - ColonySpatialSnapshot snapshot, - int centerX, - int centerZ, - int radius = 10) - { - if (snapshot == null) return string.Empty; - int clampedRadius = Math.Max(2, Math.Min(16, radius)); - var sb = new StringBuilder(); - sb.Append("Center=(").Append(centerX).Append(',').Append(centerZ).Append(") r=").Append(clampedRadius) - .AppendLine(" Legend: #=Wall +=Door B=Bed W=Work T=Table S=Storage *=Blueprint .=Indoor ,=Outdoor X=Blocked @=Center"); - - var peerGlyph = new Dictionary(); - for (int i = 0; i < snapshot.Peers.Count; i++) - { - SpatialPeerItem p = snapshot.Peers[i]; - char g = p.IsBlueprint ? '*' : p.Category switch - { - SpatialBuildingCategory.Sleeping => 'B', - SpatialBuildingCategory.Production => 'W', - SpatialBuildingCategory.DiningRecreation => 'T', - SpatialBuildingCategory.Storage => 'S', - _ => 'O' - }; - peerGlyph[PackCoord(p.X, p.Z)] = g; - } - - for (int z = centerZ + clampedRadius; z >= centerZ - clampedRadius; z--) - { - sb.Append(z.ToString().PadLeft(3)).Append("| "); - for (int x = centerX - clampedRadius; x <= centerX + clampedRadius; x++) - { - if (peerGlyph.TryGetValue(PackCoord(x, z), out char g)) - { - sb.Append(g); - continue; - } - - if (x == centerX && z == centerZ) - { - sb.Append('@'); - continue; - } - - SpatialCellKind kind = snapshot.GetCellKind(x, z); - char ch = kind switch - { - SpatialCellKind.Wall => '#', - SpatialCellKind.Door => '+', - SpatialCellKind.Blueprint => '*', - SpatialCellKind.OccupiedFurniture => 'O', - SpatialCellKind.IndoorRoom => '.', - SpatialCellKind.OutdoorFloor => snapshot.IsStorageZone(x, z) ? 'S' : ',', - SpatialCellKind.Impassable => 'X', - _ => ' ' - }; - sb.Append(ch); - } - sb.AppendLine(); - } - - return sb.ToString().TrimEnd(); - } - - private static long PackCoord(int x, int z) => (((long)x) << 32) | (uint)z; } } diff --git a/Source/Spatial/SpatialAsciiRenderer.cs b/Source/Spatial/SpatialAsciiRenderer.cs new file mode 100644 index 0000000..2f14f05 --- /dev/null +++ b/Source/Spatial/SpatialAsciiRenderer.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace RimMind.Actions.Spatial +{ + /// + /// Renders a compact ASCII top-down map of a for LLM prompts and diagnostics. + /// + public static class SpatialAsciiRenderer + { + public static string RenderCompactAsciiGrid( + ColonySpatialSnapshot? snapshot, + int centerX, + int centerZ, + int radius = 10) + { + if (snapshot == null) return string.Empty; + int clampedRadius = Math.Max(2, Math.Min(16, radius)); + var sb = new StringBuilder(); + sb.Append("Center=(").Append(centerX).Append(',').Append(centerZ).Append(") r=").Append(clampedRadius) + .AppendLine(" Legend: #=Wall +=Door B=Bed W=Work T=Table S=Storage *=Blueprint .=Indoor ,=Outdoor X=Blocked @=Center"); + + var peerGlyph = new Dictionary(); + for (int i = 0; i < snapshot.Peers.Count; i++) + { + SpatialPeerItem p = snapshot.Peers[i]; + char g = p.IsBlueprint ? '*' : p.Category switch + { + SpatialBuildingCategory.Sleeping => 'B', + SpatialBuildingCategory.Production => 'W', + SpatialBuildingCategory.DiningRecreation => 'T', + SpatialBuildingCategory.Storage => 'S', + _ => 'O' + }; + peerGlyph[PackCoord(p.X, p.Z)] = g; + } + + for (int z = centerZ + clampedRadius; z >= centerZ - clampedRadius; z--) + { + sb.Append(z.ToString().PadLeft(3)).Append("| "); + for (int x = centerX - clampedRadius; x <= centerX + clampedRadius; x++) + { + if (peerGlyph.TryGetValue(PackCoord(x, z), out char g)) + { + sb.Append(g); + continue; + } + + if (x == centerX && z == centerZ) + { + sb.Append('@'); + continue; + } + + SpatialCellKind kind = snapshot.GetCellKind(x, z); + char ch = kind switch + { + SpatialCellKind.Wall => '#', + SpatialCellKind.Door => '+', + SpatialCellKind.Blueprint => '*', + SpatialCellKind.OccupiedFurniture => 'O', + SpatialCellKind.IndoorRoom => '.', + SpatialCellKind.OutdoorFloor => snapshot.IsStorageZone(x, z) ? 'S' : ',', + SpatialCellKind.Impassable => 'X', + _ => ' ' + }; + sb.Append(ch); + } + sb.AppendLine(); + } + + return sb.ToString().TrimEnd(); + } + + private static long PackCoord(int x, int z) => (((long)x) << 32) | (uint)z; + } +} diff --git a/Source/Spatial/SpatialBuildingClassifier.cs b/Source/Spatial/SpatialBuildingClassifier.cs new file mode 100644 index 0000000..0686c5c --- /dev/null +++ b/Source/Spatial/SpatialBuildingClassifier.cs @@ -0,0 +1,45 @@ +namespace RimMind.Actions.Spatial +{ + /// + /// Classifies buildings into semantic spatial categories for peer-clustering and room-affinity heuristics. + /// + public static class SpatialBuildingClassifier + { + public static SpatialBuildingCategory Classify( + string? defName, + bool isBed = false, + bool isWorkTable = false, + bool isTable = false, + bool isJoy = false, + bool isDefense = false) + { + if (isBed) return SpatialBuildingCategory.Sleeping; + if (isWorkTable) return SpatialBuildingCategory.Production; + if (isTable || isJoy) return SpatialBuildingCategory.DiningRecreation; + if (isDefense) return SpatialBuildingCategory.Defense; + + string key = (defName ?? string.Empty).Trim().ToLowerInvariant(); + if (key.Contains("bed") || key.Contains("sleep")) + return SpatialBuildingCategory.Sleeping; + if (key.Contains("stove") || key.Contains("bench") || key.Contains("table_") + || key.Contains("butcher") || key.Contains("research") || key.Contains("smith") + || key.Contains("tailor") || key.Contains("machining") || key.Contains("fabrication") + || key.Contains("brewery") || key.Contains("stonecutter")) + return SpatialBuildingCategory.Production; + if (key.Contains("table") || key.Contains("chair") || key.Contains("stool") + || key.Contains("horseshoe") || key.Contains("chess") || key.Contains("poker")) + return SpatialBuildingCategory.DiningRecreation; + if (key.Contains("cooler") || key.Contains("heater") || key.Contains("campfire") + || key.Contains("torch") || key.Contains("lamp") || key.Contains("brazier")) + return SpatialBuildingCategory.TemperatureLight; + if (key.Contains("shelf") || key.Contains("storage") || key.Contains("hopper")) + return SpatialBuildingCategory.Storage; + if (key.Contains("turret") || key.Contains("sandbag") || key.Contains("barricade") || key.Contains("trap")) + return SpatialBuildingCategory.Defense; + if (key.Contains("wall") || key.Contains("door")) + return SpatialBuildingCategory.Structure; + + return SpatialBuildingCategory.General; + } + } +} diff --git a/Source/Spatial/SpatialGridModels.cs b/Source/Spatial/SpatialGridModels.cs new file mode 100644 index 0000000..4ba8221 --- /dev/null +++ b/Source/Spatial/SpatialGridModels.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; + +namespace RimMind.Actions.Spatial +{ + public enum SpatialCellKind + { + OutOfBounds = 0, + Impassable = 1, + Wall = 2, + Door = 3, + OutdoorFloor = 4, + IndoorRoom = 5, + OccupiedFurniture = 6, + Blueprint = 7 + } + + public enum SpatialBuildingCategory + { + General = 0, + Sleeping = 1, + Production = 2, + DiningRecreation = 3, + TemperatureLight = 4, + Storage = 5, + Defense = 6, + Structure = 7 + } + + public sealed class SpatialRoomSummary + { + public int RoomId { get; set; } + public string Role { get; set; } = "Indoor"; + public int CellCount { get; set; } + public int BedCount { get; set; } + public int WorktableCount { get; set; } + public int TableCount { get; set; } + public int CenterX { get; set; } + public int CenterZ { get; set; } + public bool IsEnclosed { get; set; } + } + + public sealed class SpatialPeerItem + { + public string DefName { get; set; } = string.Empty; + public SpatialBuildingCategory Category { get; set; } + public int X { get; set; } + public int Z { get; set; } + public int RoomId { get; set; } + public bool IsBlueprint { get; set; } + } + + public sealed class SpatialPlacementRequest + { + public string BuildingDefName { get; set; } = string.Empty; + public SpatialBuildingCategory Category { get; set; } + public int SizeX { get; set; } = 1; + public int SizeZ { get; set; } = 1; + /// + /// Offset from the candidate placement anchor (x, z) to the minimum X/Z corner of the building footprint. + /// Defaults to 0 (bottom-left anchored); RimWorld center-anchored footprints set this from GenAdj.OccupiedRect. + /// + public int FootprintMinOffsetX { get; set; } + public int FootprintMinOffsetZ { get; set; } + public bool HasInteractionCell { get; set; } + public int InteractionOffsetX { get; set; } + public int InteractionOffsetZ { get; set; } + public string LocationHint { get; set; } = "near_base"; + public int AnchorX { get; set; } + public int AnchorZ { get; set; } + } + + public sealed class SpatialCandidateScore + { + public int X { get; set; } + public int Z { get; set; } + public double Score { get; set; } + public int RoomId { get; set; } + public string Reason { get; set; } = string.Empty; + } + + public sealed class ColonySpatialSnapshot + { + private readonly SpatialCellKind[,] _cells; + private readonly int[,] _roomIds; + private readonly bool[,] _roofed; + private readonly bool[,] _storageZone; + private readonly Dictionary _roomMap = new Dictionary(); + + public ColonySpatialSnapshot(int minX, int minZ, int width, int height) + { + MinX = minX; + MinZ = minZ; + Width = Math.Max(1, width); + Height = Math.Max(1, height); + _cells = new SpatialCellKind[Width, Height]; + _roomIds = new int[Width, Height]; + _roofed = new bool[Width, Height]; + _storageZone = new bool[Width, Height]; + } + + public int MinX { get; } + public int MinZ { get; } + public int Width { get; } + public int Height { get; } + public int MaxX => MinX + Width - 1; + public int MaxZ => MinZ + Height - 1; + + public int ColonyAnchorX { get; set; } + public int ColonyAnchorZ { get; set; } + public bool HasBaseAnchor { get; set; } + + public List Rooms { get; } = new List(); + public List Peers { get; } = new List(); + + public bool InBounds(int x, int z) + => x >= MinX && x <= MaxX && z >= MinZ && z <= MaxZ; + + public void SetCell(int x, int z, SpatialCellKind kind, int roomId = 0, bool roofed = false, bool storageZone = false) + { + if (!InBounds(x, z)) return; + int ix = x - MinX; + int iz = z - MinZ; + _cells[ix, iz] = kind; + _roomIds[ix, iz] = roomId; + _roofed[ix, iz] = roofed; + _storageZone[ix, iz] = storageZone; + } + + public SpatialCellKind GetCellKind(int x, int z) + => InBounds(x, z) ? _cells[x - MinX, z - MinZ] : SpatialCellKind.OutOfBounds; + + public int GetRoomId(int x, int z) + => InBounds(x, z) ? _roomIds[x - MinX, z - MinZ] : 0; + + public bool IsRoofed(int x, int z) + => InBounds(x, z) && _roofed[x - MinX, z - MinZ]; + + public bool IsStorageZone(int x, int z) + => InBounds(x, z) && _storageZone[x - MinX, z - MinZ]; + + public void AddRoom(SpatialRoomSummary room) + { + if (room == null) return; + Rooms.Add(room); + _roomMap[room.RoomId] = room; + } + + public bool TryGetRoom(int roomId, out SpatialRoomSummary room) + => _roomMap.TryGetValue(roomId, out room!); + } +} diff --git a/Tests/ColonySpatialClusterSolverTests.cs b/Tests/ColonySpatialClusterSolverTests.cs index fd28593..fbe1e24 100644 --- a/Tests/ColonySpatialClusterSolverTests.cs +++ b/Tests/ColonySpatialClusterSolverTests.cs @@ -183,5 +183,37 @@ public void Outdoor_location_hint_and_ascii_grid_renderer_work_deterministically Assert.Contains("B", grid); Assert.Contains("@", grid); } + + [Fact] + public void CenterAnchored_MultiCell_Footprint_Rejects_Cells_Whose_Offset_Corners_Overlap_Walls() + { + ColonySpatialSnapshot snapshot = BuildBedroomAndWorkshopSnapshot(); + // 3x1 center-anchored workbench (occupied x-1..x+1): must never choose x=17 (adjacent to left wall x=16) or x=21 (adjacent to right wall x=22) + var request = new SpatialPlacementRequest + { + BuildingDefName = "FueledStove", + Category = SpatialBuildingCategory.Production, + SizeX = 3, + SizeZ = 1, + FootprintMinOffsetX = -1, + FootprintMinOffsetZ = 0, + HasInteractionCell = true, + InteractionOffsetX = 0, + InteractionOffsetZ = -1, + LocationHint = "indoor", + AnchorX = 19, + AnchorZ = 12 + }; + + List ranked = ColonySpatialClusterSolver.RankCandidates(snapshot, request); + Assert.NotEmpty(ranked); + foreach (var candidate in ranked) + { + if (candidate.RoomId == 2) + { + Assert.InRange(candidate.X, 18, 20); + } + } + } } } diff --git a/Tests/CompositeToolRegistrationTests.cs b/Tests/CompositeToolRegistrationTests.cs index 5993c96..27cf3b7 100644 --- a/Tests/CompositeToolRegistrationTests.cs +++ b/Tests/CompositeToolRegistrationTests.cs @@ -49,5 +49,19 @@ namespace RimMind.Presentation.Api public static class RimMindAPI { public static RimMind.Application.Common.Interfaces.Tools.IToolRegistry Tools { get; set; } = null!; + + public static class Autonomy + { + public static RimMind.Domain.Agent.Policies.AutonomyLevel GetLevel( + Verse.Pawn? pawn, + RimMind.Domain.Agent.Policies.AutonomyDomain domain) + => RimMind.Domain.Agent.Policies.AutonomyLevel.FullAutonomous; + } + } + + public static class RimMindPawnLookup + { + public static Verse.Pawn? FindPawnByNumber(int pawnId) => null; + public static bool IsActiveSpawnedColonist(Verse.Pawn? pawn) => pawn != null; } } diff --git a/Tests/CompositeToolSelfDescriptionContracts.cs b/Tests/CompositeToolSelfDescriptionContracts.cs index 43deeb4..9e1fd51 100644 --- a/Tests/CompositeToolSelfDescriptionContracts.cs +++ b/Tests/CompositeToolSelfDescriptionContracts.cs @@ -44,11 +44,14 @@ public void All_11_CompositeTools_Declare_RimMindActions_Owner_Valid_Domains_And Assert.False(string.IsNullOrWhiteSpace(manifest.DisplayName), $"Tool '{tool.Id}' must declare DisplayName"); Assert.NotEmpty(manifest.Aliases); Assert.NotEmpty(manifest.SummaryArgKeys); + Assert.True(manifest.Scopes.HasValue && manifest.Scopes.Value != ToolScope.None, + $"Tool '{tool.Id}' must declare explicit ToolScopes"); if (tool is QueryBuildableStructuresCompositeTool) { Assert.Equal(ToolKind.Query, manifest.Kind); Assert.Null(manifest.DefaultDomain); + Assert.Equal(ToolScope.ColonyBuild | ToolScope.ColonyManage, manifest.Scopes); } else { diff --git a/Tests/DesignateResourcesToolTests.cs b/Tests/DesignateResourcesToolTests.cs index c98b345..ad6de42 100644 --- a/Tests/DesignateResourcesToolTests.cs +++ b/Tests/DesignateResourcesToolTests.cs @@ -51,6 +51,18 @@ public void DesignateResources_Supports_Harvest_ChopWood_And_Mine() Assert.Contains("DesignationDefOf.CutPlant", source); Assert.Contains("DesignationDefOf.Mine", source); Assert.Contains("AddDesignation", source); + Assert.Contains("MatchesTargetFilter", source); + } + + [Fact] + public void No_CompositeTool_Mutates_Player_WorkPriorities_Via_SetPriority() + { + var actionsDir = Path.Combine(RepoRoot, "RimMind-Actions", "Source", "Actions"); + foreach (var file in Directory.GetFiles(actionsDir, "*.cs")) + { + var source = File.ReadAllText(file); + Assert.DoesNotContain(".SetPriority(", source); + } } } } diff --git a/Tests/PlaceBlueprintCompositeToolTests.cs b/Tests/PlaceBlueprintCompositeToolTests.cs index 88a85c4..2fecfaa 100644 --- a/Tests/PlaceBlueprintCompositeToolTests.cs +++ b/Tests/PlaceBlueprintCompositeToolTests.cs @@ -44,15 +44,18 @@ public void PlaceBlueprint_Handles_Missing_BuildingDef_Validation() } [Fact] - public void PlaceBlueprint_Integrates_AgentIntentSession_Chaining() + public void PlaceBlueprint_Integrates_Shared_ConstructionIntentChainer_And_Real_Footprint() { var source = ReadActionsSource(Path.Combine("Actions", "PlaceBlueprintCompositeTool.cs")); - Assert.Contains("RimMindAPI.Agent.StartIntentSession", source); + var chainerSource = ReadActionsSource(Path.Combine("Actions", "ConstructionIntentChainer.cs")); Assert.DoesNotContain("using RimMind.Infrastructure", source); - Assert.Contains("IssueConstructionSubJob(p, map, blueprint, targetCell)", source); - Assert.Contains("targetCell.GetThingList(map).OfType().Any(f => !f.Destroyed && f.Spawned)", source); - Assert.Contains("WorkGiver_ConstructDeliverResourcesToFrames", source); - Assert.Contains("StartIntentSession", source); + Assert.DoesNotContain("using RimMind.Infrastructure", chainerSource); + Assert.Contains("ConstructionIntentChainer.TryChainSingleBlueprint", source); + Assert.Contains("RimMindAPI.Agent.StartIntentSession", chainerSource); + Assert.Contains("WorkGiver_ConstructDeliverResourcesToFrames", chainerSource); + Assert.Contains("GenAdj.OccupiedRect(IntVec3.Zero, candidateRot, def.Size)", source); + Assert.Contains("HasInteractionCell = def.hasInteractionCell", source); + Assert.DoesNotContain("IsEssentialSurvivalStructure", source); } [Fact] diff --git a/Tests/PlanRoomProjectToolTests.cs b/Tests/PlanRoomProjectToolTests.cs index 6527bfa..cb20748 100644 --- a/Tests/PlanRoomProjectToolTests.cs +++ b/Tests/PlanRoomProjectToolTests.cs @@ -51,15 +51,17 @@ public void PlanRoomProject_Integrates_ResourceSafetyGuard() } [Fact] - public void PlanRoomProject_Chains_AgentIntentSession() + public void PlanRoomProject_Chains_Shared_ConstructionIntentChainer() { var source = ReadActionsSource(Path.Combine("Actions", "PlanRoomProjectCompositeTool.cs")); - Assert.Contains("RimMindAPI.Agent.StartIntentSession", source); + var chainerSource = ReadActionsSource(Path.Combine("Actions", "ConstructionIntentChainer.cs")); Assert.DoesNotContain("using RimMind.Infrastructure", source); - Assert.Contains("StartIntentSession", source); + Assert.DoesNotContain("using RimMind.Infrastructure", chainerSource); + Assert.Contains("ConstructionIntentChainer.TryChainProject", source); + Assert.Contains("RimMindAPI.Agent.StartIntentSession", chainerSource); Assert.Contains("PlaceBlueprintForBuild", source); Assert.Contains("targetCells", source); - Assert.Contains("WorkGiver_ConstructDeliverResourcesToFrames", source); + Assert.Contains("WorkGiver_ConstructDeliverResourcesToFrames", chainerSource); Assert.Contains("GenRadial.RadialCellsAround(origin, 30f, true)", source); Assert.DoesNotContain("for (int r = 4; r <= 30; r += 2)", source); } diff --git a/Tests/QueryBuildableStructuresCompositeToolTests.cs b/Tests/QueryBuildableStructuresCompositeToolTests.cs index 45739b7..077b428 100644 --- a/Tests/QueryBuildableStructuresCompositeToolTests.cs +++ b/Tests/QueryBuildableStructuresCompositeToolTests.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.IO; +using RimMind.Actions.Policies; using Xunit; namespace RimMind.Actions.Tests @@ -49,15 +51,101 @@ public void QueryBuildableStructures_Contains_Bottleneck_Detection_For_Beds_And_ } [Fact] - public void QueryBuildableStructures_Provides_Curated_Structure_Entries() + public void QueryBuildableStructures_Uses_Dynamic_DefDatabase_Discovery_Instead_Of_Hardcoded_List() { var source = ReadActionsSource(Path.Combine("Actions", "QueryBuildableStructuresCompositeTool.cs")); - Assert.Contains("GetCuratedStructures", source); - Assert.Contains("Bed", source); - Assert.Contains("PassiveCooler", source); - Assert.Contains("FueledStove", source); - Assert.Contains("HorseshoePin", source); - Assert.Contains("PenMarker", source); + Assert.Contains("DefDatabase.AllDefsListForReading", source); + Assert.Contains("BuildableByPlayer", source); + Assert.Contains("IsResearchFinished", source); + Assert.Contains("BuildableStructureCatalogPolicy.FilterAndProject", source); + Assert.DoesNotContain("GetCuratedStructures", source); + Assert.DoesNotContain("\"HorseshoePin\"", source); + Assert.DoesNotContain("\"ResearchBench\"", source); + } + + [Fact] + public void BuildableStructureCatalogPolicy_Classifies_Vanilla_And_Modded_Buildings_Accurately() + { + Assert.Equal("production", BuildableStructureCatalogPolicy.ClassifyCategory("Production", "SimpleResearchBench", isWorkTable: true)); + Assert.Equal("recreation", BuildableStructureCatalogPolicy.ClassifyCategory("Joy", "HorseshoesPin", isJoy: true)); + Assert.Equal("furniture", BuildableStructureCatalogPolicy.ClassifyCategory("Furniture", "Bed", isBed: true)); + Assert.Equal("temperature", BuildableStructureCatalogPolicy.ClassifyCategory("Temperature", "PassiveCooler", isTempControl: true)); + Assert.Equal("livestock", BuildableStructureCatalogPolicy.ClassifyCategory("Structure", "PenMarker", isFenceOrPen: true)); + Assert.Equal("production", BuildableStructureCatalogPolicy.ClassifyCategory("Production", "Modded_AutoSmelter", isWorkTable: true)); + Assert.Equal("power", BuildableStructureCatalogPolicy.ClassifyCategory("Power", "Modded_SolarTurbine", generatesPower: true)); + } + + [Fact] + public void BuildableStructureCatalogPolicy_Filters_FormatsCosts_And_EvaluatesAffordability() + { + var stock = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["WoodLog"] = 120, + ["Steel"] = 30, + ["ComponentIndustrial"] = 1 + }; + + var descriptors = new[] + { + new BuildableStructureDescriptor + { + DefName = "SimpleResearchBench", + Label = "simple research bench", + Category = "production", + CostStuffCount = 75, + BestStuffLabel = "WoodLog", + BestStuffAvailable = 120, + FixedCosts = new[] { new BuildableMaterialCost("Steel", "Steel", 25) }, + Purpose = "A simple bench with writing implements and low-tech scientific tools." + }, + new BuildableStructureDescriptor + { + DefName = "HorseshoesPin", + Label = "horseshoes pin", + Category = "recreation", + CostStuffCount = 10, + BestStuffLabel = "WoodLog", + BestStuffAvailable = 120, + Purpose = "A simple ancient game played with a few horseshoes and a large pin stuck in the ground." + }, + new BuildableStructureDescriptor + { + DefName = "Modded_ArcFurnace", + Label = "arc furnace", + Category = "production", + RequiresPower = true, + FixedCosts = new[] + { + new BuildableMaterialCost("Steel", "Steel", 150), + new BuildableMaterialCost("ComponentIndustrial", "ComponentIndustrial", 4) + }, + Purpose = "Modded high-speed electric smelter." + } + }; + + var production = BuildableStructureCatalogPolicy.FilterAndProject( + descriptors, + "production", + def => stock.TryGetValue(def, out int c) ? c : 0); + + Assert.Equal(2, production.Count); + // Affordable structure ranks first + Assert.Equal("SimpleResearchBench", production[0].DefName); + Assert.True(production[0].CanAfford); + Assert.Equal("75 WoodLog + 25 Steel", production[0].CostSummary); + + Assert.Equal("Modded_ArcFurnace", production[1].DefName); + Assert.False(production[1].CanAfford); + Assert.True(production[1].RequiresPower); + Assert.Equal("150 Steel + 4 ComponentIndustrial", production[1].CostSummary); + + var rec = BuildableStructureCatalogPolicy.FilterAndProject( + descriptors, + "recreation", + def => stock.TryGetValue(def, out int c) ? c : 0); + Assert.Single(rec); + Assert.Equal("HorseshoesPin", rec[0].DefName); + Assert.True(rec[0].CanAfford); } } } diff --git a/Tests/RimMindActions.Tests.csproj b/Tests/RimMindActions.Tests.csproj index 769ed6f..d1abac7 100644 --- a/Tests/RimMindActions.Tests.csproj +++ b/Tests/RimMindActions.Tests.csproj @@ -19,6 +19,7 @@ + @@ -33,12 +34,15 @@ + + +