RacesOfValheim/JotunnModStub/RaceCaveBuilding.cs
kanym b0d18b0654 feat(text): on-screen messages come from translation files
Every message the mod puts in the middle or corner of the screen now reads
its text through ModText.Get, and messages.json holds 191 texts in English
and Italian. Values computed in code become $1, $2 in the text, so a
translator can put them wherever the sentence needs them. Branching
messages get one key per branch.

A few messages travel through a field before they are shown: thralls'
refusals and the building limits now hold a token or key there. Boss and
form names inside messages use tokens too, the bosses the game's own, so
"The Elder" arrives translated.

ModText.Get now localizes each argument before inserting it. A token
argument left for a later pass ran into the text after it: "$1's power"
became the unknown token "enemy_eikthyr's".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:30:03 +02:00

225 lines
10 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// "A troll cave is a house, if you are the right sort of thing."
///
/// Skadi and Trol may build inside ANY troll cave in the world.
///
/// THE ACTUAL RESTRICTION, found only after the game was asked instead of guessed at: a troll
/// cave counts as a DUNGEON, and Valheim refuses any piece whose Piece.m_allowedInDungeons is
/// false while the player is in one - "Can't build in a dungeon". That is a per-PIECE flag, not a
/// per-location one.
///
/// Two earlier versions of this file cleared Location.m_noBuild instead. That is a real
/// restriction and it is still cleared below, but it was never the one refusing these
/// placements, which is why lifting it changed nothing twice in a row. The lesson is in the log
/// line this class now prints: Player.m_placementStatus names the exact reason, and reading it
/// would have answered the question on the first report rather than the third.
///
/// The flag is flipped only while an eligible player is actually standing in a troll cave, and
/// put back when they leave, so this does not quietly become "build anywhere in any crypt". It
/// touches only the pieces on the build tables the player is carrying, and placement checks are
/// client-side, so nobody else's game is affected.
/// </summary>
public class RaceCaveBuilding : MonoBehaviour
{
/// <summary>Matches both troll cave locations this build has: TrollCave and TrollCave02.</summary>
private const string CaveNameFragment = "TrollCave";
/// <summary>Slack on the location's own radius, since the inside of a cave is not a neat sphere.</summary>
private const float RadiusSlack = 12f;
/// <summary>
/// How far from a troll cave mouth a refusal is still worth logging. Wide enough to catch
/// "standing at the mouth but not detected", far too narrow to catch the ordinary "can't
/// build here" that happens anywhere else in the world and has nothing to do with caves.
/// </summary>
private const float ReportRadius = 100f;
private const float CheckInterval = 0.25f;
private float nextCheck;
private bool allowing;
private readonly List<Piece> flipped = new List<Piece>();
private string lastReport;
private string lastHow = "not checked yet";
private void Update()
{
if (Time.time < nextCheck) return;
nextCheck = Time.time + CheckInterval;
Player player = Player.m_localPlayer;
if (player == null) return;
if (!SkadiRace.IsLocalSkadi() && !TrolRace.IsTrol())
{
Restore();
return;
}
bool inCave = IsInTrollCave(player, out string how);
lastHow = how;
if (inCave && !allowing) Allow(player);
else if (!inCave && allowing) Restore();
ReportWhyIfRefused(player);
}
/// <summary>
/// Two ways of asking, because the two cases are genuinely different.
///
/// FIRST, Location.GetLocation(point, checkDungeons: true). That flag exists for exactly this
/// question - "which location owns this point, counting dungeon interiors" - and it is the
/// only one of the two that can answer it when the interior is not where the mouth is. The
/// previous version of this file dropped it in favour of a distance sweep, and that is why
/// the log said "in troll cave=False" while the player was standing in one: a distance test
/// against the mouth cannot find a player who is inside.
///
/// SECOND, the sweep, kept as the case the first one is weakest at: standing at the mouth,
/// outside, where there is no interior to own the point.
/// </summary>
private static bool IsInTrollCave(Player player, out string how)
{
Vector3 position = player.transform.position;
Location owning = Location.GetLocation(position, true);
if (owning != null && IsTrollCave(owning))
{
LiftOutrightBan(owning);
how = $"GetLocation -> {owning.gameObject.name}";
return true;
}
foreach (Location location in Object.FindObjectsByType<Location>(FindObjectsSortMode.None))
{
if (location == null || !IsTrollCave(location)) continue;
if (Vector3.Distance(position, location.transform.position) > location.GetMaxRadius() + RadiusSlack) continue;
LiftOutrightBan(location);
how = $"nearby -> {location.gameObject.name}";
return true;
}
how = owning != null ? $"owned by '{owning.gameObject.name}', not a cave" : "no location owns this point";
return false;
}
private static bool IsTrollCave(Location location)
{
return location.gameObject.name.IndexOf(CaveNameFragment, System.StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary>
/// Cheap and harmless while we are here: a location may also forbid building outright, and
/// that ban would beat everything else. It is NOT what refuses a piece in a troll cave - that
/// was two wrong guesses ago - but a cave that did set it would be unbuildable for a second,
/// separate reason.
/// </summary>
private static void LiftOutrightBan(Location location)
{
if (!location.m_noBuild) return;
location.m_noBuild = false;
Jotunn.Logger.LogInfo($"[Races] '{location.gameObject.name}' also forbade building outright; cleared that too.");
}
/// <summary>
/// Marks every piece on the build tables the player is carrying as dungeon-legal, remembering
/// which ones were not so they can be put back exactly as they were.
/// </summary>
private void Allow(Player player)
{
Inventory inventory = player.GetInventory();
if (inventory == null) return;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
PieceTable table = item?.m_shared?.m_buildPieces;
if (table == null || table.m_pieces == null) continue;
foreach (GameObject entry in table.m_pieces)
{
Piece piece = entry != null ? entry.GetComponent<Piece>() : null;
if (piece == null || piece.m_allowedInDungeons) continue;
piece.m_allowedInDungeons = true;
flipped.Add(piece);
}
}
allowing = true;
Jotunn.Logger.LogInfo($"[Races] In a troll cave: {flipped.Count} pieces temporarily allowed in dungeons.");
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_build_this_cave_will_hold_what"));
}
/// <summary>
/// Puts the flags back. Without this the permission would follow the player into every crypt
/// and sunken chamber in the world, which is not what was asked for.
/// </summary>
private void Restore()
{
if (!allowing) return;
foreach (Piece piece in flipped)
{
if (piece != null) piece.m_allowedInDungeons = false;
}
Jotunn.Logger.LogInfo($"[Races] Left the troll cave: {flipped.Count} pieces set back to dungeon-forbidden.");
flipped.Clear();
allowing = false;
}
private void OnDestroy()
{
Restore();
}
/// <summary>
/// Says, in the log, exactly why the game is refusing a placement right now. m_placementStatus
/// is private and Player cannot be inspected offline at all, so it is read with Traverse and
/// printed by name - the enum's own ToString does the translating, so this cannot fall out of
/// step with the game's own list of reasons. Only speaks when the answer changes.
/// </summary>
private void ReportWhyIfRefused(Player player)
{
object status = Traverse.Create(player).Field("m_placementStatus").GetValue();
if (status == null) return;
string statusName = status.ToString();
if (statusName == "Valid") { lastReport = null; return; }
// The player's own position and the distance to the nearest troll cave MOUTH are here for
// one reason: if a refusal ever survives with "in troll cave=False", these two numbers say
// whether the interior sits near its mouth or has been relocated somewhere else entirely -
// which is the difference between a tolerance to widen and a wrong idea about the world.
Vector3 position = player.transform.position;
string nearest = "<none in this world>";
float distance = float.PositiveInfinity;
if (ZoneSystem.instance != null
&& ZoneSystem.instance.FindClosestLocation("TrollCave02", position, out ZoneSystem.LocationInstance closest))
{
distance = Vector3.Distance(position, closest.m_position);
nearest = $"{distance:0} m away at {closest.m_position}";
}
// Not worth logging anywhere but near a cave - otherwise this fires on every ordinary
// "can't build here" a Trol/Skadi player runs into across the rest of the world.
if (!allowing && distance > ReportRadius) { lastReport = null; return; }
string report = statusName + "|" + lastHow;
if (report == lastReport) return;
lastReport = report;
Jotunn.Logger.LogInfo($"[Races] Placement refused: {statusName} " +
$"(in troll cave={allowing}, pieces flipped={flipped.Count}). " +
$"Detection said: {lastHow}. Player at {position}; nearest TrollCave02 mouth {nearest}.");
}
}
}