Merge branch 'localisation' into localisation-turkish

This commit is contained in:
kanym 2026-10-28 13:57:24 +01:00
commit fcdea70ee1
24 changed files with 942 additions and 13 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 441 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

View file

@ -218,6 +218,7 @@ namespace RacesOfValheim
}
prefab.transform.localScale = Vector3.one * TableScale;
Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
table.m_switch = prefab.AddComponent<Switch>();
@ -255,6 +256,65 @@ namespace RacesOfValheim
}));
}
// The look, in the table's own space BEFORE TableScale, so sizes are divided by it to come out
// in real metres. The cover lies where the map was: x -2.06 to 0.62, read off the mesh. Its top
// is the Dvergar bank's PileHeight, on the same vanilla mesh; the mesh's own height is no use
// here, since the writing desk stands taller than the map.
private const float CoverTop = 1.05f;
private static readonly Vector3 TradeSpot = new Vector3(-0.75f, CoverTop, 0.2f);
private static readonly Vector3 SkullSpot = new Vector3(-1.55f, CoverTop, 0.35f);
private const float AnvilSize = 0.75f;
private const float MealSize = 0.6f;
private const float SkullSize = 0.45f;
/// <summary>
/// The map painted over - a sheet of chainmail for the smith, a red and white tablecloth for the
/// cook - with the trade's own work on it (an anvil, a meal) and a skeleton's skull beside it.
/// </summary>
private static void Dress(GameObject prefab, ButlerFamily family)
{
bool forge = family == ButlerFamily.Forge;
LayCover(prefab, forge ? "SmithMail" : "CookCloth", metal: forge);
float metres = 1f / TableScale;
if (forge)
{
ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
TradeSpot, Quaternion.identity, AnvilSize * metres, "Butler", activeOnly: true);
}
else
{
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
TradeSpot, Quaternion.identity, MealSize * metres, "Butler", activeOnly: true);
}
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot, Quaternion.Euler(0f, -150f, 0f), SkullSize * metres, "Butler", activeOnly: true);
}
/// <summary>
/// The cartography table's own textures with the map painted over, offline:
/// scripts/paint_cook_cloth.py (CookCloth) and scripts/paint_smith_mail.py (SmithMail). Each set
/// has its own worn texture for a damaged table (a stained cloth, rusted mail) and its own normal
/// map, so the coastline's relief does not show through. The mail also brings a metallic map,
/// which is what makes the rings shine; the cloth keeps vanilla's, which is metal nowhere.
/// </summary>
private static void LayCover(GameObject prefab, string set, bool metal)
{
var cover = new System.Collections.Generic.Dictionary<string, Texture>();
AddCover(cover, "Cartographer_d", set + "_d.png", false);
AddCover(cover, "Cartographer_worn_d", set + "_worn_d.png", false);
AddCover(cover, "Cartographer_n", set + "_n.png", true);
if (metal) AddCover(cover, "Cartographer_m", set + "_m.png", true);
PieceLook.Retexture(prefab.transform, cover);
}
private static void AddCover(System.Collections.Generic.Dictionary<string, Texture> cover,
string vanilla, string resource, bool linear)
{
Texture2D texture = PieceLook.LoadTexture(resource, linear);
if (texture != null) cover[vanilla] = texture;
}
public static void EnsureKnown(Player player)
{
if (player == null) return;

View file

@ -143,7 +143,8 @@ namespace RacesOfValheim
string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting");
return m_title + "\n" + status;
// m_title is a $token, and a hover text goes to the HUD as it is: nothing localizes it later.
return Localization.instance.Localize(m_title) + "\n" + status;
}
/// <summary>

View file

@ -76,6 +76,12 @@ namespace RacesOfValheim
private const float PileHeight = 1.05f;
private const float PileSize = 0.45f;
// The dressing, in the same unscaled table space as the pile. The pile owns the centre, so the
// tankard stands just clear of it, on the near side.
private static readonly Color BankWoodTint = new Color(0.62f, 0.55f, 0.5f, 1f);
private static readonly Vector3 TankardSpot = new Vector3(0.45f, PileHeight, -0.25f);
private const float TankardSize = 0.38f;
public class Troop
{
public string Id;
@ -276,6 +282,12 @@ namespace RacesOfValheim
prefab.transform.localScale = Vector3.one * TableScale;
// A counting table, not a map table: darker wood and a dvergr tankard beside the coin.
// Tinted BEFORE the tankard goes on, or it would be darkened too.
PieceLook.Tint(prefab.transform, BankWoodTint);
ModelBorrow.Attach(prefab.transform, "BankTankard", "Tankard_dvergr",
TankardSpot, Quaternion.identity, TankardSize, "Dvergar", activeOnly: true);
DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))

View file

@ -36,10 +36,13 @@ namespace RacesOfValheim
/// <paramref name="localPosition"/> is where the model's BOTTOM CENTRE goes.
/// <paramref name="targetSize"/> is how big its largest dimension should end up, in metres,
/// measured AFTER <paramref name="localRotation"/> has been applied.
/// <paramref name="activeOnly"/> drops every child the source keeps switched off before measuring.
/// A build piece carries its snow cover, its fire, its worn and broken meshes that way, and they
/// count towards the size: the cauldron's hidden tripod legs are two metres long.
/// </summary>
public static GameObject Attach(Transform parent, string holderName, string sourcePrefab,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
string label, bool activeOnly = false)
{
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null)
@ -52,7 +55,7 @@ namespace RacesOfValheim
return empty;
}
return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label);
return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label, activeOnly);
}
/// <summary>
@ -66,7 +69,7 @@ namespace RacesOfValheim
/// </summary>
public static GameObject Attach(Transform parent, string holderName, GameObject source,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
string label, bool activeOnly = false)
{
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(parent, false);
@ -110,6 +113,16 @@ namespace RacesOfValheim
if (nview != null) Object.DestroyImmediate(nview);
}
if (activeOnly)
{
foreach (Transform child in copy.GetComponentsInChildren<Transform>(true))
{
// Null once an inactive parent above it has already gone.
if (child == null || child == copy.transform || child.gameObject.activeSelf) continue;
Object.DestroyImmediate(child.gameObject);
}
}
FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label);
holder.SetActive(true);

