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.
This commit is contained in:
kanym 2026-10-28 13:38:28 +01:00
commit 069e098cf0
8 changed files with 238 additions and 22 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

View file

@ -62,6 +62,8 @@ namespace RacesOfValheim
public const float TableSpacing = 40f; public const float TableSpacing = 40f;
private const string TableSource = "piece_blackmarble_table"; private const string TableSource = "piece_blackmarble_table";
private const string ClothTableSource = "piece_cartographytable";
private const float ClothTableScale = 0.8f;
/// <summary> /// <summary>
/// One skull, one wishbone, eight stone - the same price for both tables. /// One skull, one wishbone, eight stone - the same price for both tables.
@ -197,20 +199,22 @@ namespace RacesOfValheim
private static void RegisterTable(string pieceName, string displayName, string servantPrefab, private static void RegisterTable(string pieceName, string displayName, string servantPrefab,
ButlerFamily family, string description, string iconSource) ButlerFamily family, string description, string iconSource)
{ {
// The black marble table: "a slab of bone and slate". It was the cartography table once, // The smith works at the black marble table, "a slab of bone and slate". The cook keeps the
// whose map is baked into its own texture and could not be taken off. // cartography table, with a tablecloth painted over its map (Dress).
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, TableSource); bool kitchen = family == ButlerFamily.Kitchen;
string source = kitchen ? ClothTableSource : TableSource;
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source);
if (prefab == null) if (prefab == null)
{ {
Jotunn.Logger.LogWarning($"[Butler] Could not clone {TableSource}; " + Jotunn.Logger.LogWarning($"[Butler] Could not clone {source}; " +
$"the {displayName} is not registered."); $"the {displayName} is not registered.");
return; return;
} }
// A blanket sweep by capability rather than a named DestroyImmediate. The cartography table // The MapTable trap, and it is the reason this is a blanket sweep by capability rather than
// taught it: its MapTable is Interactable AND Hoverable, so it took the E key before our own // a named DestroyImmediate: MapTable is Interactable AND Hoverable, so it takes the E key
// Switch ever saw it. The marble table carries nothing of the kind today, and the sweep // before our own Switch ever sees it and opens the shared map instead. The marble table
// keeps a future patch from adding one behind our back. // carries nothing of the kind today, and the sweep keeps a future patch from adding one.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true)) foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{ {
if (behaviour == null) continue; if (behaviour == null) continue;
@ -218,6 +222,7 @@ namespace RacesOfValheim
Object.DestroyImmediate(behaviour); Object.DestroyImmediate(behaviour);
} }
if (kitchen) prefab.transform.localScale = Vector3.one * ClothTableScale;
Dress(prefab, family); Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>(); ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
@ -256,8 +261,8 @@ namespace RacesOfValheim
})); }));
} }
// The look. The marble table is 2.6 m by 1.5 m; both props sit either side of its centre, the // The smith's look. The marble table is 2.6 m by 1.5 m; both props sit either side of its
// trade's tool the bigger of the two. X and Z only: the height is the table's, measured. // centre, the anvil the bigger of the two. X and Z only: the height is the table's, measured.
private const float MarbleTableTop = 0.82f; private const float MarbleTableTop = 0.82f;
private static readonly Vector3 TradeSpot = new Vector3(-0.35f, 0f, 0f); private static readonly Vector3 TradeSpot = new Vector3(-0.35f, 0f, 0f);
private static readonly Vector3 SkullSpot = new Vector3(0.6f, 0f, 0.1f); private static readonly Vector3 SkullSpot = new Vector3(0.6f, 0f, 0.1f);
@ -265,12 +270,32 @@ namespace RacesOfValheim
private const float MealSize = 0.6f; private const float MealSize = 0.6f;
private const float SkullSize = 0.45f; private const float SkullSize = 0.45f;
// The cook's cartography table, in its own space BEFORE ClothTableScale (so sizes are divided by
// it to come out the same as the smith's). The cloth covers what was the map: 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 cloth.
private const float ClothTop = 1.05f;
private static readonly Vector3 MealOnCloth = new Vector3(-0.75f, ClothTop, 0.2f);
private static readonly Vector3 SkullOnCloth = new Vector3(-1.55f, ClothTop, 0.35f);
/// <summary> /// <summary>
/// "A slab of bone and slate": the black marble table, with the trade's own work in the middle - /// The trade's own work in the middle - an anvil for the smith, a meal for the cook - and a
/// an anvil for the smith, a meal for the cook - and a skeleton's skull beside it. /// skeleton's skull beside it. The smith's on the black marble, the cook's on a red and white
/// cloth painted over the cartography table's map.
/// </summary> /// </summary>
private static void Dress(GameObject prefab, ButlerFamily family) private static void Dress(GameObject prefab, ButlerFamily family)
{ {
if (family == ButlerFamily.Kitchen)
{
LayCloth(prefab);
float size = 1f / ClothTableScale;
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
MealOnCloth, Quaternion.identity, MealSize * size, "Butler", activeOnly: true);
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullOnCloth, Quaternion.Euler(0f, -150f, 0f), SkullSize * size, "Butler", activeOnly: true);
return;
}
// The table's own height off its own mesh, with vanilla's 0.82 m as the fallback. The mesh // The table's own height off its own mesh, with vanilla's 0.82 m as the fallback. The mesh
// stands on the piece's origin, so its height IS the height of the top. // stands on the piece's origin, so its height IS the height of the top.
Transform model = prefab.transform.Find("new"); Transform model = prefab.transform.Find("new");
@ -278,19 +303,32 @@ namespace RacesOfValheim
if (top <= 0f) top = MarbleTableTop; if (top <= 0f) top = MarbleTableTop;
Vector3 up = Vector3.up * top; Vector3 up = Vector3.up * top;
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot + up, Quaternion.Euler(0f, -150f, 0f), SkullSize, "Butler", activeOnly: true);
if (family == ButlerFamily.Forge)
{
ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2", ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
TradeSpot + up, Quaternion.identity, AnvilSize, "Butler", activeOnly: true); TradeSpot + up, Quaternion.identity, AnvilSize, "Butler", activeOnly: true);
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot + up, Quaternion.Euler(0f, -150f, 0f), SkullSize, "Butler", activeOnly: true);
} }
else
/// <summary>
/// The tablecloth: the cartography table's own textures with the map painted over in red and
/// white squares, by scripts/paint_cook_cloth.py. The worn texture (a damaged table) has a
/// faded, stained cloth of its own, and the normal map is smoothed there so the coastline's
/// relief does not show through.
/// </summary>
private static void LayCloth(GameObject prefab)
{ {
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter", var cloth = new System.Collections.Generic.Dictionary<string, Texture>();
TradeSpot + up, Quaternion.identity, MealSize, "Butler", activeOnly: true); AddCloth(cloth, "Cartographer_d", "CookCloth_d.png", false);
AddCloth(cloth, "Cartographer_worn_d", "CookCloth_worn_d.png", false);
AddCloth(cloth, "Cartographer_n", "CookCloth_n.png", true);
PieceLook.Retexture(prefab.transform, cloth);
} }
private static void AddCloth(System.Collections.Generic.Dictionary<string, Texture> cloth,
string vanilla, string resource, bool linear)
{
Texture2D texture = PieceLook.LoadTexture(resource, linear);
if (texture != null) cloth[vanilla] = texture;
} }
public static void EnsureKnown(Player player) public static void EnsureKnown(Player player)

View file

@ -94,6 +94,84 @@ namespace RacesOfValheim
} }
} }
/// <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) private static void Recolour(Material material, string property, Color glow)
{ {
if (!material.HasProperty(property)) return; if (!material.HasProperty(property)) return;

View file

@ -53,6 +53,12 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </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> <ItemGroup>
<None Include="app.config" /> <None Include="app.config" />
<None Include="packages.config" /> <None Include="packages.config" />

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")