From 4a36df461a05ea63aa512a1ae656a23d7a57cd0e Mon Sep 17 00:00:00 2001 From: mcocdaa <2021137961@qq.com> Date: Sat, 7 Nov 2026 09:02:49 +0100 Subject: [PATCH 1/2] feat(release): prepare v2.0.0-rc.1 with Steam feedback fixes and BBCode About.xml docs(about): expand mod description with full feature and catalog overview Replace the short description with a detailed Steam-style description covering v2.0 architecture, the sub-mod dependency table, composite action catalog, risk grading, and FAQ. Also exclude dev-only files (.coderabbit.yaml, .pre-commit-config.yaml, INTRODUCTION.txt) from the release package. --- .github/workflows/release.yml | 3 ++ About/About.xml | 70 ++++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 821f5de..ff77b3a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -171,6 +171,9 @@ jobs: --exclude='docs/' \ --exclude='*.csproj' \ --exclude='*.sln' \ + --exclude='.coderabbit.yaml' \ + --exclude='.pre-commit-config.yaml' \ + --exclude='INTRODUCTION.txt' \ --exclude='.gitignore' \ --exclude='.gitattributes' \ --exclude='*.md' \ diff --git a/About/About.xml b/About/About.xml index da555ad..747f1ed 100644 --- a/About/About.xml +++ b/About/About.xml @@ -8,7 +8,75 @@
  • 1.6
  • 1.7
  • - Composite ToolCall orchestration layer. Combines atomic ToolCalls from Core into high-level actions (e.g., stabilize_rest: undraft then force_rest). Registered via reflection. [v2.0] + [h1]RimMind - Actions (v2.0)[/h1] +Composite ToolCall orchestration and tactical emergency execution engine for RimWorld colonists. Translates high-level AI intentions into safe, multi-step in-game operations—covering battlefield triage, autonomous blueprint construction, agricultural cycles, social interactions, and survival responses. + +[b]v2.0 Clean Architecture & RimWorld 1.6 / 1.7 Dual-Version Support:[/b] +[list] +[*][b]RimWorld 1.6 & 1.7 (Waylith / .NET 10) Ready[/b]: Native multi-target compilation supporting both RimWorld 1.6 (.NET Framework 4.8) and RimWorld 1.7 (.NET 10 / Harmony 2.x & 3.x). +[*][b]v2.0 Composite ToolCall Architecture[/b]: Combines atomic Core mechanisms into stateful, multi-stage workflows registered purely through [code]RimMind-Core[/code] public ToolCall contracts. +[*][b]Multi-Stage Job Polling & Safety Gates[/b]: Continuously tracks complex jobs (such as [code]Blueprint_Build[/code] to [code]Frame[/code] delivery and construction) while enforcing strict material reserve and danger-proximity guards. +[/list] + +[h2]What Is RimMind[/h2] +RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with Large Language Models (LLM), it transforms colonists into self-reflecting agents with distinct personalities, three-tier memories, natural spoken dialogues, autonomous mechanisms, and dynamic storytelling. + +[h2]Sub-mod List & Dependency Relationships[/h2] +[table] +[tr][th]Mod[/th][th]Responsibility[/th][th]Dependencies[/th][th]GitHub[/th][/tr] +[tr][td]RimMind-Core[/td][td]LLM runtime, 4-Zone context engine, async queue, ToolCall registry & F8 Hub[/td][td]Harmony[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Core]Link[/url][/td][/tr] +[tr][td][b]RimMind-Actions[/b][/td][td]Composite ToolCall mechanisms, battlefield triage & autonomous construction[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Actions]Link[/url][/td][/tr] +[tr][td]RimMind-Advisor[/td][td]Colonist self-reflective advice cards, 5-domain autonomy & player approval[/td][td]Core, Actions[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Advisor]Link[/url][/td][/tr] +[tr][td]RimMind-Dialogue[/td][td]Contextual spoken dialogue via express_dialogue ToolCall & speech bubbles[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Dialogue]Link[/url][/td][/tr] +[tr][td]RimMind-Memory[/td][td]3-Tier cognitive memory hierarchy, work aggregation & temporal decay[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Memory]Link[/url][/td][/tr] +[tr][td]RimMind-Personality[/td][td]Big-Five psychological profiles, dawn monologues & dynamic mood thoughts[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality]Link[/url][/td][/tr] +[tr][td]RimMind-Storyteller[/td][td]AI Story Director, dramatic tension curve, chained arcs & Storyteller Altar[/td][td]Core, Memory[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Storyteller]Link[/url][/td][/tr] +[tr][td]RimMind-Extension-ModelService[/td][td]Multi-provider routing, Anthropic KV cache, local gateways & load balancing[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Extension-ModelService]Link[/url][/td][/tr] +[tr][td]RimMind-Bridge-RimChat[/td][td]RimChat compatibility bridge: dialogue/action mutual exclusion & context sync[/td][td]Core, RimChat[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimChat]Link[/url][/td][/tr] +[tr][td]RimMind-Bridge-RimTalk[/td][td]RimTalk compatibility bridge: bubble harmonization & bidirectional context[/td][td]Core, RimTalk[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimTalk]Link[/url][/td][/tr] +[/table] +[code]Core ──┬── Actions ── Advisor + ├── Dialogue + ├── Memory ── Storyteller + ├── Personality + ├── Extension-ModelService + ├── Bridge-RimChat + └── Bridge-RimTalk[/code] + +[h2]Core Features[/h2] +[list] +[*][b]10 Built-In Composite Mechanisms[/b] - High-level orchestrated tools covering emergency survival, construction engineering, and agricultural production. +[*][b]ContinuousJobPoller Multi-Stage Lifecycle[/b] - Tracks multi-step Verse job execution across ticks, seamlessly advancing from blueprint placement to material hauling and frame completion. +[*][b]ActionPermissionGuard & ResourceSafetyGuard[/b] - Validates active spawned colonist eligibility, work-type capabilities, hostile threat proximity, and colony resource reserve thresholds before executing any job. +[*][b]Graded Risk Control[/b] - Every action carries an explicit risk classification ([i]Low / Medium / High / Critical[/i]) that integrates directly with Core's 3-Tier Autonomy and Advisor's player approval workflow. +[*][b]Main-Thread Safe Execution[/b] - Dispatches all Verse and Unity side effects safely on the main game thread. +[/list] + +[h2]Composite & Atomic Action Catalog[/h2] +[table] +[tr][th]Category[/th][th]Actions & Mechanisms[/th][/tr] +[tr][td]Emergency & Survival[/td][td]actions.stabilize_rest, actions.emergency_flee, actions.eat_and_recreation, actions.triage_patient, force_rest, eat_food, tend_pawn, rescue_pawn[/td][/tr] +[tr][td]Construction & Engineering[/td][td]actions.place_blueprint, actions.plan_room_project, actions.clear_area_for_build[/td][/tr] +[tr][td]Production & Agriculture[/td][td]actions.designated_harvest, actions.set_work_bill, actions.schedule_farming_cycle, assign_work, set_work_priority[/td][/tr] +[tr][td]Social & Mood[/td][td]social_dining, social_relax, give_item, romance_accept, romance_breakup, inspire_work, add_thought[/td][/tr] +[tr][td]Combat & Tactical[/td][td]draft, undraft, move_to, drop_weapon, cancel_job[/td][/tr] +[/table] + +[h2]Risk Grading System[/h2] +[table] +[tr][th]Risk Level[/th][th]Description[/th][th]Examples[/th][/tr] +[tr][td]Low[/td][td]Easily reversible routine operations[/td][td]move_to, assign_work, cancel_job, undraft[/td][/tr] +[tr][td]Medium[/td][td]Moderate impact on survival, work, or social state[/td][td]stabilize_rest, eat_and_recreation, designated_harvest, social_dining, set_work_bill[/td][/tr] +[tr][td]High[/td][td]Resource-consuming or structural colony changes[/td][td]place_blueprint, plan_room_project, triage_patient, draft, drop_weapon[/td][/tr] +[tr][td]Critical[/td][td]Major colony-wide or irreversible impacts[/td][td]trigger_mental_state, trigger_incident[/td][/tr] +[/table] + +[h2]Frequently Asked Questions[/h2] +[b]Q: Can RimMind-Actions be used standalone?[/b] +A: Actions registers composite tools into [code]RimMind-Core[/code]. Pair it with [code]RimMind-Advisor[/code] so AI colonists can autonomously propose and execute these mechanisms. + +[b]Q: Will AI colonists waste scarce resources on blueprints?[/b] +A: No. [code]ResourceSafetyGuard[/code] verifies colony material reserves before placing blueprints, and high-impact actions respect your approval settings.
  • brrainz.harmony From 02d466029101005db4529804eea0cd9189e72b34 Mon Sep 17 00:00:00 2001 From: mcocdaa Date: Mon, 16 Nov 2026 07:13:23 +0100 Subject: [PATCH 2/2] feat(actions): add colony spatial cluster solver, composite tool fidelity guards, and behavior autotests feat(spatial): add colony spatial cluster solver for blueprint placement Introduce a spatial topology snapshot and clustering solver that ranks blueprint placement candidates by room role, peer-furniture proximity, and wall/door adjacency instead of random spawn-adjacent placement. Expose colony anchor, room summaries, and a compact ASCII grid through the buildable-structures query so the agent can reason about layout. Also: - Add Hunt designation support with safety filters (skip predators, manhunters, large/vengeful animals) and auto-enable Hunting/PlantCutting work priorities; prioritize edible harvest targets. - Make composite tools null-safe on defName/label comparisons and fall back to any capable worktable when a guessed def name is missing. - Route hunger-driven eat-and-recreation to eat_food before resting. - Auto-resolve a doctor and issue rescue/tend jobs in triage, reporting an honest error when no care is possible. - Unify blueprint/room autonomy domain to BlueprintPlacement and add WorkPriorityModification risk mapping. - Extend autotest suite and unit tests for spatial solver, permission gates, and hunt argument adaptation. --- Source/Actions/ActionsToolArgumentAdapter.cs | 7 +- .../Actions/AddWorktableBillCompositeTool.cs | 46 +- Source/Actions/CompositeToolCallBase.cs | 1 + .../DesignateResourcesCompositeTool.cs | 103 +++- .../Actions/EatAndRecreationCompositeTool.cs | 36 +- .../Actions/ManageEquipmentCompositeTool.cs | 5 +- Source/Actions/ManageZoneCompositeTool.cs | 23 +- Source/Actions/PlaceBlueprintCompositeTool.cs | 193 ++++-- .../Actions/PlanRoomProjectCompositeTool.cs | 19 +- .../QueryBuildableStructuresCompositeTool.cs | 35 +- Source/Actions/TriagePatientCompositeTool.cs | 62 +- Source/Debug/ActionsBehaviorAutotestSuite.cs | 154 +++++ Source/Spatial/ColonySpatialClusterSolver.cs | 547 ++++++++++++++++++ Source/Spatial/MapSpatialSnapshotBuilder.cs | 280 +++++++++ Tests/ColonySpatialClusterSolverTests.cs | 187 ++++++ .../CompositeToolSelfDescriptionContracts.cs | 16 +- Tests/PlaceBlueprintCompositeToolTests.cs | 12 + Tests/RimMindActions.Tests.csproj | 2 + 18 files changed, 1618 insertions(+), 110 deletions(-) create mode 100644 Source/Spatial/ColonySpatialClusterSolver.cs create mode 100644 Source/Spatial/MapSpatialSnapshotBuilder.cs create mode 100644 Tests/ColonySpatialClusterSolverTests.cs diff --git a/Source/Actions/ActionsToolArgumentAdapter.cs b/Source/Actions/ActionsToolArgumentAdapter.cs index 87595d1..2358517 100644 --- a/Source/Actions/ActionsToolArgumentAdapter.cs +++ b/Source/Actions/ActionsToolArgumentAdapter.cs @@ -88,8 +88,13 @@ private static void AdaptResourceDesignationArguments(JObject obj) } else if (!obj.ContainsKey("designation_type")) { - obj["designation_type"] = isFoodOrCropTarget ? "Harvest" : "ChopWood"; + obj["designation_type"] = IsHuntTarget(targetStr) ? "Hunt" : (isFoodOrCropTarget ? "Harvest" : "ChopWood"); } } + + private static bool IsHuntTarget(string target) + => target.IndexOf("hunt", StringComparison.OrdinalIgnoreCase) >= 0 + || target.IndexOf("meat", StringComparison.OrdinalIgnoreCase) >= 0 + || target.IndexOf("animal", StringComparison.OrdinalIgnoreCase) >= 0; } } diff --git a/Source/Actions/AddWorktableBillCompositeTool.cs b/Source/Actions/AddWorktableBillCompositeTool.cs index e791099..c5d6611 100644 --- a/Source/Actions/AddWorktableBillCompositeTool.cs +++ b/Source/Actions/AddWorktableBillCompositeTool.cs @@ -48,7 +48,7 @@ public sealed class AddWorktableBillCompositeTool : CompositeToolCallBase Id = Id, Category = "action", Description = "Adds a production bill (e.g. CookMealSimple, ButcherCorpseFlesh, Make_Apparel_Parka) to an available worktable in the colony with target count safety limits and duplicate prevention.", - ParametersSchema = "{\"type\":\"object\",\"properties\":{\"recipe_def\":{\"type\":\"string\",\"description\":\"DefName of the recipe to add (e.g. 'CookMealSimple', 'CookMealFine', 'Make_Apparel_Parka', 'ButcherCorpseFlesh').\"},\"worktable_def\":{\"type\":\"string\",\"description\":\"Optional DefName of the target worktable (e.g. 'TableStoveElectric', 'TableStoveFueled', 'HandTailoringBench', 'TableButcher'). If omitted, searches for any capable player worktable.\"},\"target_count\":{\"type\":\"integer\",\"description\":\"Target inventory stock count or repeat count (default: 10).\"},\"repeat_mode\":{\"type\":\"string\",\"description\":\"Production mode: 'TargetCount' (make until you have X, default) or 'RepeatCount' (make X times).\"},\"pawn_id\":{\"type\":\"integer\",\"description\":\"Optional colonist pawn ID to assign exclusively or anchor permission check.\"}},\"required\":[\"recipe_def\"]}" + ParametersSchema = "{\"type\":\"object\",\"properties\":{\"recipe_def\":{\"type\":\"string\",\"description\":\"DefName of the recipe to add (e.g. 'CookMealSimple', 'CookMealFine', 'Make_Apparel_Parka', 'ButcherCorpseFlesh').\"},\"worktable_def\":{\"type\":\"string\",\"description\":\"Optional DefName of the target worktable (e.g. 'FueledStove', 'ElectricStove', 'Campfire', 'HandTailoringBench', 'TableButcher'). If omitted or not present, searches for any capable player worktable.\"},\"target_count\":{\"type\":\"integer\",\"description\":\"Target inventory stock count or repeat count (default: 10).\"},\"repeat_mode\":{\"type\":\"string\",\"description\":\"Production mode: 'TargetCount' (make until you have X, default) or 'RepeatCount' (make X times).\"},\"pawn_id\":{\"type\":\"integer\",\"description\":\"Optional colonist pawn ID to assign exclusively or anchor permission check.\"}},\"required\":[\"recipe_def\"]}" }; public override IReadOnlyList RequiredToolIds => Array.Empty(); @@ -108,12 +108,14 @@ public override Task> ExecuteAsync( Pawn? pawn = actorResolution.Pawn; // 2. Resolve RecipeDef - var recipeDef = DefDatabase.GetNamedSilentFail(recipeDefName.Trim()); + var trimmedRecipeName = recipeDefName.Trim(); + var recipeDef = DefDatabase.GetNamedSilentFail(trimmedRecipeName); if (recipeDef == null) { recipeDef = DefDatabase.AllDefsListForReading - .FirstOrDefault(r => r.defName.Equals(recipeDefName.Trim(), StringComparison.OrdinalIgnoreCase) - || r.label.Equals(recipeDefName.Trim(), StringComparison.OrdinalIgnoreCase)); + .FirstOrDefault(r => r != null + && (string.Equals(r.defName, trimmedRecipeName, StringComparison.OrdinalIgnoreCase) + || string.Equals(r.label, trimmedRecipeName, StringComparison.OrdinalIgnoreCase))); } if (recipeDef == null) @@ -143,21 +145,31 @@ public override Task> ExecuteAsync( if (!string.IsNullOrWhiteSpace(worktableDefName)) { + var trimmedTableName = worktableDefName.Trim(); targetWorktable = playerWorktables.FirstOrDefault(w => - w.def.defName.Equals(worktableDefName.Trim(), StringComparison.OrdinalIgnoreCase)); + w?.def != null + && (string.Equals(w.def.defName, trimmedTableName, StringComparison.OrdinalIgnoreCase) + || string.Equals(w.def.label, trimmedTableName, StringComparison.OrdinalIgnoreCase))); if (targetWorktable == null) { - return Task.FromResult(Result.Err( - RimMindErrors.InvalidAction(Id, $"Specified worktable '{worktableDefName}' not found or destroyed in player colony."))); + // LLMs often guess a def name that does not exist (e.g. 'TableStoveFueled'). + // Prefer any capable worktable over failing outright. + targetWorktable = FindCapableWorktable(playerWorktables, recipeDef); + if (targetWorktable == null) + { + string available = playerWorktables.Count > 0 + ? string.Join(", ", playerWorktables.Select(w => w.def.defName).Distinct()) + : "none"; + return Task.FromResult(Result.Err( + RimMindErrors.InvalidAction(Id, $"Specified worktable '{worktableDefName}' not found in player colony and no other worktable can run '{recipeDef.defName}'. Available worktables: {available}."))); + } } } else { // Find any table that can execute this recipe - targetWorktable = playerWorktables.FirstOrDefault(w => - (w.def.recipes != null && w.def.recipes.Contains(recipeDef)) - || (w.def.AllRecipes != null && w.def.AllRecipes.Contains(recipeDef))); + targetWorktable = FindCapableWorktable(playerWorktables, recipeDef); } if (targetWorktable == null) @@ -167,7 +179,8 @@ public override Task> ExecuteAsync( } // 4. Ingredient & Duplicate Check - bool isCookingRecipe = recipeDef.defName.Contains("Meal") || recipeDef.defName.Contains("Cook"); + bool isCookingRecipe = (recipeDef.defName?.IndexOf("Meal", StringComparison.OrdinalIgnoreCase) >= 0) + || (recipeDef.defName?.IndexOf("Cook", StringComparison.OrdinalIgnoreCase) >= 0); int rawNutrition = -1; if (isCookingRecipe && targetWorktable.Map != null) { @@ -190,7 +203,7 @@ public override Task> ExecuteAsync( return Task.FromResult(Result.Err( RimMindErrors.InvalidAction( Id, - $"Missing raw food ingredients (0 raw food on map) for '{recipeDef.defName}' on '{targetWorktable.LabelCap}'. Call actions_designate_resources (Harvest) to gather wild food first."))); + $"Missing raw food ingredients (0 raw food on map) for '{recipeDef.defName}' on '{targetWorktable.LabelCap}'. Call actions_designate_resources with designation_type 'Hunt' (wild animals) or 'Harvest' (wild plants/crops) to gather food first."))); } } @@ -261,6 +274,15 @@ public override Task> ExecuteAsync( #endif } +#if !RIMMIND_ACTIONS_TESTS + private static Building_WorkTable? FindCapableWorktable(List tables, RecipeDef recipeDef) + { + return tables.FirstOrDefault(w => + (w.def.recipes != null && w.def.recipes.Contains(recipeDef)) + || (w.def.AllRecipes != null && w.def.AllRecipes.Contains(recipeDef))); + } +#endif + private static bool IsEssentialSurvivalRecipe(string? recipeDefName) { if (string.IsNullOrWhiteSpace(recipeDefName)) return false; diff --git a/Source/Actions/CompositeToolCallBase.cs b/Source/Actions/CompositeToolCallBase.cs index feee626..3a685e4 100644 --- a/Source/Actions/CompositeToolCallBase.cs +++ b/Source/Actions/CompositeToolCallBase.cs @@ -115,6 +115,7 @@ private static RiskLevel MapDomainToRisk(AutonomyDomain? domain, ToolKind kind) AutonomyDomain.ResourceMarking => RiskLevel.Low, AutonomyDomain.WorktableBills => RiskLevel.Medium, AutonomyDomain.BlueprintPlacement => RiskLevel.Medium, + AutonomyDomain.WorkPriorityModification => RiskLevel.Medium, AutonomyDomain.HighRiskOperations => RiskLevel.High, _ => RiskLevel.Medium }; diff --git a/Source/Actions/DesignateResourcesCompositeTool.cs b/Source/Actions/DesignateResourcesCompositeTool.cs index 394b7f5..5276384 100644 --- a/Source/Actions/DesignateResourcesCompositeTool.cs +++ b/Source/Actions/DesignateResourcesCompositeTool.cs @@ -48,7 +48,7 @@ public sealed class DesignateResourcesCompositeTool : CompositeToolCallBase Id = Id, Category = "action", Description = "Autonomously designates resources on the map for colonist worktab execution (e.g. harvesting ripe wild berries/healroot, chopping mature trees for wood, or mining exposed mineral veins).", - ParametersSchema = "{\"type\":\"object\",\"properties\":{\"designation_type\":{\"type\":\"string\",\"description\":\"Type of designation: 'Harvest' (ripe wild food/plants), 'ChopWood' (mature timber trees), or 'Mine' (mineral ores).\"},\"radius\":{\"type\":\"integer\",\"description\":\"Search radius in tiles from anchor colonist/base center (default: 25, max: 60).\"},\"target_name\":{\"type\":\"string\",\"description\":\"Optional filter for specific defName or label (e.g. 'Plant_Berry', 'Plant_TreeOak', 'MineableSteel').\"},\"max_count\":{\"type\":\"integer\",\"description\":\"Maximum number of items to designate in one call (default: 15, max: 50).\"},\"pawn_id\":{\"type\":\"integer\",\"description\":\"Optional colonist pawn ID to center search and check autonomy permissions.\"}},\"required\":[\"designation_type\"]}" + ParametersSchema = "{\"type\":\"object\",\"properties\":{\"designation_type\":{\"type\":\"string\",\"description\":\"Type of designation: 'Harvest' (ripe wild food/plants), 'ChopWood' (mature timber trees), 'Mine' (mineral ores), or 'Hunt' (safe wild animals for meat when food is low).\"},\"radius\":{\"type\":\"integer\",\"description\":\"Search radius in tiles from anchor colonist/base center (default: 25, max: 60).\"},\"target_name\":{\"type\":\"string\",\"description\":\"Optional filter for specific defName or label (e.g. 'Plant_Berry', 'Plant_TreeOak', 'MineableSteel').\"},\"max_count\":{\"type\":\"integer\",\"description\":\"Maximum number of items to designate in one call (default: 15, max: 50).\"},\"pawn_id\":{\"type\":\"integer\",\"description\":\"Optional colonist pawn ID to center search and check autonomy permissions.\"}},\"required\":[\"designation_type\"]}" }; public override IReadOnlyList RequiredToolIds => Array.Empty(); @@ -61,7 +61,7 @@ public override Task> ExecuteAsync( || string.IsNullOrWhiteSpace(designationTypeStr)) { return Task.FromResult(Result.Err( - RimMindErrors.InvalidAction(Id, "Missing required parameter 'designation_type' (Harvest, ChopWood, or Mine)."))); + RimMindErrors.InvalidAction(Id, "Missing required parameter 'designation_type' (Harvest, ChopWood, Mine, or Hunt)."))); } #if RIMMIND_ACTIONS_TESTS @@ -108,8 +108,8 @@ public override Task> ExecuteAsync( // 3. Resolve Radius and Count Limit TryGetArgument(args.ArgumentsJson, "radius", out var radius); - if (radius <= 0) radius = 25; - radius = Math.Clamp(radius, 5, 60); + if (radius <= 0) radius = 60; + radius = Math.Clamp(radius, 5, 120); TryGetArgument(args.ArgumentsJson, "max_count", out var maxCount); if (maxCount <= 0) maxCount = 15; @@ -145,12 +145,12 @@ public override Task> ExecuteAsync( { 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 && plant.Growth < 0.7f) return false; + if (!plant.HarvestableNow) return false; if (map.designationManager.DesignationOn(plant, desDef) != null) return false; if (!string.IsNullOrWhiteSpace(targetNameFilter)) { - if (!plant.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase) - && !plant.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) + 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; @@ -168,8 +168,8 @@ public override Task> ExecuteAsync( if (map.designationManager.DesignationOn(plant, desDef) != null) return false; if (!string.IsNullOrWhiteSpace(targetNameFilter)) { - if (!plant.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase) - && !plant.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) + 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; @@ -187,8 +187,8 @@ public override Task> ExecuteAsync( if (map.designationManager.DesignationOn(plant, desDef) != null) return false; if (!string.IsNullOrWhiteSpace(targetNameFilter)) { - if (!plant.def.defName.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase) - && !plant.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) + 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; @@ -205,8 +205,31 @@ public override Task> ExecuteAsync( 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.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase) - && !t.Label.Contains(targetNameFilter, StringComparison.OrdinalIgnoreCase)) + 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; + }; + } + 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; @@ -215,7 +238,7 @@ public override Task> ExecuteAsync( else { return Task.FromResult(Result.Err( - RimMindErrors.InvalidAction(Id, $"Unknown designation type '{designationTypeStr}'. Supported: 'Harvest', 'ChopWood', 'Mine'."))); + 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) @@ -312,9 +335,16 @@ public override Task> ExecuteAsync( centerCell.z)))); } - // 6. Sort by Distance and Apply Designation + // 6. Sort by Edible Food Priority & Distance and Apply Designation + bool prioritizeEdible = mode.Contains("harvest") && !targetImpliesTrees; var selected = candidates - .OrderBy(t => t.Position.DistanceToSquared(centerCell)) + .OrderByDescending(t => + { + if (!prioritizeEdible || t is not Plant p) return 0; + var hDef = p.def?.plant?.harvestedThingDef; + return (hDef != null && hDef.IsNutritionGivingIngestible && hDef.ingestible?.HumanEdible == true) ? 1 : 0; + }) + .ThenBy(t => t.Position.DistanceToSquared(centerCell)) .Take(maxCount) .ToList(); @@ -325,6 +355,47 @@ public override Task> ExecuteAsync( 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) + { + 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); + } + } + string targetSample = string.Join(", ", selected.Take(3).Select(t => t.LabelShort)); if (selected.Count > 3) targetSample += $" (+{addedCount - 3} more)"; diff --git a/Source/Actions/EatAndRecreationCompositeTool.cs b/Source/Actions/EatAndRecreationCompositeTool.cs index 5db8e14..562dded 100644 --- a/Source/Actions/EatAndRecreationCompositeTool.cs +++ b/Source/Actions/EatAndRecreationCompositeTool.cs @@ -76,9 +76,39 @@ public override async Task> ExecuteAsync( var cancelJob = await ExecuteAtomicAsync("pawn.job.set", cancelArgs, args, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); - // 2. Direct pawn to rest and regenerate vital energies - var restArgs = BuildArgumentsJson(("pawn_id", pawnId), ("action", "force_rest")); - var rest = await ExecuteAtomicAsync("pawn.job.set", restArgs, args, ct).ConfigureAwait(false); + // 2. Direct pawn to eat food if hunger-driven, otherwise rest and regenerate vital energies + TryGetArgument(args.ArgumentsJson, "reason", out var reasonText); + bool wantsFood = !string.IsNullOrWhiteSpace(reasonText) && + (reasonText.IndexOf("eat", System.StringComparison.OrdinalIgnoreCase) >= 0 || + reasonText.IndexOf("food", System.StringComparison.OrdinalIgnoreCase) >= 0 || + reasonText.IndexOf("hunger", System.StringComparison.OrdinalIgnoreCase) >= 0 || + reasonText.IndexOf("starv", System.StringComparison.OrdinalIgnoreCase) >= 0 || + reasonText.IndexOf("meal", System.StringComparison.OrdinalIgnoreCase) >= 0 || + reasonText.IndexOf("nutrition", System.StringComparison.OrdinalIgnoreCase) >= 0); +#if !RIMMIND_ACTIONS_TESTS + var targetPawn = RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber(pawnId); + if (targetPawn?.needs?.food != null && targetPawn.needs.food.CurLevelPercentage < 0.80f) + { + wantsFood = true; + } +#endif + + ToolResult rest; + if (wantsFood) + { + var eatArgs = BuildArgumentsJson(("pawn_id", pawnId), ("action", "eat_food")); + rest = await ExecuteAtomicAsync("pawn.job.set", eatArgs, args, ct).ConfigureAwait(false); + if (rest.IsError) + { + var restArgs = BuildArgumentsJson(("pawn_id", pawnId), ("action", "force_rest")); + rest = await ExecuteAtomicAsync("pawn.job.set", restArgs, args, ct).ConfigureAwait(false); + } + } + else + { + var restArgs = BuildArgumentsJson(("pawn_id", pawnId), ("action", "force_rest")); + rest = await ExecuteAtomicAsync("pawn.job.set", restArgs, args, ct).ConfigureAwait(false); + } // No mood thought is injected: granting Catharsis on every LLM call was a free, repeatable mood buff. var summary = BuildStepSummary( diff --git a/Source/Actions/ManageEquipmentCompositeTool.cs b/Source/Actions/ManageEquipmentCompositeTool.cs index 100006f..7ee9800 100644 --- a/Source/Actions/ManageEquipmentCompositeTool.cs +++ b/Source/Actions/ManageEquipmentCompositeTool.cs @@ -135,9 +135,10 @@ public override Task> ExecuteAsync( if (!string.IsNullOrWhiteSpace(targetApparelDefName)) { + var trimmedApparel = targetApparelDefName.Trim(); allApparel = allApparel.Where(a => - a.def.defName.Equals(targetApparelDefName.Trim(), StringComparison.OrdinalIgnoreCase) - || a.Label.Contains(targetApparelDefName.Trim(), StringComparison.OrdinalIgnoreCase)) + string.Equals(a.def?.defName, trimmedApparel, StringComparison.OrdinalIgnoreCase) + || (a.Label != null && a.Label.Contains(trimmedApparel, StringComparison.OrdinalIgnoreCase))) .ToList(); } diff --git a/Source/Actions/ManageZoneCompositeTool.cs b/Source/Actions/ManageZoneCompositeTool.cs index 2df8719..13ec08a 100644 --- a/Source/Actions/ManageZoneCompositeTool.cs +++ b/Source/Actions/ManageZoneCompositeTool.cs @@ -141,11 +141,17 @@ public override Task> ExecuteAsync( TryGetArgument(args.ArgumentsJson, "crop_def", out var cropDefName); if (string.IsNullOrWhiteSpace(cropDefName)) cropDefName = "Plant_Rice"; - var plantDef = DefDatabase.GetNamedSilentFail(cropDefName.Trim()); + var trimmedCrop = cropDefName.Trim(); + var plantDef = DefDatabase.GetNamedSilentFail(trimmedCrop); if (plantDef == null || plantDef.plant == null) { - plantDef = DefDatabase.GetNamedSilentFail("Plant_Rice") - ?? DefDatabase.AllDefsListForReading.FirstOrDefault(d => d.plant != null); + plantDef = DefDatabase.AllDefsListForReading + .FirstOrDefault(d => d?.plant != null + && (string.Equals(d.defName, trimmedCrop, StringComparison.OrdinalIgnoreCase) + || string.Equals(d.defName, "Plant_" + trimmedCrop, StringComparison.OrdinalIgnoreCase) + || string.Equals(d.label, trimmedCrop, StringComparison.OrdinalIgnoreCase))) + ?? DefDatabase.GetNamedSilentFail("Plant_Rice") + ?? DefDatabase.AllDefsListForReading.FirstOrDefault(d => d?.plant != null); } if (plantDef == null) @@ -178,6 +184,17 @@ 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); + } + } } else { diff --git a/Source/Actions/PlaceBlueprintCompositeTool.cs b/Source/Actions/PlaceBlueprintCompositeTool.cs index 8e6a82b..ac6e55b 100644 --- a/Source/Actions/PlaceBlueprintCompositeTool.cs +++ b/Source/Actions/PlaceBlueprintCompositeTool.cs @@ -12,6 +12,7 @@ using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; #if !RIMMIND_ACTIONS_TESTS +using RimMind.Actions.Spatial; using RimWorld; using Verse.AI; #endif @@ -62,9 +63,7 @@ public sealed class PlaceBlueprintCompositeTool : CompositeToolCallBase { TryGetArgument(args.ArgumentsJson, "building_def", out buildingDefName); } - return IsEssentialSurvivalStructure(buildingDefName?.Trim()) - ? AutonomyDomain.EmergencySurvival - : AutonomyDomain.BlueprintPlacement; + return AutonomyDomain.BlueprintPlacement; } public override Task> ExecuteAsync( @@ -107,13 +106,15 @@ public override Task> ExecuteAsync( } // 1. Resolve BuildableDef - var thingDef = DefDatabase.GetNamedSilentFail(buildingDefName.Trim()); + var trimmedBuildingName = buildingDefName.Trim(); + var thingDef = DefDatabase.GetNamedSilentFail(trimmedBuildingName); if (thingDef == null) { - // Fallback: case-insensitive search + // Fallback: null-safe case-insensitive search thingDef = DefDatabase.AllDefsListForReading - .FirstOrDefault(d => d.defName.Equals(buildingDefName.Trim(), StringComparison.OrdinalIgnoreCase) - || d.label.Equals(buildingDefName.Trim(), StringComparison.OrdinalIgnoreCase)); + .FirstOrDefault(d => d != null + && (string.Equals(d.defName, trimmedBuildingName, StringComparison.OrdinalIgnoreCase) + || string.Equals(d.label, trimmedBuildingName, StringComparison.OrdinalIgnoreCase))); } if (thingDef == null) @@ -135,7 +136,12 @@ public override Task> ExecuteAsync( TryGetArgument(args.ArgumentsJson, "stuff_def", out var stuffDefName); if (!string.IsNullOrWhiteSpace(stuffDefName)) { - selectedStuff = DefDatabase.GetNamedSilentFail(stuffDefName.Trim()); + 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))) { @@ -168,10 +174,7 @@ public override Task> ExecuteAsync( Pawn? anchorPawn = actorResolution.Pawn; // Autonomy Permission & Resource Safety Guards - var autonomyDomain = ResolveAutonomyDomain(new JObject { ["building_def"] = thingDef.defName }, args) - ?? (IsEssentialSurvivalStructure(thingDef.defName) - ? AutonomyDomain.EmergencySurvival - : AutonomyDomain.BlueprintPlacement); + var autonomyDomain = AutonomyDomain.BlueprintPlacement; var permCheck = ActionPermissionGuard.CheckPermission(anchorPawn, Id, autonomyDomain, args); if (!permCheck.IsOk) { @@ -189,10 +192,28 @@ public override Task> ExecuteAsync( locationHint = string.IsNullOrWhiteSpace(locationHint) ? "near_base" : locationHint.ToLowerInvariant().Trim(); var rot = Rot4.North; - IntVec3 targetCell = FindValidPlacementCell(map, thingDef, anchorPos, locationHint, ref rot, selectedStuff); + string clusterReason = "default_fallback"; + int clusterRoomId = 0; + IntVec3 targetCell = FindValidPlacementCell( + map, + thingDef, + anchorPos, + locationHint, + ref rot, + selectedStuff, + out clusterReason, + out clusterRoomId); if (!targetCell.IsValid && anchorPos != map.Center) { - targetCell = FindValidPlacementCell(map, thingDef, map.Center, locationHint, ref rot, selectedStuff); + targetCell = FindValidPlacementCell( + map, + thingDef, + map.Center, + locationHint, + ref rot, + selectedStuff, + out clusterReason, + out clusterRoomId); } if (!targetCell.IsValid) { @@ -276,6 +297,9 @@ public override Task> ExecuteAsync( label = thingDef.label, stuff_used = selectedStuff?.defName ?? "None", placed_position = new { x = targetCell.x, z = targetCell.z }, + rotation = rot.ToStringHuman(), + placement_reason = clusterReason, + room_id = clusterRoomId > 0 ? (int?)clusterRoomId : null, chained_intent_session = sessionStarted, assigned_builder = builderName, message = placeMsg @@ -292,7 +316,15 @@ public override Task> ExecuteAsync( } #if !RIMMIND_ACTIONS_TESTS - private static IntVec3 FindValidPlacementCell(Map map, ThingDef def, IntVec3 anchor, string hint, ref Rot4 rot, ThingDef? stuff) + private static IntVec3 FindValidPlacementCell( + Map map, + ThingDef def, + IntVec3 anchor, + string hint, + ref Rot4 rot, + ThingDef? stuff, + out string clusterReason, + out int clusterRoomId) { bool wantsIndoor = hint.Contains("indoor") || hint.Contains("bed") || hint.Contains("room"); bool wantsOutdoor = hint.Contains("outdoor"); @@ -300,30 +332,68 @@ private static IntVec3 FindValidPlacementCell(Map map, ThingDef def, IntVec3 anc ? new[] { Rot4.North, Rot4.East, Rot4.South, Rot4.West } : new[] { Rot4.North }; - for (int radius = 2; radius <= 25; radius += 2) + // 1. Spatial topology + peer-furniture clustering solver (replaces random spawn-adjacent placement) + try { - for (int attempt = 0; attempt < 12; attempt++) + 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 isDefense = (def.building != null && def.building.IsTurret) || def.passability == Traversability.PassThroughOnly; + SpatialBuildingCategory category = ColonySpatialClusterSolver.ClassifyBuilding( + def.defName, + isBed: isBed, + isWorkTable: isWorkTable, + isTable: isTable, + isDefense: isDefense); + + SpatialCandidateScore? bestOverall = null; + Rot4 bestRot = rot; + + foreach (Rot4 candidateRot in rotations) { - var cell = CellFinder.StandableCellNear(anchor, map, radius); - if (!cell.IsValid || !cell.InBounds(map) || cell.Fogged(map)) continue; - - var room = cell.GetRoom(map); - if (wantsIndoor && (room == null || room.PsychologicallyOutdoors)) continue; - if (wantsOutdoor && room != null && !room.PsychologicallyOutdoors) continue; - if (room != null && room.IsDoorway) continue; - - foreach (var candidateRot in rotations) + var req = new SpatialPlacementRequest { - if (GenConstruct.CanPlaceBlueprintAt(def, cell, candidateRot, map, false, null, null, stuff).Accepted) + BuildingDefName = def.defName ?? string.Empty, + Category = category, + SizeX = 1, + SizeZ = 1, + HasInteractionCell = false, + LocationHint = hint, + AnchorX = anchor.x, + AnchorZ = anchor.z + }; + + List ranked = ColonySpatialClusterSolver.RankCandidates( + snapshot, + req, + (cx, cz) => GenConstruct.CanPlaceBlueprintAt(def, new IntVec3(cx, 0, cz), candidateRot, map, false, null, null, stuff).Accepted); + + if (ranked.Count > 0) + { + SpatialCandidateScore top = ranked[0]; + if (bestOverall == null || top.Score > bestOverall.Score) { - rot = candidateRot; - return cell; + bestOverall = top; + bestRot = candidateRot; } } } + + if (bestOverall != null) + { + rot = bestRot; + clusterReason = bestOverall.Reason; + clusterRoomId = bestOverall.RoomId; + return new IntVec3(bestOverall.X, 0, bestOverall.Z); + } + } + catch + { + // Fall back to deterministic radial scan if spatial solver encounters an unexpected map state } - // Deterministic radial scan with room preference + // 2. Deterministic radial scan with room preference foreach (var cell in GenRadial.RadialCellsAround(anchor, 28, true)) { if (!cell.IsValid || !cell.InBounds(map) || cell.Fogged(map) || !cell.Standable(map)) continue; @@ -337,12 +407,14 @@ private static IntVec3 FindValidPlacementCell(Map map, ThingDef def, IntVec3 anc if (GenConstruct.CanPlaceBlueprintAt(def, cell, candidateRot, map, false, null, null, stuff).Accepted) { rot = candidateRot; + clusterReason = "radial_fallback"; + clusterRoomId = room != null && !room.PsychologicallyOutdoors ? room.ID : 0; return cell; } } } - // Deterministic radial fallback without strict indoor/outdoor constraint + // 3. Deterministic radial fallback without strict indoor/outdoor constraint foreach (var cell in GenRadial.RadialCellsAround(anchor, 28, true)) { if (!cell.IsValid || !cell.InBounds(map) || cell.Fogged(map) || !cell.Standable(map)) continue; @@ -354,11 +426,15 @@ private static IntVec3 FindValidPlacementCell(Map map, ThingDef def, IntVec3 anc if (GenConstruct.CanPlaceBlueprintAt(def, cell, candidateRot, map, false, null, null, stuff).Accepted) { rot = candidateRot; + clusterReason = "radial_unconstrained_fallback"; + clusterRoomId = 0; return cell; } } } + clusterReason = "none"; + clusterRoomId = 0; return IntVec3.Invalid; } @@ -374,37 +450,44 @@ private static IntVec3 FindValidPlacementCell(Map map, ThingDef def, IntVec3 anc return null; } - // Step 1: If blueprint is still active, try delivering resources then finishing frame - if (blueprint != null && !blueprint.Destroyed && blueprint.Spawned) + try { - if (pawn.CanReserveAndReach(blueprint, PathEndMode.Touch, Danger.Some)) + // Step 1: If blueprint is still active, try delivering resources then finishing frame + if (blueprint != null && !blueprint.Destroyed && blueprint.Spawned) { - var deliverBpGiver = DefDatabase.GetNamedSilentFail("ConstructDeliverResourcesToBlueprints")?.Worker as WorkGiver_Scanner - ?? new WorkGiver_ConstructDeliverResourcesToBlueprints(); - var haulJob = deliverBpGiver.JobOnThing(pawn, blueprint, true); - if (haulJob != null) return haulJob; + 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; + } - var finishBpGiver = DefDatabase.GetNamedSilentFail("ConstructFinishFrames")?.Worker as WorkGiver_Scanner + // 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 finishBpJob = finishBpGiver.JobOnThing(pawn, blueprint, true); - if (finishBpJob != null) return finishBpJob; + var finishJob = finishGiver.JobOnThing(pawn, frame, true); + if (finishJob != null) return finishJob; } - 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)) + catch { - 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; + return null; } return null; diff --git a/Source/Actions/PlanRoomProjectCompositeTool.cs b/Source/Actions/PlanRoomProjectCompositeTool.cs index 5901bc6..f2f46ac 100644 --- a/Source/Actions/PlanRoomProjectCompositeTool.cs +++ b/Source/Actions/PlanRoomProjectCompositeTool.cs @@ -67,12 +67,7 @@ public sealed class PlanRoomProjectCompositeTool : CompositeToolCallBase roomType = "Shelter"; } - string normalized = roomType!.Trim(); - bool isSurvivalRoom = normalized.Equals("Shelter", StringComparison.OrdinalIgnoreCase) - || normalized.Equals("Bedroom", StringComparison.OrdinalIgnoreCase); - return isSurvivalRoom - ? AutonomyDomain.EmergencySurvival - : AutonomyDomain.BlueprintPlacement; + return AutonomyDomain.BlueprintPlacement; } public override Task> ExecuteAsync( @@ -122,10 +117,7 @@ public override Task> ExecuteAsync( TryGetArgument(args.ArgumentsJson, "room_type", out var roomType); if (string.IsNullOrWhiteSpace(roomType)) roomType = "Shelter"; - bool isSurvivalRoom = roomType.Equals("Shelter", StringComparison.OrdinalIgnoreCase) - || roomType.Equals("Bedroom", StringComparison.OrdinalIgnoreCase); - var roomAutonomyDomain = ResolveAutonomyDomain(new JObject { ["room_type"] = roomType }, args) - ?? (isSurvivalRoom ? AutonomyDomain.EmergencySurvival : AutonomyDomain.BlueprintPlacement); + var roomAutonomyDomain = AutonomyDomain.BlueprintPlacement; var permCheck = ActionPermissionGuard.CheckPermission(builderPawn, Id, roomAutonomyDomain, args); if (!permCheck.IsOk) @@ -142,7 +134,12 @@ public override Task> ExecuteAsync( ThingDef? selectedStuff = null; if (!string.IsNullOrWhiteSpace(stuffDefName)) { - selectedStuff = DefDatabase.GetNamedSilentFail(stuffDefName.Trim()); + 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))); } if (selectedStuff == null) { diff --git a/Source/Actions/QueryBuildableStructuresCompositeTool.cs b/Source/Actions/QueryBuildableStructuresCompositeTool.cs index b3b6282..774fc7f 100644 --- a/Source/Actions/QueryBuildableStructuresCompositeTool.cs +++ b/Source/Actions/QueryBuildableStructuresCompositeTool.cs @@ -8,6 +8,7 @@ using RimMind.Domain.Agent.Policies; using RimMind.Domain.ValueObjects; #if !RIMMIND_ACTIONS_TESTS +using RimMind.Actions.Spatial; using RimWorld; #endif using Verse; @@ -67,7 +68,8 @@ public override Task> ExecuteAsync( })); #else // Read-only query: prefer the acting colonist's map, fall back to the viewed map. - var map = RimMind.Actions.Policies.ActionPermissionGuard.ResolveActorAndMap(args).Map ?? Find.CurrentMap; + var actorResolution = RimMind.Actions.Policies.ActionPermissionGuard.ResolveActorAndMap(args); + var map = actorResolution.Map ?? Find.CurrentMap; if (map == null) { var noMapResult = new @@ -84,6 +86,29 @@ public override Task> ExecuteAsync( })); } + var anchorPawn = actorResolution.Pawn; + IntVec3 fallbackAnchor = anchorPawn != null && anchorPawn.Spawned && anchorPawn.Map == map ? anchorPawn.Position : map.Center; + ColonySpatialSnapshot spatialSnapshot = MapSpatialSnapshotBuilder.Build(map, fallbackAnchor.x, fallbackAnchor.z, radius: 22); + var roomSummaries = spatialSnapshot.Rooms + .Take(10) + .Select(r => new + { + room_id = r.RoomId, + role = r.Role, + center_x = r.CenterX, + center_z = r.CenterZ, + cells = r.CellCount, + beds = r.BedCount, + worktables = r.WorktableCount, + tables = r.TableCount + }) + .ToList(); + string spatialAsciiMap = ColonySpatialClusterSolver.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); var compDef = DefDatabase.GetNamedSilentFail("ComponentIndustrial") @@ -131,6 +156,14 @@ public override Task> ExecuteAsync( var responsePayload = new { status = "ok", + colony_anchor = new + { + x = spatialSnapshot.ColonyAnchorX, + z = spatialSnapshot.ColonyAnchorZ, + has_base = spatialSnapshot.HasBaseAnchor + }, + rooms = roomSummaries, + spatial_ascii_map = spatialAsciiMap, colony_status = new { outdoor_temperature_c = Math.Round(outdoorTemp, 1), diff --git a/Source/Actions/TriagePatientCompositeTool.cs b/Source/Actions/TriagePatientCompositeTool.cs index b87bc58..1759121 100644 --- a/Source/Actions/TriagePatientCompositeTool.cs +++ b/Source/Actions/TriagePatientCompositeTool.cs @@ -84,12 +84,59 @@ public override async Task> ExecuteAsync( var patientRest = await ExecuteAtomicAsync("pawn.job.set", patientRestArgs, args, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); - // 2. If doctor_id is provided, interrupt doctor's non-medical work so they can triage immediately + // 2. If doctor_id is provided (or auto-resolved on the map), direct doctor to rescue/tend patient immediately ToolResult doctorPrep = ToolResult.Ok("no doctor specified"); +#if !RIMMIND_ACTIONS_TESTS + var patientPawn = RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber(patientId); + if ((!hasDoctor || doctorId == patientId) && patientPawn?.Map != null) + { + var candidates = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(patientPawn.Map); + for (int i = 0; i < candidates.Count; i++) + { + var c = candidates[i]; + if (c == null || c.thingIDNumber == patientId || c.Dead || c.Downed) continue; + if (c.WorkTypeIsDisabled(RimWorld.WorkTypeDefOf.Doctor)) continue; + doctorId = c.thingIDNumber; + hasDoctor = true; + break; + } + } +#endif 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); + } + + if (patientPawn != null && patientPawn.Downed && !RimWorld.RestUtility.InBed(patientPawn)) + { + var rescueArgs = BuildArgumentsJson(("pawn_id", doctorId), ("action", "rescue_pawn"), ("target_pawn_id", patientId)); + doctorPrep = await ExecuteAtomicAsync("pawn.job.set", rescueArgs, args, ct).ConfigureAwait(false); + } + else if (patientPawn?.health != null && patientPawn.health.HasHediffsNeedingTend()) + { + var tendArgs = BuildArgumentsJson(("pawn_id", doctorId), ("action", "tend_pawn"), ("target_pawn_id", patientId)); + doctorPrep = await ExecuteAtomicAsync("pawn.job.set", tendArgs, args, ct).ConfigureAwait(false); + } + else + { + var doctorCancelArgs = BuildArgumentsJson(("pawn_id", doctorId), ("action", "cancel_job")); + doctorPrep = await ExecuteAtomicAsync("pawn.job.set", doctorCancelArgs, args, ct).ConfigureAwait(false); + } + + if (doctorPrep.IsError) + { + var doctorCancelArgs = BuildArgumentsJson(("pawn_id", doctorId), ("action", "cancel_job")); + doctorPrep = await ExecuteAtomicAsync("pawn.job.set", doctorCancelArgs, args, ct).ConfigureAwait(false); + } +#else var doctorCancelArgs = BuildArgumentsJson(("pawn_id", doctorId), ("action", "cancel_job")); doctorPrep = await ExecuteAtomicAsync("pawn.job.set", doctorCancelArgs, args, ct).ConfigureAwait(false); +#endif } // No mood thought is injected: granting Catharsis on every LLM call was a free, repeatable mood buff. @@ -97,12 +144,23 @@ public override async Task> ExecuteAsync( ("patientBedRest", patientRest), ("doctorTriageReady", doctorPrep)); + bool noCareAvailable = false; +#if !RIMMIND_ACTIONS_TESTS + // Honest outcome: a downed patient with no able doctor gets no care at all + // (a standing patient can still self-tend through vanilla work). + noCareAvailable = !hasDoctor && patientPawn != null && patientPawn.Downed; + if (noCareAvailable) + { + summary = $"No able-bodied colonist can rescue or tend {patientPawn!.LabelShort}; no medical care was given. {summary}"; + } +#endif + return Result.Ok(new ToolResult { ToolCallId = args.ToolCallId, ToolName = Id, Content = summary, - IsError = patientRest.IsError + IsError = patientRest.IsError || noCareAvailable }); } } diff --git a/Source/Debug/ActionsBehaviorAutotestSuite.cs b/Source/Debug/ActionsBehaviorAutotestSuite.cs index a7bfeaa..95c337c 100644 --- a/Source/Debug/ActionsBehaviorAutotestSuite.cs +++ b/Source/Debug/ActionsBehaviorAutotestSuite.cs @@ -1,8 +1,10 @@ using System; +using System.Linq; using System.Threading; using LudeonTK; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models.Tools; +using RimMind.Domain.Agent.Policies; using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -116,6 +118,158 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) { context.Assert(false, $"Negative boundary probe threw uncaught exception: {ex.Message}"); } + + // 5. Spatial Query & Topology (actions_query_buildable_structures) + try + { + var queryBuildableTool = registry.FindById("actions_query_buildable_structures"); + context.Assert(queryBuildableTool != null, "actions_query_buildable_structures is registered in Core registry"); + if (queryBuildableTool != null) + { + var qArgs = new ToolCallArgs + { + ToolCallId = "autotest_actions_query_buildable", + ToolName = "actions_query_buildable_structures", + ArgumentsJson = "{\"category\":\"furniture\"}", + PawnId = pawn?.thingIDNumber, + TraceId = "autotest_actions_query_trace" + }; + + var qRes = queryBuildableTool.ExecuteAsync(qArgs, CancellationToken.None).GetAwaiter().GetResult(); + string qContent = qRes.IsOk ? (qRes.Value?.Content ?? string.Empty) : string.Empty; + context.Assert( + qRes.IsOk && qRes.Value != null && !qRes.Value.IsError + && qContent.Contains("spatial_ascii_map") + && qContent.Contains("colony_anchor"), + "actions_query_buildable_structures returns spatial_ascii_map and colony_anchor"); + } + } + catch (Exception ex) + { + context.Assert(false, $"actions_query_buildable_structures check threw unexpected exception: {ex.Message}"); + } + + // 6. Blueprint Permission Gate & Spatial Placement + Work Queue & WorkPriorityModification Gate + if (pawn != null) + { + var placeBlueprintTool = registry.FindById("actions_place_blueprint"); + context.Assert(placeBlueprintTool != null, "actions_place_blueprint is registered in Core registry"); + if (placeBlueprintTool != null) + { + AutonomyLevel origBp = RimMindAPI.Autonomy.GetLevel(pawn, AutonomyDomain.BlueprintPlacement); + try + { + RimMindAPI.Autonomy.SetLevel(pawn, AutonomyDomain.BlueprintPlacement, AutonomyLevel.Disabled); + var blockedArgs = new ToolCallArgs + { + ToolCallId = "autotest_actions_bp_blocked", + ToolName = "actions_place_blueprint", + ArgumentsJson = $"{{\"pawn_id\":{pawn.thingIDNumber},\"building_def\":\"SleepingSpot\"}}", + PawnId = pawn.thingIDNumber, + IsPlayerApproved = false, + TraceId = "autotest_actions_bp_blocked_trace" + }; + var blockedRes = placeBlueprintTool.ExecuteAsync(blockedArgs, CancellationToken.None).GetAwaiter().GetResult(); + context.Assert(blockedRes.IsErr, "actions_place_blueprint blocks unpermitted blueprint placement when BlueprintPlacement is Disabled"); + + RimMindAPI.Autonomy.SetLevel(pawn, AutonomyDomain.BlueprintPlacement, AutonomyLevel.FullAutonomous); + var allowedArgs = new ToolCallArgs + { + ToolCallId = "autotest_actions_bp_allowed", + ToolName = "actions_place_blueprint", + ArgumentsJson = $"{{\"pawn_id\":{pawn.thingIDNumber},\"building_def\":\"SleepingSpot\",\"location_hint\":\"near_base\"}}", + PawnId = pawn.thingIDNumber, + IsPlayerApproved = false, + TraceId = "autotest_actions_bp_allowed_trace" + }; + var allowedRes = placeBlueprintTool.ExecuteAsync(allowedArgs, CancellationToken.None).GetAwaiter().GetResult(); + context.Assert(allowedRes.IsOk && allowedRes.Value != null && !allowedRes.Value.IsError, + $"actions_place_blueprint succeeds when BlueprintPlacement is FullAutonomous ({allowedRes.Value?.Content ?? allowedRes.Error?.Message})"); + } + catch (Exception ex) + { + context.Assert(false, $"actions_place_blueprint permission gate check threw unexpected exception: {ex.Message}"); + } + finally + { + RimMindAPI.Autonomy.SetLevel(pawn, AutonomyDomain.BlueprintPlacement, origBp); + try + { + var map = context.CurrentMap ?? pawn.Map; + if (map?.listerThings != null) + { + var cleanupBlueprints = map.listerThings.AllThings + .Where(t => t != null && !t.Destroyed && t.def.IsBlueprint && t.def.entityDefToBuild?.defName == "SleepingSpot") + .ToList(); + foreach (var bp in cleanupBlueprints) + { + bp.Destroy(DestroyMode.Cancel); + } + } + } + catch (Exception ex) + { + context.Warn($"Cleanup of SleepingSpot blueprints encountered warning: {ex.Message}"); + } + } + } + + try + { + var jobSetTool = registry.FindById("pawn.job.set"); + context.Assert(jobSetTool != null, "pawn.job.set is registered in Core registry"); + if (jobSetTool != null) + { + var clearArgs = new ToolCallArgs + { + ToolCallId = "autotest_actions_clear_queue", + ToolName = "pawn.job.set", + ArgumentsJson = $"{{\"pawn_id\":{pawn.thingIDNumber},\"action\":\"clear_queue\"}}", + PawnId = pawn.thingIDNumber, + IsPlayerApproved = true, + TraceId = "autotest_actions_clear_queue_trace" + }; + var clearRes = jobSetTool.ExecuteAsync(clearArgs, CancellationToken.None).GetAwaiter().GetResult(); + context.Assert(clearRes.IsOk && clearRes.Value != null && !clearRes.Value.IsError, + "pawn.job.set clear_queue executes cleanly on active colonist"); + } + } + catch (Exception ex) + { + context.Assert(false, $"pawn.job.set clear_queue check threw unexpected exception: {ex.Message}"); + } + + var workSetTool = registry.FindById("pawn.work.set"); + context.Assert(workSetTool != null, "pawn.work.set is registered in Core registry"); + if (workSetTool != null) + { + AutonomyLevel origWp = RimMindAPI.Autonomy.GetLevel(pawn, AutonomyDomain.WorkPriorityModification); + try + { + RimMindAPI.Autonomy.SetLevel(pawn, AutonomyDomain.WorkPriorityModification, AutonomyLevel.Disabled); + var wpArgs = new ToolCallArgs + { + ToolCallId = "autotest_actions_wp_blocked", + ToolName = "pawn.work.set", + ArgumentsJson = $"{{\"pawn_id\":{pawn.thingIDNumber},\"action\":\"set_batch\",\"params\":{{\"priorities\":\"Firefighter=1\"}}}}", + PawnId = pawn.thingIDNumber, + IsPlayerApproved = false, + TraceId = "autotest_actions_wp_blocked_trace" + }; + var wpBlocked = workSetTool.ExecuteAsync(wpArgs, CancellationToken.None).GetAwaiter().GetResult(); + context.Assert(wpBlocked.IsErr || (wpBlocked.IsOk && wpBlocked.Value != null && wpBlocked.Value.IsError), + "pawn.work.set blocks batch priority modification when WorkPriorityModification is Disabled"); + } + catch (Exception ex) + { + context.Assert(false, $"pawn.work.set permission gate check threw unexpected exception: {ex.Message}"); + } + finally + { + RimMindAPI.Autonomy.SetLevel(pawn, AutonomyDomain.WorkPriorityModification, origWp); + } + } + } } } } diff --git a/Source/Spatial/ColonySpatialClusterSolver.cs b/Source/Spatial/ColonySpatialClusterSolver.cs new file mode 100644 index 0000000..b45f6ad --- /dev/null +++ b/Source/Spatial/ColonySpatialClusterSolver.cs @@ -0,0 +1,547 @@ +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!); + } + + public static class ColonySpatialClusterSolver + { + public static SpatialBuildingCategory ClassifyBuilding( + 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; + } + + public static List RankCandidates( + ColonySpatialSnapshot snapshot, + SpatialPlacementRequest request, + Func? extraValidator = null) + { + if (snapshot == null) throw new ArgumentNullException(nameof(snapshot)); + if (request == null) throw new ArgumentNullException(nameof(request)); + + int sizeX = Math.Max(1, request.SizeX); + int sizeZ = Math.Max(1, request.SizeZ); + string hint = (request.LocationHint ?? "near_base").Trim().ToLowerInvariant(); + + int targetX = hint == "near_pawn" || !snapshot.HasBaseAnchor + ? request.AnchorX + : snapshot.ColonyAnchorX; + int targetZ = hint == "near_pawn" || !snapshot.HasBaseAnchor + ? request.AnchorZ + : snapshot.ColonyAnchorZ; + + var candidates = new List(); + + for (int x = snapshot.MinX; x <= snapshot.MaxX; x++) + { + for (int z = snapshot.MinZ; z <= snapshot.MaxZ; z++) + { + if (!IsFootprintFree(snapshot, x, z, sizeX, sizeZ)) + continue; + + if (request.HasInteractionCell) + { + int ix = x + request.InteractionOffsetX; + int iz = z + request.InteractionOffsetZ; + if (!IsCellPassableForInteraction(snapshot.GetCellKind(ix, iz))) + continue; + } + + if (extraValidator != null && !extraValidator(x, z)) + continue; + + SpatialCandidateScore scored = ScoreCandidate(snapshot, request, hint, x, z, sizeX, sizeZ, targetX, targetZ); + candidates.Add(scored); + } + } + + candidates.Sort((a, b) => + { + int scoreCmp = b.Score.CompareTo(a.Score); + if (scoreCmp != 0) return scoreCmp; + int distA = Math.Abs(a.X - targetX) + Math.Abs(a.Z - targetZ); + int distB = Math.Abs(b.X - targetX) + Math.Abs(b.Z - targetZ); + int distCmp = distA.CompareTo(distB); + if (distCmp != 0) return distCmp; + int xCmp = a.X.CompareTo(b.X); + return xCmp != 0 ? xCmp : a.Z.CompareTo(b.Z); + }); + + return candidates; + } + + private static bool IsFootprintFree(ColonySpatialSnapshot snapshot, int x, int z, 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); + if (kind != SpatialCellKind.IndoorRoom && kind != SpatialCellKind.OutdoorFloor) + return false; + } + } + return true; + } + + private static bool IsCellPassableForInteraction(SpatialCellKind kind) + => kind == SpatialCellKind.IndoorRoom || kind == SpatialCellKind.OutdoorFloor || kind == SpatialCellKind.Door; + + private static SpatialCandidateScore ScoreCandidate( + ColonySpatialSnapshot snapshot, + SpatialPlacementRequest request, + string hint, + int x, + int z, + int sizeX, + int sizeZ, + int targetX, + int targetZ) + { + SpatialCellKind cellKind = snapshot.GetCellKind(x, z); + int roomId = snapshot.GetRoomId(x, z); + SpatialRoomSummary? room = null; + bool inEnclosedRoom = roomId > 0 && snapshot.TryGetRoom(roomId, out room) && room.IsEnclosed; + 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); + + double score = 0d; + string reason = "open_ground"; + + bool wantsOutdoor = hint == "outdoor" || request.Category == SpatialBuildingCategory.Defense; + bool wantsIndoor = hint == "indoor" + || request.Category == SpatialBuildingCategory.Sleeping + || request.Category == SpatialBuildingCategory.Production + || request.Category == SpatialBuildingCategory.DiningRecreation + || request.Category == SpatialBuildingCategory.Storage; + + if (wantsOutdoor) + { + if (cellKind == SpatialCellKind.OutdoorFloor) + { + score += 45d; + reason = "outdoor_clear"; + } + else + { + score -= 60d; + } + } + else if (wantsIndoor) + { + if (inEnclosedRoom) + { + score += 65d; + reason = "enclosed_room"; + } + else if (isRoofed && cellKind == SpatialCellKind.IndoorRoom) + { + score += 35d; + reason = "roofed_interior"; + } + else if (hint == "indoor") + { + score -= 30d; + } + } + else if (inEnclosedRoom) + { + score += 20d; + reason = "enclosed_room"; + } + + if (adjDoors > 0) + score -= 35d * adjDoors; + + if (inStorage && request.Category != SpatialBuildingCategory.Storage) + score -= 18d; + + if (request.Category == SpatialBuildingCategory.Sleeping) + { + if (room != null && room.IsEnclosed) + { + if (room.BedCount > 0) + { + score += 35d; + reason = "cluster_bedroom"; + } + else if (room.WorktableCount == 0 && room.TableCount == 0) + { + score += 22d; + reason = "empty_enclosed_room"; + } + else if (room.WorktableCount > 0) + { + score -= 12d; + } + } + + if (adjWalls >= 1 && adjWalls <= 2) + { + score += 25d; + if (reason == "open_ground" || reason == "enclosed_room") + reason = "indoor_wall_aligned"; + } + + score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.Sleeping, x, z, maxDist: 4, bonus: 22d); + } + else if (request.Category == SpatialBuildingCategory.Production) + { + if (room != null && room.IsEnclosed && room.WorktableCount > 0) + { + score += 35d; + reason = "cluster_workshop"; + } + else if (inEnclosedRoom && (room == null || room.BedCount == 0)) + { + score += 18d; + } + + if (adjWalls == 1) + score += 15d; + + 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) + { + if (room != null && room.IsEnclosed && room.TableCount > 0) + { + score += 35d; + reason = "cluster_dining"; + } + + 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) + { + if (inEnclosedRoom) + { + score += 25d; + reason = "indoor_storage"; + } + if (adjWalls >= 1) score += 10d; + score += PeerClusterBonus(snapshot.Peers, SpatialBuildingCategory.Storage, x, z, maxDist: 4, bonus: 20d); + } + else if (request.Category == SpatialBuildingCategory.TemperatureLight) + { + if (inEnclosedRoom) + { + score += 40d; + if (room != null && (room.BedCount > 0 || room.WorktableCount > 0)) + { + score += 25d; + reason = "serve_occupied_room"; + } + } + } + + 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 PeerClusterBonus( + IReadOnlyList peers, + SpatialBuildingCategory category, + int x, + int z, + int maxDist, + double bonus) + { + double best = 0d; + for (int i = 0; i < peers.Count; i++) + { + SpatialPeerItem peer = peers[i]; + if (peer.Category != category) continue; + int dist = Math.Abs(peer.X - x) + Math.Abs(peer.Z - z); + if (dist == 1) + best = Math.Max(best, bonus * 0.75d); + else if (dist >= 2 && dist <= maxDist) + best = Math.Max(best, bonus); + } + return best; + } + + private static int CountAdjacentKind( + ColonySpatialSnapshot snapshot, + int x, + int z, + int sizeX, + int sizeZ, + SpatialCellKind targetKind) + { + 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++; + } + 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++; + } + 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/MapSpatialSnapshotBuilder.cs b/Source/Spatial/MapSpatialSnapshotBuilder.cs new file mode 100644 index 0000000..0b11b5e --- /dev/null +++ b/Source/Spatial/MapSpatialSnapshotBuilder.cs @@ -0,0 +1,280 @@ +#if !RIMMIND_ACTIONS_TESTS +using System; +using System.Collections.Generic; +using RimWorld; +using Verse; + +namespace RimMind.Actions.Spatial +{ + public static class MapSpatialSnapshotBuilder + { + private sealed class RoomAccumulator + { + public int RoomId; + public int CellCount; + public long SumX; + public long SumZ; + public int BedCount; + public int WorktableCount; + public int TableCount; + } + + public static ColonySpatialSnapshot Build(Map map, int fallbackX, int fallbackZ, int radius = 26) + { + if (map == null) throw new ArgumentNullException(nameof(map)); + + map.regionAndRoomUpdater?.TryRebuildDirtyRegionsAndRooms(); + + int clampedRadius = Math.Max(8, Math.Min(32, radius)); + DetermineColonyAnchor(map, fallbackX, fallbackZ, out int anchorX, out int anchorZ, out bool hasBaseAnchor); + + int minX = Math.Max(0, anchorX - clampedRadius); + int maxX = Math.Min(map.Size.x - 1, anchorX + clampedRadius); + int minZ = Math.Max(0, anchorZ - clampedRadius); + int maxZ = Math.Min(map.Size.z - 1, anchorZ + clampedRadius); + + var snapshot = new ColonySpatialSnapshot(minX, minZ, maxX - minX + 1, maxZ - minZ + 1) + { + ColonyAnchorX = anchorX, + ColonyAnchorZ = anchorZ, + HasBaseAnchor = hasBaseAnchor + }; + + var roomAccum = new Dictionary(); + var roofGrid = map.roofGrid; + var zoneManager = map.zoneManager; + + for (int x = minX; x <= maxX; x++) + { + for (int z = minZ; z <= maxZ; z++) + { + IntVec3 cell = new IntVec3(x, 0, z); + bool fogged = cell.Fogged(map); + Room? room = fogged ? null : cell.GetRoom(map); + bool enclosed = room != null && !room.PsychologicallyOutdoors && !room.TouchesMapEdge; + int roomId = enclosed ? room!.ID : 0; + bool roofed = roofGrid != null && roofGrid.Roofed(cell); + bool isStorage = zoneManager != null && zoneManager.ZoneAt(cell) is Zone_Stockpile; + + SpatialCellKind kind; + if (fogged) + { + kind = SpatialCellKind.Impassable; + } + else + { + Building edifice = cell.GetEdifice(map); + if (edifice != null) + { + if (edifice is Building_Door) + kind = SpatialCellKind.Door; + else if (edifice.def.building != null && edifice.def.building.isNaturalRock) + kind = SpatialCellKind.Impassable; + else if (edifice.def.passability == Traversability.Impassable) + kind = SpatialCellKind.Wall; + else + kind = SpatialCellKind.OccupiedFurniture; + } + else if (!cell.Standable(map)) + { + kind = SpatialCellKind.Impassable; + } + else if (cell.GetFirstThing(map) != null || cell.GetFirstThing(map) != null) + { + kind = SpatialCellKind.Blueprint; + } + else if (enclosed || roofed) + { + kind = SpatialCellKind.IndoorRoom; + } + else + { + kind = SpatialCellKind.OutdoorFloor; + } + } + + snapshot.SetCell(x, z, kind, roomId, roofed, isStorage); + + if (enclosed && roomId > 0) + { + if (!roomAccum.TryGetValue(roomId, out var acc)) + { + acc = new RoomAccumulator { RoomId = roomId }; + roomAccum[roomId] = acc; + } + acc.CellCount++; + acc.SumX += x; + acc.SumZ += z; + } + } + } + + var buildings = map.listerBuildings?.allBuildingsColonist; + if (buildings != null) + { + int limit = Math.Min(buildings.Count, 300); + for (int i = 0; i < limit; i++) + { + Building b = buildings[i]; + if (b == null || !b.Spawned || b.Destroyed) continue; + IntVec3 pos = b.Position; + if (!snapshot.InBounds(pos.x, pos.z)) continue; + + bool isBed = b is Building_Bed; + bool isWorkTable = b is Building_WorkTable; + SpatialBuildingCategory cat = ColonySpatialClusterSolver.ClassifyBuilding( + b.def?.defName, + isBed: isBed, + isWorkTable: isWorkTable); + + int roomId = snapshot.GetRoomId(pos.x, pos.z); + snapshot.Peers.Add(new SpatialPeerItem + { + DefName = b.def?.defName ?? string.Empty, + Category = cat, + X = pos.x, + Z = pos.z, + RoomId = roomId, + IsBlueprint = false + }); + + if (roomId > 0 && roomAccum.TryGetValue(roomId, out var acc)) + { + if (isBed || cat == SpatialBuildingCategory.Sleeping) acc.BedCount++; + if (isWorkTable || cat == SpatialBuildingCategory.Production) acc.WorktableCount++; + if (cat == SpatialBuildingCategory.DiningRecreation) acc.TableCount++; + } + } + } + + var blueprints = map.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint); + if (blueprints != null) + { + int limit = Math.Min(blueprints.Count, 150); + for (int i = 0; i < limit; i++) + { + Thing bp = blueprints[i]; + if (bp == null || !bp.Spawned || bp.Faction != Faction.OfPlayer) continue; + IntVec3 pos = bp.Position; + if (!snapshot.InBounds(pos.x, pos.z)) continue; + + string buildDefName = (bp as Blueprint_Build)?.def?.entityDefToBuild?.defName ?? bp.def?.defName ?? string.Empty; + SpatialBuildingCategory cat = ColonySpatialClusterSolver.ClassifyBuilding(buildDefName); + int roomId = snapshot.GetRoomId(pos.x, pos.z); + snapshot.Peers.Add(new SpatialPeerItem + { + DefName = buildDefName, + Category = cat, + X = pos.x, + Z = pos.z, + RoomId = roomId, + IsBlueprint = true + }); + + if (roomId > 0 && roomAccum.TryGetValue(roomId, out var acc)) + { + if (cat == SpatialBuildingCategory.Sleeping) acc.BedCount++; + if (cat == SpatialBuildingCategory.Production) acc.WorktableCount++; + if (cat == SpatialBuildingCategory.DiningRecreation) acc.TableCount++; + } + } + } + + foreach (var kv in roomAccum) + { + var acc = kv.Value; + if (acc.CellCount <= 0) continue; + string role = InferRoomRole(acc); + snapshot.AddRoom(new SpatialRoomSummary + { + RoomId = acc.RoomId, + Role = role, + CellCount = acc.CellCount, + BedCount = acc.BedCount, + WorktableCount = acc.WorktableCount, + TableCount = acc.TableCount, + CenterX = (int)(acc.SumX / acc.CellCount), + CenterZ = (int)(acc.SumZ / acc.CellCount), + IsEnclosed = true + }); + } + + return snapshot; + } + + private static string InferRoomRole(RoomAccumulator acc) + { + if (acc.BedCount > 1) return "Barracks"; + if (acc.BedCount == 1) return "Bedroom"; + if (acc.WorktableCount > 0) return "Workshop"; + if (acc.TableCount > 0) return "Dining"; + return "Indoor"; + } + + private static void DetermineColonyAnchor( + Map map, + int fallbackX, + int fallbackZ, + out int anchorX, + out int anchorZ, + out bool hasBaseAnchor) + { + long sumX = 0; + long sumZ = 0; + int count = 0; + + var buildings = map.listerBuildings?.allBuildingsColonist; + if (buildings != null) + { + int limit = Math.Min(buildings.Count, 200); + for (int i = 0; i < limit; i++) + { + Building b = buildings[i]; + if (b == null || !b.Spawned || b.Destroyed) continue; + if (b.def != null && b.def.passability == Traversability.Impassable) continue; + sumX += b.Position.x; + sumZ += b.Position.z; + count++; + } + + if (count == 0) + { + for (int i = 0; i < limit; i++) + { + Building b = buildings[i]; + if (b == null || !b.Spawned || b.Destroyed) continue; + sumX += b.Position.x; + sumZ += b.Position.z; + count++; + } + } + } + + if (count == 0 && map.zoneManager?.AllZones != null) + { + foreach (Zone z in map.zoneManager.AllZones) + { + if (z is Zone_Stockpile && z.Cells.Count > 0) + { + sumX += z.Position.x; + sumZ += z.Position.z; + count++; + } + } + } + + if (count > 0) + { + anchorX = (int)(sumX / count); + anchorZ = (int)(sumZ / count); + hasBaseAnchor = true; + return; + } + + anchorX = fallbackX; + anchorZ = fallbackZ; + hasBaseAnchor = false; + } + } +} +#endif diff --git a/Tests/ColonySpatialClusterSolverTests.cs b/Tests/ColonySpatialClusterSolverTests.cs new file mode 100644 index 0000000..fd28593 --- /dev/null +++ b/Tests/ColonySpatialClusterSolverTests.cs @@ -0,0 +1,187 @@ +using System.Collections.Generic; +using RimMind.Actions.Spatial; +using Xunit; + +namespace RimMind.Actions.Tests +{ + public sealed class ColonySpatialClusterSolverTests + { + private static ColonySpatialSnapshot BuildBedroomAndWorkshopSnapshot() + { + var snapshot = new ColonySpatialSnapshot(0, 0, 24, 24); + snapshot.ColonyAnchorX = 12; + snapshot.ColonyAnchorZ = 12; + snapshot.HasBaseAnchor = true; + + for (int x = 0; x <= 23; x++) + { + for (int z = 0; z <= 23; z++) + { + snapshot.SetCell(x, z, SpatialCellKind.OutdoorFloor, roomId: 0, roofed: false); + } + } + + // Room 1 (Bedroom): x=8..14, z=10..15 with door at (8, 12) + snapshot.AddRoom(new SpatialRoomSummary + { + RoomId = 1, + Role = "Bedroom", + CellCount = 20, + BedCount = 1, + CenterX = 11, + CenterZ = 12, + IsEnclosed = true + }); + FillEnclosedRoom(snapshot, 8, 14, 10, 15, roomId: 1, doorX: 8, doorZ: 12); + + // Place existing bed inside bedroom away from door at (13, 14) + snapshot.SetCell(13, 14, SpatialCellKind.OccupiedFurniture, roomId: 1, roofed: true); + snapshot.Peers.Add(new SpatialPeerItem + { + DefName = "Bed", + Category = SpatialBuildingCategory.Sleeping, + X = 13, + Z = 14, + RoomId = 1, + IsBlueprint = false + }); + + // Room 2 (Workshop): x=16..22, z=10..15 with door at (16, 12) + snapshot.AddRoom(new SpatialRoomSummary + { + RoomId = 2, + Role = "Workshop", + CellCount = 20, + WorktableCount = 1, + CenterX = 19, + CenterZ = 12, + IsEnclosed = true + }); + FillEnclosedRoom(snapshot, 16, 22, 10, 15, roomId: 2, doorX: 16, doorZ: 12); + + // Existing worktable at (20, 14) + snapshot.SetCell(20, 14, SpatialCellKind.OccupiedFurniture, roomId: 2, roofed: true); + snapshot.Peers.Add(new SpatialPeerItem + { + DefName = "TableButcher", + Category = SpatialBuildingCategory.Production, + X = 20, + Z = 14, + RoomId = 2, + IsBlueprint = false + }); + + return snapshot; + } + + private static void FillEnclosedRoom( + ColonySpatialSnapshot snapshot, + int minX, + int maxX, + int minZ, + int maxZ, + int roomId, + int doorX, + int doorZ) + { + for (int x = minX; x <= maxX; x++) + { + for (int z = minZ; z <= maxZ; z++) + { + bool isPerimeter = x == minX || x == maxX || z == minZ || z == maxZ; + if (x == doorX && z == doorZ) + { + snapshot.SetCell(x, z, SpatialCellKind.Door, roomId: 0, roofed: true); + } + else if (isPerimeter) + { + snapshot.SetCell(x, z, SpatialCellKind.Wall, roomId: 0, roofed: true); + } + else + { + snapshot.SetCell(x, z, SpatialCellKind.IndoorRoom, roomId: roomId, roofed: true); + } + } + } + } + + [Fact] + public void Bed_placement_prefers_enclosed_bedroom_wall_and_clusters_near_peer_bed_away_from_door() + { + ColonySpatialSnapshot snapshot = BuildBedroomAndWorkshopSnapshot(); + var request = new SpatialPlacementRequest + { + BuildingDefName = "Bed", + Category = SpatialBuildingCategory.Sleeping, + SizeX = 1, + SizeZ = 1, + LocationHint = "near_base", + AnchorX = 2, + AnchorZ = 2 + }; + + List ranked = ColonySpatialClusterSolver.RankCandidates(snapshot, request); + Assert.NotEmpty(ranked); + + SpatialCandidateScore top = ranked[0]; + Assert.Equal(1, top.RoomId); + Assert.True(top.X > 8 && top.X < 14); + Assert.True(top.Z > 10 && top.Z < 15); + Assert.NotEqual(9, top.X); // Not blocking the doorway at (8, 12) when top-right wall cells exist + } + + [Fact] + public void Worktable_placement_prefers_workshop_and_rejects_blocked_interaction_cell() + { + ColonySpatialSnapshot snapshot = BuildBedroomAndWorkshopSnapshot(); + var request = new SpatialPlacementRequest + { + BuildingDefName = "ElectricSmithy", + Category = SpatialBuildingCategory.Production, + SizeX = 2, + SizeZ = 1, + HasInteractionCell = true, + InteractionOffsetX = 0, + InteractionOffsetZ = -1, + LocationHint = "near_base", + AnchorX = 2, + AnchorZ = 2 + }; + + List ranked = ColonySpatialClusterSolver.RankCandidates(snapshot, request); + Assert.NotEmpty(ranked); + + SpatialCandidateScore top = ranked[0]; + Assert.Equal(2, top.RoomId); + // Interaction cell at (top.X, top.Z - 1) must remain strictly passable (not Wall at z=10) + Assert.True(top.Z > 11); + } + + [Fact] + public void Outdoor_location_hint_and_ascii_grid_renderer_work_deterministically() + { + ColonySpatialSnapshot snapshot = BuildBedroomAndWorkshopSnapshot(); + var outdoorReq = new SpatialPlacementRequest + { + BuildingDefName = "Campfire", + Category = SpatialBuildingCategory.TemperatureLight, + SizeX = 1, + SizeZ = 1, + LocationHint = "outdoor", + AnchorX = 4, + AnchorZ = 4 + }; + + List ranked = ColonySpatialClusterSolver.RankCandidates(snapshot, outdoorReq); + Assert.NotEmpty(ranked); + Assert.Equal(0, ranked[0].RoomId); + + string grid = ColonySpatialClusterSolver.RenderCompactAsciiGrid(snapshot, centerX: 11, centerZ: 12, radius: 6); + Assert.Contains("Legend:", grid); + Assert.Contains("#", grid); + Assert.Contains("+", grid); + Assert.Contains("B", grid); + Assert.Contains("@", grid); + } + } +} diff --git a/Tests/CompositeToolSelfDescriptionContracts.cs b/Tests/CompositeToolSelfDescriptionContracts.cs index 376365a..43deeb4 100644 --- a/Tests/CompositeToolSelfDescriptionContracts.cs +++ b/Tests/CompositeToolSelfDescriptionContracts.cs @@ -98,8 +98,8 @@ public void PolicyClassifier_Classifies_Survival_Vs_NonSurvival_Arguments_Identi ToolName = placeBlueprint.Id, ArgumentsJson = "{\"building_def\":\"SculptureSmall\"}" }); - Assert.Equal(AutonomyDomain.EmergencySurvival, bedPolicy.Domain); - Assert.Equal(RiskLevel.Low, bedPolicy.Risk); + Assert.Equal(AutonomyDomain.BlueprintPlacement, bedPolicy.Domain); + Assert.Equal(RiskLevel.Medium, bedPolicy.Risk); Assert.Equal(AutonomyDomain.BlueprintPlacement, statuePolicy.Domain); Assert.Equal(RiskLevel.Medium, statuePolicy.Risk); @@ -130,8 +130,8 @@ public void PolicyClassifier_Classifies_Survival_Vs_NonSurvival_Arguments_Identi ToolName = planRoom.Id, ArgumentsJson = "{\"room_type\":\"Storage\"}" }); - Assert.Equal(AutonomyDomain.EmergencySurvival, shelterPolicy.Domain); - Assert.Equal(RiskLevel.Low, shelterPolicy.Risk); + Assert.Equal(AutonomyDomain.BlueprintPlacement, shelterPolicy.Domain); + Assert.Equal(RiskLevel.Medium, shelterPolicy.Risk); Assert.Equal(AutonomyDomain.BlueprintPlacement, storagePolicy.Domain); Assert.Equal(RiskLevel.Medium, storagePolicy.Risk); } @@ -159,6 +159,14 @@ public void ActionsToolArgumentAdapter_Adapts_CropDesignations_And_RecoveryReaso 1); Assert.Equal("ChopWood", oakArgs["designation_type"]?.ToString()); + // Starving colonies must be able to request hunting via a plain target hint. + var huntArgs = adapter.AdaptArguments( + "actions_designate_resources", + JObject.Parse("{\"target_name\":\"wild animals for meat\"}"), + new AgentDecision { ActionIntent = "designate_map_order" }, + 1); + Assert.Equal("Hunt", huntArgs["designation_type"]?.ToString()); + var restArgs = adapter.AdaptArguments( "actions.stabilize_rest", new JObject(), diff --git a/Tests/PlaceBlueprintCompositeToolTests.cs b/Tests/PlaceBlueprintCompositeToolTests.cs index d3bf0ca..88a85c4 100644 --- a/Tests/PlaceBlueprintCompositeToolTests.cs +++ b/Tests/PlaceBlueprintCompositeToolTests.cs @@ -54,5 +54,17 @@ public void PlaceBlueprint_Integrates_AgentIntentSession_Chaining() Assert.Contains("WorkGiver_ConstructDeliverResourcesToFrames", source); Assert.Contains("StartIntentSession", source); } + + [Fact] + public void AllCompositeTools_Use_NullSafe_DefName_And_Label_Comparisons() + { + var actionsDir = Path.Combine(RepoRoot, "RimMind-Actions", "Source", "Actions"); + foreach (var file in Directory.GetFiles(actionsDir, "*CompositeTool.cs")) + { + var source = File.ReadAllText(file); + Assert.DoesNotContain(".label.Equals(", source); + Assert.DoesNotContain(".defName.Equals(", source); + } + } } } diff --git a/Tests/RimMindActions.Tests.csproj b/Tests/RimMindActions.Tests.csproj index cfdb8e1..769ed6f 100644 --- a/Tests/RimMindActions.Tests.csproj +++ b/Tests/RimMindActions.Tests.csproj @@ -59,6 +59,8 @@ + +