View file

@ -1,7 +1,7 @@
{
"name": "RacesOfValheim",
"description": "A Valheim mod that adds eleven custom playable races (Alfar, Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.",
"version_number": "1.6.2",
"version_number": "1.6.3",
"website_url": "",
"dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333",

197
JotunnModStub/PieceLook.cs Normal file
View file

@ -0,0 +1,197 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Recolouring a cloned vanilla piece without touching the original.
///
/// A clone made by CreateClonedPrefab shares its MATERIALS with the vanilla prefab, so writing a
/// colour onto renderer.sharedMaterial would repaint every Ward or cartography table in the world.
/// Each material is copied once and the copy is written; renderers that shared one material before
/// share the one copy after, so the LOD, worn and broken meshes stay matched.
/// </summary>
public static class PieceLook
{
/// <summary>
/// Multiplies the base colour of every mesh under <paramref name="root"/>, inactive ones included
/// (a piece's worn and broken meshes are switched off until it takes damage). Particles are left
/// alone: that is what <see cref="Rehue"/> is for.
/// </summary>
public static void Tint(Transform root, Color tint)
{
if (root == null) return;
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] materials = renderer.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
Material copy = CopyOf(materials[i], copies);
if (copy == null) continue;
if (copy.HasProperty("_Color")) copy.SetColor("_Color", copy.GetColor("_Color") * tint);
materials[i] = copy;
}
renderer.sharedMaterials = materials;
}
}
/// <summary>
/// Swaps the hue of everything under <paramref name="root"/> that GLOWS - lights, particles and
/// any material with emission - for <paramref name="glow"/>, keeping each one's brightness.
///
/// Brightness is kept rather than overwritten because these values are not 0 to 1: the Ward's
/// sparks are authored at a colour of 2.0, and painting them a flat 1.0 blue would dim them by
/// half. A material whose emission is black does not glow and is skipped, so the Ward's stone
/// stays stone.
/// </summary>
public static void Rehue(Transform root, Color glow)
{
if (root == null) return;
foreach (Light light in root.GetComponentsInChildren<Light>(true))
{
if (light != null) light.color = glow;
}
foreach (ParticleSystem ps in root.GetComponentsInChildren<ParticleSystem>(true))
{
if (ps == null) continue;
ParticleSystem.MainModule main = ps.main;
main.startColor = new ParticleSystem.MinMaxGradient(glow);
}
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
bool particles = renderer is ParticleSystemRenderer;
Material[] materials = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < materials.Length; i++)
{
Material source = materials[i];
if (source == null) continue;
bool emits = source.HasProperty("_EmissionColor") && Brightness(source.GetColor("_EmissionColor")) > 0.01f;
if (!emits && !particles) continue;
Material copy = CopyOf(source, copies);
if (emits) Recolour(copy, "_EmissionColor", glow);
if (particles)
{
Recolour(copy, "_Color", glow);
Recolour(copy, "_TintColor", glow);
}
materials[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = materials;
}
}
/// <summary>
/// Swaps textures by the name of the texture they replace: every material under
/// <paramref name="root"/> that uses "Cartographer_d" gets <paramref name="replacements"/>'s
/// "Cartographer_d" instead, whichever slot it sits in. Materials are copied as in Tint.
/// </summary>
public static void Retexture(Transform root, IDictionary<string, Texture> replacements)
{
if (root == null) return;
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] materials = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < materials.Length; i++)
{
Material source = materials[i];
if (source == null) continue;
foreach (string property in source.GetTexturePropertyNames())
{
Texture current = source.GetTexture(property);
if (current == null || !replacements.TryGetValue(current.name, out Texture replacement)) continue;
Material copy = CopyOf(source, copies);
copy.SetTexture(property, replacement);
materials[i] = copy;
changed = true;
}
}
if (changed) renderer.sharedMaterials = materials;
}
}
/// <summary>
/// ImageConversion.LoadImage, found at run time. Its module is built against netstandard 2.1 and
/// this project targets net48, so referencing it at compile time fails the build (CS1705); the
/// game has the module loaded either way.
/// </summary>
private static readonly System.Reflection.MethodInfo LoadImage =
System.Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")
?.GetMethod("LoadImage", new[] { typeof(Texture2D), typeof(byte[]), typeof(bool) });
/// <summary>
/// A PNG embedded in the DLL (see the csproj's EmbeddedResource), or null with a warning.
/// <paramref name="linear"/> for anything that is data rather than colour - a normal map read
/// as sRGB comes out bent.
/// </summary>
public static Texture2D LoadTexture(string resource, bool linear = false)
{
using (System.IO.Stream stream = typeof(PieceLook).Assembly.GetManifestResourceStream(resource))
{
if (stream == null)
{
Jotunn.Logger.LogWarning($"No embedded texture '{resource}'.");
return null;
}
byte[] bytes = new byte[stream.Length];
int read = 0;
while (read < bytes.Length) read += stream.Read(bytes, read, bytes.Length - read);
Texture2D texture = new Texture2D(2, 2, TextureFormat.RGBA32, true, linear)
{
name = System.IO.Path.GetFileNameWithoutExtension(resource),
anisoLevel = 4,
};
if (LoadImage == null || !(bool)LoadImage.Invoke(null, new object[] { texture, bytes, true }))
{
Jotunn.Logger.LogWarning($"Embedded texture '{resource}' would not decode.");
return null;
}
return texture;
}
}
private static void Recolour(Material material, string property, Color glow)
{
if (!material.HasProperty(property)) return;
Color old = material.GetColor(property);
Color hue = glow * Brightness(old);
hue.a = old.a;
material.SetColor(property, hue);
}
private static float Brightness(Color colour) => Mathf.Max(colour.r, Mathf.Max(colour.g, colour.b));
private static Material CopyOf(Material source, Dictionary<Material, Material> copies)
{
if (source == null) return null;
if (!copies.TryGetValue(source, out Material copy))
{
copy = new Material(source) { name = source.name + "_rov" };
copies[source] = copy;
}
return copy;
}
}
}

