RacesOfValheim/JotunnModStub/PieceLook.cs
kanym 069e098cf0 feat: red and white tablecloth on the Cook's Table
The cook goes back to the cartography table with its map painted over
offline (scripts/paint_cook_cloth.py from textures pulled by
scripts/extract_carto.py). The three PNGs are embedded in the DLL and
swapped onto copied materials by PieceLook.Retexture. The smith stays on
the black marble table.
2026-10-28 13:38:28 +01:00

197 lines
8.6 KiB
C#

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;
}
}
}