diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs index 76bce42..9efa86a 100644 --- a/JotunnModStub/Alfar/AlfarChests.cs +++ b/JotunnModStub/Alfar/AlfarChests.cs @@ -138,7 +138,7 @@ namespace RacesOfValheim AlfarPieces.Extra.Add(pieceName); } - private static Sprite IconFrom(string resource) + internal static Sprite IconFrom(string resource) { Texture2D texture = PieceLook.LoadTexture(resource); if (texture == null) return null; diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs index 8ba5ac9..26024f5 100644 --- a/JotunnModStub/Alfar/AlfarNexus.cs +++ b/JotunnModStub/Alfar/AlfarNexus.cs @@ -46,7 +46,9 @@ namespace RacesOfValheim Object.DestroyImmediate(behaviour); } - AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); + // The floating pyramid; the blue table stays as the fallback if it cannot be built. + bool pyramid = AlfarNexusLook.Build(prefab); + if (!pyramid) AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); AlfarNexusBehaviour nexus = prefab.AddComponent(); nexus.m_switch = prefab.AddComponent(); @@ -71,7 +73,7 @@ namespace RacesOfValheim trader.m_randomUseItemAlreadyRecieved = new List(); trader.m_randomTalkConditionals = new List(); - Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); + Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); piece.m_craftingStation = null; diff --git a/JotunnModStub/Alfar/AlfarNexusLook.cs b/JotunnModStub/Alfar/AlfarNexusLook.cs new file mode 100644 index 0000000..a21928a --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusLook.cs @@ -0,0 +1,260 @@ +using System.Collections.Generic; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Ljoskjarne's body: a stone pyramid, 2 m to a side and 2 m tall, floating 0.5 m above the + /// ground. Dark steel carved with Valheim's own runes (the Ashlands rune tile's glyphs, laid out by + /// scripts/paint_nexus.py), and a cyan seam down the middle of each face. + /// + /// Only the look moves. The piece keeps one still collider from the ground up, so building on it, + /// support, hovering and the E key behave as before; the pyramid bobs and turns on each client by + /// itself, nothing over the network. The seam breathes, and burns brighter while crystals wait. + /// + public static class AlfarNexusLook + { + private const float Height = 2f; + private const float HalfBase = 1f; + private const float Lift = 0.5f; + private const float SeamWidth = 0.04f; // half the rib's width at the base + private const float SeamHeight = 0.025f; + private const string SourceMaterialPrefab = "piece_cartographytable"; + private const string EmbersSource = "fx_Torch_Carried"; + + private static readonly Color Seam = new Color(0.35f, 0.75f, 1f); + + /// Strips the cartography table's body and puts the pyramid in its place. False leaves + /// the table, with a warning, so the Nexus is never invisible. + public static bool Build(GameObject prefab) + { + Texture2D face = PieceLook.LoadTexture("AlfarNexus_face.png"); + Renderer tableRenderer = prefab.transform.Find("new/high")?.GetComponent(); + if (face == null || tableRenderer == null || tableRenderer.sharedMaterial == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not build the Ljoskjarne's pyramid; it keeps the cartography table's look."); + return false; + } + + Material stone = new Material(tableRenderer.sharedMaterial) { name = "AlfarNexus_stone" }; + stone.color = Color.white; + stone.SetTexture("_MainTex", face); + foreach (string slot in new[] { "_BumpMap", "_MetallicGlossMap" }) + if (stone.HasProperty(slot)) stone.SetTexture(slot, null); + if (stone.HasProperty("_Metallic")) stone.SetFloat("_Metallic", 0.75f); + if (stone.HasProperty("_Glossiness")) stone.SetFloat("_Glossiness", 0.55f); + + Material seam = new Material(stone) { name = "AlfarNexus_seam" }; + seam.SetTexture("_MainTex", null); + seam.color = Color.black; + seam.EnableKeyword("_EMISSION"); + seam.SetColor("_EmissionColor", Seam); + + // The table goes whole: its meshes, its damage states, its fragments and its four colliders. + for (int i = prefab.transform.childCount - 1; i >= 0; i--) + Object.DestroyImmediate(prefab.transform.GetChild(i).gameObject); + WearNTear wear = prefab.GetComponent(); + if (wear != null) + { + wear.m_new = null; + wear.m_worn = null; + wear.m_broken = null; + wear.m_fragmentRoots = new GameObject[0]; + } + + // One still collider, from the ground to the tip, a little inside the faces. + GameObject solid = new GameObject("collider") { layer = prefab.layer }; + solid.transform.SetParent(prefab.transform, false); + BoxCollider box = solid.AddComponent(); + box.center = new Vector3(0f, (Lift + Height) / 2f, 0f); + box.size = new Vector3(HalfBase * 1.4f, Lift + Height, HalfBase * 1.4f); + + Transform floating = new GameObject("float").transform; + floating.SetParent(prefab.transform, false); + floating.gameObject.layer = prefab.layer; + + MeshRenderer seamRenderer = Part(floating, "seam", SeamMesh(), seam).GetComponent(); + Part(floating, "pyramid", PyramidMesh(), stone); + + NexusLook look = prefab.AddComponent(); + look.Float = floating; + look.SeamRenderer = seamRenderer; + look.Motes = AddMotes(prefab.transform); + return true; + } + + private static GameObject Part(Transform parent, string name, Mesh mesh, Material material) + { + GameObject part = new GameObject(name) { layer = parent.gameObject.layer }; + part.transform.SetParent(parent, false); + part.AddComponent().sharedMesh = mesh; + part.AddComponent().sharedMaterial = material; + return part; + } + + private static Vector3 Apex => new Vector3(0f, Lift + Height, 0f); + + private static Vector3[] BaseCorners => new[] + { + new Vector3(-HalfBase, Lift, -HalfBase), new Vector3(HalfBase, Lift, -HalfBase), + new Vector3(HalfBase, Lift, HalfBase), new Vector3(-HalfBase, Lift, HalfBase), + }; + + /// Four faces, each with its own three corners so the shading stays flat and every face + /// shows the whole carving (u along the base, v = 1 at the tip), and the underside. + private static Mesh PyramidMesh() + { + Vector3[] c = BaseCorners; + var vertices = new Vector3[16]; + var uvs = new Vector2[16]; + var triangles = new int[18]; + for (int i = 0; i < 4; i++) + { + // Wound clockwise seen from outside, which is Unity's front face. + vertices[i * 3] = c[(i + 1) % 4]; + vertices[i * 3 + 1] = c[i]; + vertices[i * 3 + 2] = Apex; + uvs[i * 3] = new Vector2(1f, 0f); + uvs[i * 3 + 1] = new Vector2(0f, 0f); + uvs[i * 3 + 2] = new Vector2(0.5f, 1f); + triangles[i * 3] = i * 3; + triangles[i * 3 + 1] = i * 3 + 1; + triangles[i * 3 + 2] = i * 3 + 2; + } + for (int i = 0; i < 4; i++) { vertices[12 + i] = c[i]; uvs[12 + i] = new Vector2(0.5f, 0.02f); } + int[] under = { 12, 13, 14, 12, 14, 15 }; + System.Array.Copy(under, 0, triangles, 12, 6); + + Mesh mesh = new Mesh { name = "AlfarNexus_pyramid", vertices = vertices, uv = uvs, triangles = triangles }; + mesh.RecalculateNormals(); + mesh.RecalculateBounds(); + return mesh; + } + + /// + /// The seams: a raised rib down the middle of each face, from the middle of its base edge to + /// the tip, standing on the stone with its own sides. A flat strip a centimetre off the face + /// lost the depth test to the stone at a glancing angle, and the cyan came and went in patches + /// as the pyramid turned; a rib has no surface lying that close to the face. + /// + private static Mesh SeamMesh() + { + Vector3[] c = BaseCorners; + var vertices = new List(); + var triangles = new List(); + Vector3 centre = new Vector3(0f, Lift + Height / 3f, 0f); + for (int i = 0; i < 4; i++) + { + Vector3 a = c[i], b = c[(i + 1) % 4]; + Vector3 middle = (a + b) / 2f; + Vector3 along = (b - a).normalized; + Vector3 normal = Vector3.Cross(b - a, Apex - a).normalized; + if (Vector3.Dot(normal, middle - centre) < 0f) normal = -normal; + + Vector3 top = normal * SeamHeight, foot = normal * 0.002f; + Vector3 baseLeft = middle - along * SeamWidth, baseRight = middle + along * SeamWidth; + Vector3 tipLeft = Apex - along * 0.004f, tipRight = Apex + along * 0.004f; + + Quad(vertices, triangles, baseLeft + top, baseRight + top, tipRight + top, tipLeft + top, normal); + Quad(vertices, triangles, baseLeft + foot, baseLeft + top, tipLeft + top, tipLeft + foot, -along); + Quad(vertices, triangles, baseRight + foot, baseRight + top, tipRight + top, tipRight + foot, along); + Quad(vertices, triangles, baseLeft + foot, baseRight + foot, baseRight + top, baseLeft + top, middle - Apex); + } + + Mesh mesh = new Mesh { name = "AlfarNexus_seam", vertices = vertices.ToArray(), triangles = triangles.ToArray() }; + mesh.RecalculateNormals(); + mesh.RecalculateBounds(); + return mesh; + } + + /// + /// One quad with its own corners, turned so its front faces : Unity's + /// front face is the side Cross(v1 - v0, v2 - v0) points to. + /// + private static void Quad(List vertices, List triangles, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 outward) + { + int first = vertices.Count; + vertices.Add(p0); vertices.Add(p1); vertices.Add(p2); vertices.Add(p3); + + bool flip = Vector3.Dot(Vector3.Cross(p1 - p0, p2 - p0), outward) < 0f; + int[] quad = flip ? new[] { 0, 2, 1, 0, 3, 2 } : new[] { 0, 1, 2, 0, 2, 3 }; + foreach (int k in quad) triangles.Add(first + k); + } + + /// A few cyan motes drifting up from the ground under it: the torch's embers, recoloured, + /// spread over the pyramid's shadow and slowed down. + private static ParticleSystem AddMotes(Transform root) + { + GameObject torch = PrefabManager.Cache.GetPrefab(EmbersSource); + Transform source = torch != null ? torch.transform.Find("Embers") : null; + if (source == null) return null; + + GameObject motes = Object.Instantiate(source.gameObject, root, false); + motes.name = "motes"; + motes.transform.localPosition = new Vector3(0f, 0.05f, 0f); + motes.transform.localRotation = Quaternion.identity; + PieceLook.Rehue(motes.transform, Seam * 2f); + + ParticleSystem particles = motes.GetComponent(); + if (particles != null) + { + ParticleSystem.ShapeModule shape = particles.shape; + shape.enabled = true; + shape.shapeType = ParticleSystemShapeType.Circle; + shape.radius = HalfBase; + shape.rotation = new Vector3(-90f, 0f, 0f); + ParticleSystem.MainModule main = particles.main; + main.simulationSpeed = 0.5f; + } + return particles; + } + + /// The motion and the seam's light, per client. + public class NexusLook : MonoBehaviour + { + public Transform Float; + public Renderer SeamRenderer; + public ParticleSystem Motes; + + private const float BobHeight = 0.08f; + private const float BobSeconds = 4.5f; + private const float TurnSeconds = 40f; + private const float BreathSeconds = 3.5f; + + private AlfarNexusBehaviour m_nexus; + private Material m_seam; + private float m_phase; + private float m_ready; // eases between 0 (no crystals) and 1, so the brightening is not a jump + + private void Awake() + { + m_nexus = GetComponent(); + if (SeamRenderer != null) m_seam = SeamRenderer.material; // this one's own copy, to animate + // Two Nexuses side by side must not bob in step. + m_phase = (Mathf.Abs(transform.position.x * 0.37f + transform.position.z * 0.71f)) % 10f; + } + + private void Update() + { + float t = Time.time + m_phase; + if (Float != null) + { + Float.localPosition = new Vector3(0f, Mathf.Sin(t * 2f * Mathf.PI / BobSeconds) * BobHeight, 0f); + Float.localRotation = Quaternion.Euler(0f, t * 360f / TurnSeconds, 0f); + } + + if (m_seam == null) return; + bool ready = m_nexus != null && m_nexus.Crystals > 0; + m_ready = Mathf.MoveTowards(m_ready, ready ? 1f : 0f, Time.deltaTime * 0.5f); + float breath = 0.75f + 0.25f * Mathf.Sin(t * 2f * Mathf.PI / BreathSeconds); + m_seam.SetColor("_EmissionColor", Seam * breath * Mathf.Lerp(1f, 2.2f, m_ready)); + } + + private void OnDestroy() + { + if (m_seam != null) Destroy(m_seam); + } + } + } +} diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png new file mode 100644 index 0000000..ca3a0a3 Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png differ diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png new file mode 100644 index 0000000..6b87faa Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png differ diff --git a/scripts/paint_nexus.py b/scripts/paint_nexus.py new file mode 100644 index 0000000..abe0c53 --- /dev/null +++ b/scripts/paint_nexus.py @@ -0,0 +1,100 @@ +"""Paint the Ljoskjarne's pyramid face (Alfar Nexus) and render a preview. +Usage: py -3.14 -I paint_nexus.py + must hold runes/RuneTile_d.png (the stone) and runes/RuneTile_e.png (Valheim's glyphs, +the Ashlands rune tile's glow mask), both from bundle c4210710. Writes AlfarNexus_face.png (one +face, u 0..1 along the base, v 1 at the apex), AlfarNexus_icon.png and prev_nexus.png; copy the face and icon to +JotunnModStub/Assets/AlfarNexus/. The cyan seam down the middle is geometry, not paint.""" +import sys, os, math +sys.path.insert(0, sys.argv[1]); sys.path.insert(0, sys.argv[2]) +import numpy as np +from PIL import Image, ImageFilter, ImageChops +from render_obj import render +d = sys.argv[3] +S = 512 + +# --- the glyphs: every blob of the rune tile's glow mask, cut out with its bounding box +mask = np.asarray(Image.open(os.path.join(d,"runes","RuneTile_e.png")).convert("L"), dtype=np.float32)/255 +grown = np.asarray(Image.fromarray((mask>0.15).astype(np.uint8)*255).filter(ImageFilter.MaxFilter(15)))>0 +seen = np.zeros_like(grown); blobs = [] +H, W = grown.shape +for y in range(H): + for x in range(W): + if grown[y,x] and not seen[y,x]: + stack=[(y,x)]; seen[y,x]=True; ys=[];xs=[] + while stack: + cy,cx=stack.pop(); ys.append(cy); xs.append(cx) + for ny,nx in ((cy+1,cx),(cy-1,cx),(cy,cx+1),(cy,cx-1)): + if 0<=ny 150: blobs.append((x0,y0,x1+1,y1+1)) +tall = [b for b in blobs if (b[3]-b[1]) > 2.5*(b[2]-b[0])] +wide = [b for b in blobs if b not in tall and (b[2]-b[0]) < 200] +glyph = lambda b: Image.fromarray((mask[b[1]:b[3], b[0]:b[2]]*255).astype(np.uint8)) +print("glyphs: tall", len(tall), "short", len(wide)) + +# --- the plate: the rune tile's own stone, greyed toward steel +stone = Image.open(os.path.join(d,"runes","RuneTile_d.png")).convert("RGB").resize((S,S), Image.BICUBIC) +stone = np.asarray(stone, dtype=np.float32)/255 +grey = stone.mean(axis=2, keepdims=True) +stone = (grey*0.8 + stone*0.2)*0.7 + np.array([0.02,0.03,0.05]) + +# --- lay the glyphs out inside the face's triangle (in image space the apex is at the top middle) +ink = Image.new("L", (S,S), 0) +inside = lambda x, y: abs(x - S/2) < (y/S)*S/2 - 14 # y measured from the apex +GAP = 26 # half-width kept clear for the seam +# the tall columns flank the seam +for i, b in enumerate(tall[:3]): + g = glyph(b); h = int(S*0.28); w = max(1, int(g.width*h/g.height)) + g = g.resize((w,h), Image.LANCZOS) + for side in (-1, 1): + x = int(S/2 + side*(GAP + 8 + i*(w+10)) - (w if side < 0 else 0)); y = int(S*0.34) + if inside(x, y) and inside(x+w, y): ink.paste(g, (x,y), g) +# short clusters in rows toward the base +k = 0 +for row, y in enumerate(range(int(S*0.66), S-40, 48)): + half = (y/S)*S/2 - 22 + x = S/2 - half + while x < S/2 + half: + g = glyph(wide[k % len(wide)]); k += 1 + h = 34; w = max(1, int(g.width*h/g.height)); w = min(w, 80) + g = g.resize((w,h), Image.LANCZOS) + if abs(x + w/2 - S/2) < GAP + w/2: x = S/2 + GAP; continue + if inside(x, y) and inside(x+w, y+h): ink.paste(g, (int(x), int(y)), g) + x += w + 14 +ink = ink.filter(ImageFilter.MaxFilter(3)) # thicker strokes: they are read from metres away +inkf = np.clip(np.asarray(ink, dtype=np.float32)/255*1.4, 0, 1) +# carved: a dark rim just below each line, the line itself light grey +shadow = np.asarray(ink.filter(ImageFilter.GaussianBlur(2)).transform((S,S), Image.AFFINE, (1,0,-1,0,1,-2)), dtype=np.float32)/255 +face = stone*(1 - 0.45*shadow[...,None]) +face = face*(1 - inkf[...,None]) + np.array([0.72,0.73,0.76])*inkf[...,None] +out = Image.fromarray((np.clip(face,0,1)*255).astype(np.uint8)) # top row is v = 1, the apex, as Unity reads a PNG +out.save(os.path.join(d,"AlfarNexus_face.png")) + +# --- preview: the pyramid as AlfarNexus builds it +HGT, B, LIFT = 2.0, 1.0, 0.5 # AlfarNexusLook: 2 m tall, 2 m base, floating 0.5 m up +apex = np.array([0, LIFT+HGT, 0]); c = [np.array(p) for p in [(-B,LIFT,-B),(B,LIFT,-B),(B,LIFT,B),(-B,LIFT,B)]] +L = []; vi = 1; seam = []; sv = 1 +for i in range(4): + a, b = c[i], c[(i+1)%4] + for p in (a, b, apex): L.append("v %f %f %f" % (-p[0], p[1], p[2])) + L += ["vt 0 0", "vt 1 0", "vt 0.5 1", f"f {vi}/{vi} {vi+1}/{vi+1} {vi+2}/{vi+2}"]; vi += 3 + m = (a+b)/2; along = (b-a)/np.linalg.norm(b-a); n = np.cross(b-a, apex-a); n /= np.linalg.norm(n) + if np.dot(n, m - np.array([0, LIFT+HGT/3, 0])) < 0: n = -n + for p in (m-along*0.04+n*0.025, m+along*0.04+n*0.025, apex+n*0.025+along*0.004, apex+n*0.025-along*0.004): # the rib's top + seam.append("v %f %f %f" % (-p[0], p[1], p[2])) + seam.append(f"f {sv}/1 {sv+1}/1 {sv+2}/1 {sv+3}/1"); sv += 4 +for p in c: L.append("v %f %f %f" % (-p[0], p[1], p[2])) +L += ["vt 0 0", f"f {vi}/{3*4+1} {vi+3}/{3*4+1} {vi+2}/{3*4+1} {vi+1}/{3*4+1}"] +open(os.path.join(d,"pyramid.obj"),"w").write("\n".join(L)+"\n") +open(os.path.join(d,"seam.obj"),"w").write("vt 0 0\n" + "\n".join(seam)+"\n") +open(os.path.join(d,"ground.obj"),"w").write("v -2 0 -2\nv 2 0 -2\nv 2 0 2\nv -2 0 2\nvt 0 0\nf 1/1 2/1 3/1 4/1\n") +sh = B*0.85 +open(os.path.join(d,"shadow.obj"),"w").write( + f"v {-sh} 0.005 {-sh}\nv {sh} 0.005 {-sh}\nv {sh} 0.005 {sh}\nv {-sh} 0.005 {sh}\nvt 0 0\nf 1/1 2/1 3/1 4/1\n") +parts = [{'obj':os.path.join(d,'pyramid.obj'),'tex':out}, + {'obj':os.path.join(d,'seam.obj'),'color':(0.35,0.75,1.0),'emissive':True}, + {'obj':os.path.join(d,'ground.obj'),'color':(0.33,0.36,0.3)}, + {'obj':os.path.join(d,'shadow.obj'),'color':(0.18,0.2,0.17)}] +render(parts, os.path.join(d,'prev_nexus.png'), size=640, yaw=25, pitch=-12, light=(0.4,0.8,0.6), fit=(np.array([0,1.4,0]), 2.5)) +# the hammer icon: the pyramid and its seams alone, nearly side-on so two faces show +render(parts[:2], os.path.join(d,'AlfarNexus_icon.png'), size=128, yaw=35, pitch=-12, bg=(0,0,0,0), light=(0.3,0.8,0.7))