View file

@ -44,6 +44,8 @@ namespace RacesOfValheim
prefab.AddComponent<RaceMenuWardBehavior>();
Restyle(prefab);
PieceConfig config = new PieceConfig
{
Name = "$rov_piece_racemenuward_name",
@ -60,6 +62,44 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config));
}
// ---------------------------------------------------------------- the look
/// <summary>Seidr blue in place of the Ward's hearth orange: every race builds this, so no race's colour.</summary>
private static readonly Color Glow = new Color(0.55f, 0.62f, 1f, 1f);
/// <summary>A colder stone, so it reads as a different thing from the vanilla Ward across a base.</summary>
private static readonly Color StoneTint = new Color(0.78f, 0.82f, 0.92f, 1f);
/// <summary>Narrower and taller than the Ward, on a plinth: a statue rather than a waystone.</summary>
private static readonly Vector3 StatueShape = new Vector3(0.9f, 1.12f, 0.9f);
private const float PlinthWidth = 1.3f;
/// <summary>
/// Odin's stone on a plinth, glowing blue. The statue, its light and its sparks are lifted by the
/// plinth's MEASURED height, so a different plinth model needs no new offset.
/// </summary>
private static void Restyle(GameObject prefab)
{
Transform statue = prefab.transform.Find("new");
if (statue == null)
{
Jotunn.Logger.LogWarning("guard_stone has no 'new' model; the Race Menu Ward keeps the vanilla look.");
return;
}
PieceLook.Tint(statue, StoneTint);
PieceLook.Rehue(prefab.transform, Glow);
statue.localScale = Vector3.Scale(statue.localScale, StatueShape);
GameObject plinth = ModelBorrow.Attach(prefab.transform, "WardPlinth", "stone_floor_2x2",
Vector3.zero, Quaternion.identity, PlinthWidth,
"RaceMenuWard", activeOnly: true);
float lift = ModelBorrow.HeightOf(plinth);
foreach (string child in new[] { "new", "WayEffect", "GuidePoint" })
{
Transform part = prefab.transform.Find(child);
if (part != null) part.localPosition += Vector3.up * lift;
}
}
// Marks a world as already having its starter ward, so it is placed exactly once rather
// than every time someone loads in.
private const string PlacedKey = "RacesOfValheim_StarterWardPlaced";

View file

@ -16,7 +16,7 @@ namespace RacesOfValheim
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.6.2";
public const string PluginVersion = "1.6.3";
private readonly Harmony harmony = new Harmony(PluginGUID);
@ -89,6 +89,7 @@ namespace RacesOfValheim
CommandManager.Instance.AddConsoleCommand(new AlfarEitrCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarHpCommand());
CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand());
CommandManager.Instance.AddConsoleCommand(new TrolPoseCommand());
CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand());
}

View file

@ -53,6 +53,12 @@
<Reference Include="System.Xml" />
</ItemGroup>
<!-- Textures painted offline (scripts/paint_cook_cloth.py), carried inside the DLL so a mod
manager has no extra folder to flatten. Loaded by name: PieceLook.LoadTexture("CookCloth_d.png"). -->
<ItemGroup>
<EmbeddedResource Include="Assets\**\*.png" LogicalName="%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />

View file

@ -0,0 +1,112 @@
using System.Globalization;
using Jotunn.Entities;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// [DEBUG] Tries troll states as the True Form guard and roll, live, until the right frame is
/// found and baked into TrolTrueFormModel. Nothing is saved: a restart goes back to the defaults.
/// </summary>
public class TrolPoseCommand : ConsoleCommand
{
// Off troll_animator with scripts/dump_controller.py. Wakeup? and the AnyState entries left
// out: an entry check and transitions, not poses.
private static readonly string[] States =
{
"Movement", "attack", "jump", "punch", "throw", "swing log V", "swing log H",
"Stagger", "Summon", "Sleeping", "Wakeup", "In Water",
};
public override string Name => "trolpose";
public override string Help =>
"[DEBUG] trolpose guard <state> [0-1] - the frame True Form holds while blocking. " +
"trolpose play <state> - plays a state whole on your troll. " +
"trolpose dodge <state|off> [speed] - the state played when you roll, and how fast. trolpose - lists states and current values.";
public override void Run(string[] args)
{
if (args.Length == 0)
{
Print($"guard: '{TrolTrueFormModel.GuardState}' at {TrolTrueFormModel.GuardTime:0.00}, " +
$"dodge: '{TrolTrueFormModel.DodgeState ?? "off"}' at speed {TrolTrueFormModel.DodgeSpeed:0.00}");
Print("states: " + string.Join(", ", States));
return;
}
string verb = args[0].ToLowerInvariant();
float time = -1f;
int nameEnd = args.Length;
// The trailing number: the frame for guard, the speed for dodge.
if ((verb == "guard" || verb == "dodge") && args.Length > 2 &&
float.TryParse(args[args.Length - 1], NumberStyles.Float, CultureInfo.InvariantCulture, out float number))
{
time = number;
nameEnd--;
}
string typed = string.Join(" ", args, 1, Mathf.Max(0, nameEnd - 1));
if (verb == "dodge" && typed.ToLowerInvariant() == "off")
{
TrolTrueFormModel.DodgeState = null;
Print("dodge: off");
return;
}
string state = Match(typed);
if (state == null)
{
Print($"unknown state '{typed}'. states: " + string.Join(", ", States));
return;
}
switch (verb)
{
case "guard":
TrolTrueFormModel.GuardState = state;
if (time >= 0f) TrolTrueFormModel.GuardTime = Mathf.Clamp01(time);
Print($"guard: '{state}' at {TrolTrueFormModel.GuardTime:0.00}. Hold right click in True Form to see it.");
break;
case "dodge":
TrolTrueFormModel.DodgeState = state;
if (time > 0f) TrolTrueFormModel.DodgeSpeed = Mathf.Clamp(time, 0.25f, 5f);
Print($"dodge: '{state}' at speed {TrolTrueFormModel.DodgeSpeed:0.00}. Block and jump in True Form to roll.");
break;
case "play":
Animator anim = TrolTrueFormModel.LocalAnimator;
if (anim == null)
{
Print("play needs True Form on (not Legacy).");
return;
}
anim.speed = 1f;
anim.CrossFadeInFixedTime("Base Layer." + state, 0.1f, 0, 0f);
Print($"playing '{state}'.");
break;
default:
Print(Help);
break;
}
}
private static string Match(string typed)
{
foreach (string s in States)
{
if (string.Equals(s, typed, System.StringComparison.OrdinalIgnoreCase)) return s;
}
return null;
}
private static void Print(string line)
{
Jotunn.Logger.LogInfo("[Trol] trolpose " + line);
if (Console.instance != null) Console.instance.Print(line);
}
}
}

View file

@ -27,6 +27,9 @@ namespace RacesOfValheim
private bool isAttacking;
private float busySince = -1f;
private bool guarding;
private bool dodging;
private readonly TrolGuardPose guardPose = new TrolGuardPose();
private GameObject heldLog;
private string heldLogName;
@ -42,6 +45,8 @@ namespace RacesOfValheim
private void OnDestroy()
{
TrolTrueFormModel.LocalAttacking = false;
TrolTrueFormModel.EndDodge();
if (guarding && Player.m_localPlayer != null) TrolTrueFormModel.PublishGuard(Player.m_localPlayer, false);
}
private void Start()
@ -84,22 +89,60 @@ namespace RacesOfValheim
SetAttacking(false);
}
// The guard: right click blocks, as it does for the human underneath, and the troll
// holds a pose for it. A roll out of the guard drops it, so the roll is not hidden
// behind a frozen troll.
bool guard = !isAttacking && !player.IsDead() && player.IsBlocking() && !player.InDodge();
TrolTrueFormModel.TickDodge();
if (guard) TrolTrueFormModel.EndDodge();
Guard(player, guard);
if (isAttacking || player.IsDead()) return;
bool grounded = locomotion.Mirror(anim, playerAnim, player);
if (guard) return;
if (player.InDodge())
{
if (!dodging) TrolTrueFormModel.PlayDodge(anim);
dodging = true;
return;
}
dodging = false;
if (!grounded || !RaceInput.Allowed) return;
// Left punches, middle slams: the vanilla primary and secondary attack. Right click is
// the block, so the slam no longer goes off every time the troll raises its guard.
bool log = heldLogName != null;
if (RaceInput.AttackDown(0))
{
Play(log ? TrolTrueFormModel.AttackKind.LogSwingH : TrolTrueFormModel.AttackKind.Punch);
}
else if (RaceInput.AttackDown(1))
else if (RaceInput.AttackDown(2))
{
Play(log ? TrolTrueFormModel.AttackKind.LogSwingV : TrolTrueFormModel.AttackKind.Slam);
}
}
/// <summary>Holds the guard pose while blocking and lets go after, and tells every other
/// client which pose to hold.</summary>
private void Guard(Player player, bool on)
{
if (on)
{
guardPose.Hold(anim, TrolTrueFormModel.GuardState, TrolTrueFormModel.GuardTime);
TrolTrueFormModel.PublishGuard(player, true);
guarding = true;
}
else if (guarding)
{
guardPose.Release(anim);
TrolTrueFormModel.PublishGuard(player, false);
guarding = false;
}
}
private void Play(TrolTrueFormModel.AttackKind kind)
{
TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(kind);
@ -406,6 +449,8 @@ namespace RacesOfValheim
private Animator playerAnim;
private ZNetView nview;
private string lastAttack;
private bool guarding;
private readonly TrolGuardPose guardPose = new TrolGuardPose();
private readonly FormLocomotion locomotion = new FormLocomotion();
private GameObject heldLog;
@ -438,6 +483,17 @@ namespace RacesOfValheim
ReplayAttack();
locomotion.Mirror(anim, playerAnim, player);
if (TrolTrueFormModel.ReadGuard(nview.GetZDO(), out string guardState, out float guardTime))
{
guardPose.Hold(anim, guardState, guardTime);
guarding = true;
}
else if (guarding)
{
guardPose.Release(anim);
guarding = false;
}
}
private void ReplayAttack()

View file

@ -79,6 +79,8 @@ namespace RacesOfValheim
public static bool LocalActive => localModel != null;
public static Animator LocalAnimator => localModel != null ? localModel.GetComponentInChildren<Animator>() : null;
/// <summary>True while the local troll is in the middle of a swing, a slam or a throw.
/// Trol_TrueFormHoldStill_Patch holds the player still for exactly that long.</summary>
public static bool LocalAttacking { get; set; }
@ -434,6 +436,105 @@ namespace RacesOfValheim
nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackSeq);
}
// ─── Guard and roll poses ────────────────────────────────────────────
// The troll has no block or roll of its own, so the guard is one frame of another state held
// still. State names are read off troll_animator with scripts/dump_controller.py: Movement,
// attack, jump, punch, throw, swing log V, swing log H, Stagger, Summon, Sleeping, Wakeup,
// In Water. Both are settable live with the trolpose command until the right frame is found.
public const string MovementState = "Movement";
// Picked in game with trolpose: the troll half risen out of its Wakeup, arms up.
public static string GuardState = "Wakeup";
public static float GuardTime = 0.13f;
/// <summary>The state played whole when the player rolls; null plays nothing and the troll
/// slides along with the roll.</summary>
public static string DodgeState = "jump";
/// <summary>How fast the roll state plays: the troll's jump runs longer than a roll, so at 1
/// the troll was still leaping after the roll had ended.</summary>
public static float DodgeSpeed = 2f;
// The local troll's Animator while its roll state plays, null otherwise.
// Trol_TrueFormDodgeSpeed_Patch keeps its speed up through every FixedUpdate.
private static Animator dodgeAnimator;
private static float dodgeStarted;
/// <summary>Set while the owner's troll holds its guard, to "state|time", so every other
/// client's copy holds the same frame. Empty when it is not guarding.</summary>
public const string GuardKey = "RacesOfValheim_TrolTrueFormGuard";
public static bool HasState(Animator anim, string state)
{
return anim != null && !string.IsNullOrEmpty(state) && anim.HasState(0, Animator.StringToHash("Base Layer." + state));
}
public static void PlayDodge(Animator anim)
{
if (!HasState(anim, DodgeState)) return;
anim.speed = DodgeSpeed;
anim.CrossFadeInFixedTime("Base Layer." + DodgeState, 0.1f, 0, 0f);
dodgeAnimator = anim;
dodgeStarted = Time.time;
}
/// <summary>
/// Called every frame: keeps the roll state at DodgeSpeed while it plays, and puts the speed
/// back once the troll has left it. The first moments are skipped, because the cross-fade
/// into the state only starts on the Animator's next update.
/// </summary>
public static void TickDodge()
{
if (dodgeAnimator == null) return;
int hash = Animator.StringToHash("Base Layer." + DodgeState);
bool inState = dodgeAnimator.GetCurrentAnimatorStateInfo(0).fullPathHash == hash ||
(dodgeAnimator.IsInTransition(0) && dodgeAnimator.GetNextAnimatorStateInfo(0).fullPathHash == hash);
if (inState || Time.time - dodgeStarted < 0.15f) dodgeAnimator.speed = DodgeSpeed;
else EndDodge();
}
public static void EndDodge()
{
if (dodgeAnimator != null) dodgeAnimator.speed = 1f;
dodgeAnimator = null;
}
/// <summary>The troll's CharacterAnimEvent sets its Animator back to speed 1 in every
/// FixedUpdate; this sets the roll's speed again right after.</summary>
[HarmonyPatch(typeof(CharacterAnimEvent), nameof(CharacterAnimEvent.CustomFixedUpdate))]
public static class Trol_TrueFormDodgeSpeed_Patch
{
public static void Postfix(CharacterAnimEvent __instance)
{
if (dodgeAnimator != null && __instance.gameObject == dodgeAnimator.gameObject) dodgeAnimator.speed = DodgeSpeed;
}
}
public static void PublishGuard(Player player, bool on)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
string value = on ? GuardState + "|" + GuardTime.ToString(System.Globalization.CultureInfo.InvariantCulture) : "";
if (nview.GetZDO().GetString(GuardKey, "") != value) nview.GetZDO().Set(GuardKey, value);
}
/// <summary>The pose another client's troll should hold, read back off the owner's ZDO.</summary>
public static bool ReadGuard(ZDO zdo, out string state, out float time)
{
state = null;
time = 0f;
string value = zdo.GetString(GuardKey, "");
int bar = value.LastIndexOf('|');
if (bar <= 0) return false;
state = value.Substring(0, bar);
return float.TryParse(value.Substring(bar + 1), System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out time);
}
/// <summary>
/// The damage a troll attack deals for this player right now: the troll's own numbers, times
/// Troll Attack Damage, times the same random Clubs factor a club would get.
@ -465,6 +566,35 @@ namespace RacesOfValheim
crouch = false;
dodge = false;
}
/// <summary>
/// Rooted while guarding, so the held pose cannot slide across the ground. Cleared after
/// SetControls, not before: the block-and-jump roll takes its direction from the move
/// input inside SetControls, and an input zeroed first sent every roll backwards.
/// </summary>
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || !LocalActive || LocalAttacking) return;
if (__instance.IsBlocking() && !__instance.InDodge()) MoveDir(__instance) = Vector3.zero;
}
private static readonly AccessTools.FieldRef<Character, Vector3> MoveDir =
AccessTools.FieldRefAccess<Character, Vector3>("m_moveDir");
}
// Share of a normal roll's distance the troll covers. The roll moves by root motion, and
// under True Form two animators feed it: the hidden human's dodge and the troll's jump.
private const float RollDistance = 0.5f;
/// <summary>A shorter roll for the troll: every bit of root motion that reaches the player
/// during a True Form roll is scaled, whichever of the two clips it came from.</summary>
[HarmonyPatch(typeof(Character), nameof(Character.AddRootMotion))]
public static class Trol_TrueFormRollDistance_Patch
{
public static void Prefix(Character __instance, ref Vector3 vel)
{
if (__instance == Player.m_localPlayer && LocalActive && __instance.InDodge()) vel *= RollDistance;
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
@ -502,4 +632,86 @@ namespace RacesOfValheim
}
}
}
/// <summary>
/// Holds one troll at one frame of a state, for the True Form guard. It blends in the way it
/// blends out: a cross-fade into the frame first, then the frame pinned once the fade is over.
/// Pinned again every frame it holds: the troll's own CharacterAnimEvent puts the Animator back
/// to speed 1 in every FixedUpdate, so a speed of 0 set once would not stay.
/// </summary>
internal class TrolGuardPose
{
private const float Fade = 0.2f;
// Each state's length, learned the first time it is held: the fade starts that far ahead of
// the frame, so the state lands on it when the fade ends instead of running past it.
private static readonly Dictionary<int, float> lengths = new Dictionary<int, float>();
private int state;
private float target;
private float fadeStarted;
private bool fading;
private float pinned;
public void Hold(Animator anim, string name, float time)
{
if (!TrolTrueFormModel.HasState(anim, name)) return;
int hash = Animator.StringToHash("Base Layer." + name);
time = Mathf.Clamp01(time);
if (hash != state || time != target)
{
state = hash;
target = time;
StartFade(anim);
}
if (fading)
{
anim.speed = 1f;
if (Time.time - fadeStarted < Fade || anim.IsInTransition(0)) return;
AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
if (info.fullPathHash == state && info.length > 0f)
{
lengths[state] = info.length;
pinned = info.normalizedTime < 1f ? info.normalizedTime : target;
}
else
{
pinned = target;
}
fading = false;
}
anim.Play(state, 0, pinned);
anim.speed = 0f;
}
private void StartFade(Animator anim)
{
// CrossFade takes its duration as a share of the state being left, so turn the seconds
// into that share.
float from = anim.GetCurrentAnimatorStateInfo(0).length;
float lead = lengths.TryGetValue(state, out float length) && length > 0f ? Fade / length : 0f;
anim.speed = 1f;
anim.CrossFade(state, from > 0f ? Fade / from : Fade, 0, Mathf.Max(0f, target - lead));
fadeStarted = Time.time;
fading = true;
}
public void Release(Animator anim)
{
state = 0;
fading = false;
if (anim == null) return;
anim.speed = 1f;
if (TrolTrueFormModel.HasState(anim, TrolTrueFormModel.MovementState))
{
anim.CrossFadeInFixedTime("Base Layer." + TrolTrueFormModel.MovementState, Fade, 0);
}
}
}
}

View file

@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
---
## New in v1.6.2
## New in v1.6.3
**Eyes and controllers.** The races' eyes now sit right on female faces, the Dvergar and Aswid eyes are smaller, and the Alfar have new grey-alien eyes. On a gamepad the Alfar can now levitate and fire Geisli, and the Draugh eats bear, Asksvin and Bonemaw meat. Full details in the [changelog](#v162).
**The troll learns to guard, and the stations get dressed.** The Trol's True Form blocks with right click and rolls with block + jump; the slam moves to middle click. The Race Menu Ward glows blue on a stone plinth, the Smith's Table is covered in chainmail, the Cook's Table in a red and white checked cloth, and the Contract Bank gets darker wood and a tankard. Full details in the [changelog](#v163).
---
@ -74,7 +74,7 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
- **Kindling:** the one drawback — fire lands 50% harder on a Trol than on anyone else, and no armour or resistance changes that.
- **Immense Strength:** Increased carry weight; armor scales up as you defeat bosses.
- **Rock Throwing:** Hurl huge boulders at enemies.
- **True Form:** From Moder, become a forest troll: punch, slam the ground, and from the Queen swing or throw a log. Using a player model mod? `Trol - True Form` → `Legacy True Form` keeps your own Trol, grown huge, with weapons in hand.
- **True Form:** From Moder, become a forest troll: punch (left click), slam the ground (middle click), block with your arms up (right click) and roll (block + jump), and from the Queen swing or throw a log. Using a player model mod? `Trol - True Form` → `Legacy True Form` keeps your own Trol, grown huge, with weapons in hand.
- **Your Own Colours:** pick your skin and hair colour under `Trol - Appearance`. Other players see them too.
### 7. Draugh
@ -377,7 +377,7 @@ Meat goes in and a standing pack fills up, in three ranks. It is a herd you keep
### Skeleton & Skadi — Bone Servants
Two disarmed skeletons that never fight, summoned at their own table to work every station and marked chest within 20 m of it.
Two disarmed skeletons that never fight, summoned at their own table to work every station and marked chest within 20 m of it. Each table shows its trade: a sheet of chainmail and an anvil for the smith, a checked tablecloth and a meal for the cook.
- **Build (either table):** 1 Skeleton Trophy, 1 Wishbone, 8 Stone, at a Hammer — no crafting station needed. Removed and the cost comes back in full, like every other station. One table of each kind per forty meters — but a smith's circle and a cook's may sit right on top of each other, since neither ever touches the other's stations.
- **Bone Smith (Smith's Table):** works the Forge family — smelters, kilns, anything that turns ore into metal on its own. Open to **Skeleton or Skadi**.
@ -438,7 +438,7 @@ The size is a slider in Configuration Manager under `Trols Hammer`. Turning the
## The Race Menu Ward
- Build (2 Wood, Hammer/Misc, no crafting station). First placed near Sacrificial Stones in every new world.
- Build (2 Wood, Hammer/Misc, no crafting station). First placed near Sacrificial Stones in every new world. It looks like Odin's statue on a stone plinth, lit blue, so you can tell it apart from a vanilla Ward.
Interact to reset your race, reset your progression, or switch between:
- **World progression:** tier follows world’s bosses.
@ -475,6 +475,13 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact
## Changelog
### v1.6.3
- **Change - Trol True Form can block and roll:** right click now blocks in True Form, the way it does with a shield, and the troll raises its arms into a guard while you do. You stand rooted while guarding, so you can turn but not walk. Block + jump still rolls, half as far as a normal roll, and the troll leaps with its own jump animation, played at double speed so it ends with the roll, instead of sliding. The ground slam moved to middle click (the secondary attack on a gamepad), next to the punch on left click; with a log in hand the vertical swing moved with it. Other players see the guard too.
- **Change - New looks for the Race Menu Ward and three stations:** the Race Menu Ward glows blue instead of orange, and its statue is colder, slimmer and stands on a stone plinth, so it no longer looks like a vanilla Ward. The Dvergar Contract Bank has darker wood and a dvergr tankard beside the coin. The Bone Servants' tables keep their shape, but the map is gone: a sheet of shining chainmail covers the Smith's Table, with an anvil and a skeleton skull on it, and a red and white checked tablecloth covers the Cook's Table, with a meal and a skull. A damaged table shows rusted mail or a stained cloth.
- **Fix - Smith's and Cook's Table names:** the table's hover showed `$rov_piece_smithtable_name` or `$rov_piece_cooktable_name` instead of its name once a servant stood there.
Thanks to lexsonn for the True Form block idea, and to sistermilker for reporting the female characters' misplaced eyes (fixed in v1.6.2).
### v1.6.2
- **Fix - eyes on female faces:** the glowing eyes of the Dvergar, Aswid and Sverm, and the Alfar's black eyes, now sit on the female face. They used to land on the brow and seemed not to follow the head.
- **Changed - Dvergar eyes:** smaller.

View file

@ -1,7 +1,7 @@
{
"name": "RacesOfValheim",
"description": "A Valheim mod that adds eleven custom playable races (Alfar, Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.",
"version_number": "1.6.2",
"version_number": "1.6.3",
"website_url": "",
"dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333",

39
scripts/extract_carto.py Normal file
View file

@ -0,0 +1,39 @@
"""Export the cartography table's textures (PNG) and its high mesh (OBJ) from Valheim's bundle.
Usage: py -3.14 -I extract_carto.py <pylib> <bundle file> <out dir>"""
import os, sys
sys.path.insert(0, sys.argv[1])
import UnityPy
bundle, out = sys.argv[2], sys.argv[3]
os.makedirs(out, exist_ok=True)
env = UnityPy.load(bundle)
want_tex = {"Cartographer_d", "Cartographer_worn_d", "Cartographer_n", "Cartographer_m"}
for obj in env.objects:
if obj.type.name == "Texture2D":
t = obj.read()
if t.m_Name in want_tex:
img = t.image
img.save(os.path.join(out, t.m_Name + ".png"))
print("tex", t.m_Name, img.size, t.m_TextureFormat)
for path, ptr in env.container.items():
if path.endswith("/piece_cartographytable.prefab"):
go = ptr.read()
def walk(tr, prefix):
g = tr.m_GameObject.read()
name = prefix + "/" + g.m_Name
for c in g.m_Component:
o = (c.component if hasattr(c, 'component') else c[1]).read()
if o.object_reader.type.name == "MeshFilter":
m = o.m_Mesh.read()
fn = name.strip("/").replace("/", "__") + ".obj"
open(os.path.join(out, fn), "w").write(m.export())
print("mesh", name, m.m_Name, "->", fn)
for ch in tr.m_Children:
walk(ch.read(), name)
for c in go.m_Component:
o = (c.component if hasattr(c, 'component') else c[1]).read()
if o.object_reader.type.name == "Transform":
walk(o, "")
break

View file

@ -0,0 +1,55 @@
"""Paint a red and white gingham tablecloth over the cartography table's map.
Usage: py -3.14 -I paint_cloth.py <pylib> <carto dir> <out dir>"""
import os, sys
sys.path.insert(0, sys.argv[1])
from PIL import Image, ImageFilter
src, out = sys.argv[2], sys.argv[3]
os.makedirs(out, exist_ok=True)
# The parchment's UV island spans x 10-133, y 11-90 (read off the mesh). A margin either side,
# stopping short of the next island (the red disc starts at y 96, the stone at x 150).
X0, Y0, X1, Y1 = 4, 4, 141, 95
SQUARE = 6 # pixels; the island is ~45 px per metre, so about 13 cm squares
WHITE = (236, 231, 219)
MID = (204, 92, 86)
DARK = (158, 28, 32)
def gingham(x, y):
a = ((x - X0) // SQUARE) % 2 == 0
b = ((y - Y0) // SQUARE) % 2 == 0
return DARK if a and b else MID if a or b else WHITE
def paint(name, fade=0.0, dirt=1.0):
img = Image.open(os.path.join(src, name + ".png")).convert("RGBA")
# Keep the parchment's broad light and shadow (the folds, the dark rolled edges) but not
# its ink: a heavy blur of its brightness, around 1.0.
lum = img.convert("L").filter(ImageFilter.GaussianBlur(5))
region = [lum.getpixel((x, y)) for y in range(Y0, Y1) for x in range(X0, X1)]
mean = sum(region) / len(region)
px = img.load()
for y in range(Y0, Y1):
for x in range(X0, X1):
shade = max(0.7, min(1.15, lum.getpixel((x, y)) / mean)) * dirt
r, g, b = gingham(x, y)
o = px[x, y]
c = [int(min(255, v * shade)) for v in (r, g, b)]
c = [int(cv * (1 - fade) + ov * fade) for cv, ov in zip(c, o[:3])]
px[x, y] = (c[0], c[1], c[2], o[3])
img.save(os.path.join(out, name.replace("Cartographer", "CookCloth") + ".png"))
def smooth_normal(name):
img = Image.open(os.path.join(src, name + ".png")).convert("RGBA")
box = (X0, Y0, X1, Y1)
img.paste(img.crop(box).filter(ImageFilter.GaussianBlur(4)), box)
img.save(os.path.join(out, name.replace("Cartographer", "CookCloth") + ".png"))
paint("Cartographer_d")
paint("Cartographer_worn_d", fade=0.3, dirt=0.85) # the damaged table: a stained, faded cloth
smooth_normal("Cartographer_n")
print("done")

118
scripts/paint_smith_mail.py Normal file
View file

@ -0,0 +1,118 @@
"""Paint a sheet of chainmail over the cartography table's map: colour, worn (rusted) colour,
normal map and metallic map, at twice the vanilla resolution so the rings keep their shape.
Usage: py -3.14 -I paint_mail.py <pylib> <carto dir> <out dir>"""
import os, sys
sys.path.insert(0, sys.argv[1])
import numpy as np
from PIL import Image, ImageFilter
src, out = sys.argv[2], sys.argv[3]
os.makedirs(out, exist_ok=True)
SCALE = 2
# The parchment's UV island (x 10-133, y 11-90 at 256 px) plus a margin, as in paint_cook_cloth.py.
X0, Y0, X1, Y1 = 4 * SCALE, 4 * SCALE, 141 * SCALE, 95 * SCALE
W, H = X1 - X0, Y1 - Y0
RING = 7.0 # ring radius to the middle of the wire, px at 512 (about 15 cm across in game)
WIRE = 1.5 # half the wire's thickness
SX, SY = RING * 2.3, RING * 1.3 # 4-in-1: each row offset by half, linking the rows above and below
rng = np.random.default_rng(7)
# ---------------------------------------------------------------- the rings, as a height field
ys, xs = np.mgrid[0:H, 0:W].astype(np.float32)
height = np.zeros((H, W), np.float32)
tone = np.ones((H, W), np.float32)
rows = int(H / SY) + 3
cols = int(W / SX) + 3
for row in range(-1, rows):
tilt = 0.45 if row % 2 else -0.45 # alternate rows lean opposite ways, like real mail
lift = 0.25 if row % 2 else 0.0 # and one set lies over the other
for col in range(-1, cols):
cx = col * SX + (SX / 2 if row % 2 else 0)
cy = row * SY
x0, x1 = int(max(0, cx - RING - WIRE - 2)), int(min(W, cx + RING + WIRE + 3))
y0, y1 = int(max(0, cy - RING - WIRE - 2)), int(min(H, cy + RING + WIRE + 3))
if x0 >= x1 or y0 >= y1:
continue
dx = xs[y0:y1, x0:x1] - cx
dy = ys[y0:y1, x0:x1] - cy
# a tilted ring seen from above is an ellipse, squashed along its lean
u = dx * np.cos(tilt) + dy * np.sin(tilt)
v = (-dx * np.sin(tilt) + dy * np.cos(tilt)) / 0.78
t = (np.sqrt(u * u + v * v) - RING) / WIRE
h = np.where(np.abs(t) < 1, np.sqrt(np.clip(1 - t * t, 0, 1)) * 0.75 + lift, 0)
win = h > height[y0:y1, x0:x1]
height[y0:y1, x0:x1] = np.where(win, h, height[y0:y1, x0:x1])
tone[y0:y1, x0:x1] = np.where(win, 0.92 + rng.random() * 0.16, tone[y0:y1, x0:x1])
ring = height > 0
# ---------------------------------------------------------------- lighting from the height field
gx = np.zeros_like(height); gy = np.zeros_like(height)
gx[:, 1:-1] = height[:, 2:] - height[:, :-2]
gy[1:-1, :] = height[2:, :] - height[:-2, :]
K = 1.6
n = np.stack([-gx * K, gy * K, np.ones_like(height)], -1) # image y runs down, texture v up
n /= np.linalg.norm(n, axis=-1, keepdims=True)
light = np.array([-0.45, 0.55, 0.70]); light /= np.linalg.norm(light)
diffuse = np.clip((n * light).sum(-1), 0, 1)
half = light + np.array([0, 0, 1.0]); half /= np.linalg.norm(half)
spec = np.clip((n * half).sum(-1), 0, 1) ** 24
def broad_shade(img):
"""The parchment's folds and rolled edges, without its ink: a heavy blur of its brightness."""
lum = np.asarray(img.convert("L").filter(ImageFilter.GaussianBlur(5 * SCALE)), np.float32)[Y0:Y1, X0:X1]
return np.clip(lum / lum.mean(), 0.7, 1.15)
def upscale(name):
img = Image.open(os.path.join(src, name + ".png")).convert("RGBA")
return img.resize((img.width * SCALE, img.height * SCALE), Image.BICUBIC)
def colour(name, rust):
img = upscale(name)
a = np.asarray(img, np.float32).copy()
shade = broad_shade(img)
steel = np.array([150, 156, 164], np.float32)
# Through the holes, the table's own planks in the mail's shadow: tiled from the wood island.
wood = a[130 * SCALE:240 * SCALE, 60 * SCALE:240 * SCALE, :3]
reps = (H // wood.shape[0] + 1, W // wood.shape[1] + 1, 1)
gap = np.tile(wood, reps)[:H, :W] * 0.5
lit = steel * (0.30 + 0.75 * diffuse[..., None]) * tone[..., None] + 120 * spec[..., None]
if rust:
blotch = np.asarray(Image.fromarray((rng.random((H // 6 + 1, W // 6 + 1)) * 255).astype(np.uint8))
.resize((W, H), Image.BICUBIC).filter(ImageFilter.GaussianBlur(3)), np.float32) / 255
amount = np.clip((blotch - 0.35) * 2.2, 0, 0.85)[..., None]
rusty = np.array([118, 62, 32], np.float32) * (0.45 + 0.6 * diffuse[..., None])
lit = lit * (1 - amount) + rusty * amount
lit *= 0.85
rgb = np.where(ring[..., None], lit, gap) * shade[..., None]
a[Y0:Y1, X0:X1, :3] = np.clip(rgb, 0, 255)
return Image.fromarray(a.astype(np.uint8), "RGBA")
def normal():
a = np.asarray(upscale("Cartographer_n"), np.float32).copy()
# DXT5nm, as Valheim packs it: X in alpha, Y in green (blue repeats it), red pinned to 255.
a[Y0:Y1, X0:X1, 0] = 255
a[Y0:Y1, X0:X1, 1] = (n[..., 1] * 0.5 + 0.5) * 255
a[Y0:Y1, X0:X1, 2] = (n[..., 1] * 0.5 + 0.5) * 255
a[Y0:Y1, X0:X1, 3] = (n[..., 0] * 0.5 + 0.5) * 255
return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8), "RGBA")
def metallic():
a = np.asarray(upscale("Cartographer_m"), np.float32).copy()
a[Y0:Y1, X0:X1, 0] = np.where(ring, 210, 0) # red is metallic; the rest of the table stays 0
return Image.fromarray(a.astype(np.uint8), "RGBA")
colour("Cartographer_d", rust=False).save(os.path.join(out, "SmithMail_d.png"))
colour("Cartographer_worn_d", rust=True).save(os.path.join(out, "SmithMail_worn_d.png"))
normal().save(os.path.join(out, "SmithMail_n.png"))
metallic().save(os.path.join(out, "SmithMail_m.png"))
print("done")