using System; using System.Collections.Generic; using System.Globalization; using System.Text; using HarmonyLib; using UnityEngine; using UnityEngine.UI; using Object = UnityEngine.Object; namespace UltraParadise { internal static class HealthMirror { public static int Mode; private const int Layer = 31; private const float FrameEvery = 0.1f; private const float RebuildEvery = 30f; private static GameObject rig, holder, canvasGo, cloneGo; private static Camera cam; private static Canvas canvas; private static RenderTexture rt; private static Texture2D readTex; private static WoundView clone, source; private static Body sourceBody; private static float nextFrame, nextVitals, rebuildAt, pendingDt, scale = 0.5f; private static int width, height; private static bool failed; private static string lastState; public static void SetMode(int m) { Mode = Mathf.Clamp(m, 0, 1); lastState = null; nextVitals = 0f; if (Mode < 2) { failed = false; Teardown(); } } public static void Tick() { if (Mode == 0) return; pendingDt += Time.unscaledDeltaTime; Body b = PlayerCamera.main != null && WorldGeneration.world != null ? PlayerCamera.main.body : null; if (Time.unscaledTime >= nextVitals) { nextVitals = Time.unscaledTime + 0.5f; if (b != null) SendVitals(b); else Link.Send("VITALS none"); } if (Mode < 2) return; WoundView src = WoundView.view; if (b == null || src == null || src.body == null || src == clone) { DropClone(); State("norun"); return; } if (failed || Time.unscaledTime < nextFrame || Link.FramePending) return; nextFrame = Time.unscaledTime + FrameEvery; try { if (clone == null || source != src || sourceBody != src.body || Time.unscaledTime >= rebuildAt) Build(src); if (clone == null) return; Render(); State("ok"); } catch (Exception e) { failed = true; Plugin.Log.LogWarning("Health mirror failed: " + e); DropClone(); State("error"); } } private static void State(string s) { if (s == lastState) return; lastState = s; Link.Send("HSTATE " + s); } public static void Click(float fx, float fy) { if (clone == null || source == null || cam == null || width == 0) return; Vector2 p = new Vector2(fx * width, (1f - fy) * height); Image[] limbs = clone.limbImages; if (limbs == null || clone.body == null) return; for (int i = 0; i < limbs.Length; i++) { if (limbs[i] == null || i >= clone.body.limbs.Length || clone.body.limbs[i].dismembered) continue; if (RectTransformUtility.RectangleContainsScreenPoint(limbs[i].rectTransform, p, cam)) { source.limbLookingAt = i; clone.limbLookingAt = i; nextFrame = 0f; return; } } } private static void EnsureRig() { if (rig != null) return; rig = new GameObject("UltraParadiseHealthRig"); rig.hideFlags = HideFlags.HideAndDontSave; Object.DontDestroyOnLoad(rig); rig.transform.position = new Vector3(60000f, 60000f, 0f); holder = new GameObject("Holder"); holder.transform.SetParent(rig.transform, false); holder.SetActive(false); GameObject camGo = new GameObject("Camera"); camGo.transform.SetParent(rig.transform, false); camGo.transform.localPosition = new Vector3(0f, 0f, -20f); cam = camGo.AddComponent(); cam.enabled = false; cam.orthographic = true; cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0f, 0f, 0f, 0f); cam.cullingMask = 1 << Layer; cam.nearClipPlane = 0.1f; cam.farClipPlane = 100f; canvasGo = new GameObject("Canvas"); canvasGo.layer = Layer; canvasGo.transform.SetParent(rig.transform, false); canvas = canvasGo.AddComponent(); canvas.renderMode = RenderMode.ScreenSpaceCamera; canvas.worldCamera = cam; canvas.planeDistance = 10f; } private static void Build(WoundView src) { EnsureRig(); DropClone(); source = src; sourceBody = src.body; rebuildAt = Time.unscaledTime + RebuildEvery; RectTransform srcRt = (RectTransform)src.transform; Vector2 size = srcRt.rect.size; GameObject go = Object.Instantiate(src.gameObject, holder.transform, false); go.name = "HealthMirror"; cloneGo = go; try { foreach (MonoBehaviour mb in go.GetComponentsInChildren(true)) { if (mb == null) continue; Type t = mb.GetType(); if (!string.IsNullOrEmpty(t.Namespace)) continue; if (mb is WoundView || mb is FilledImagePP || mb is ECGVisualizer) continue; try { Object.DestroyImmediate(mb); } catch (Exception) { mb.enabled = false; } } foreach (AudioSource a in go.GetComponentsInChildren(true)) a.enabled = false; Transform tr = go.transform; for (int i = tr.childCount - 1; i >= 0; i--) if (tr.GetChild(i).name == "icon") Object.DestroyImmediate(tr.GetChild(i).gameObject); foreach (Transform t2 in go.GetComponentsInChildren(true)) t2.gameObject.layer = Layer; clone = go.GetComponent(); clone.enabled = false; clone.armorMode = false; clone.body = src.body; clone.limbLookingAt = src.limbLookingAt; RectTransform crt = (RectTransform)go.transform; crt.anchorMin = new Vector2(0.5f, 0.5f); crt.anchorMax = new Vector2(0.5f, 0.5f); crt.sizeDelta = size; crt.anchoredPosition = Vector2.zero; crt.localRotation = Quaternion.identity; crt.localScale = Vector3.one; go.SetActive(true); go.transform.SetParent(canvasGo.transform, false); } finally { WoundView.view = src; } scale = ArtScale(go); canvas.scaleFactor = 1f; SetTarget(256, 256); Canvas.ForceUpdateCanvases(); Rect bounds = Bounds(go); if (bounds.width < 10f || bounds.height < 10f) bounds = new Rect(-size.x * 0.5f, -size.y * 0.5f, size.x, size.y); ((RectTransform)go.transform).anchoredPosition -= bounds.center; int w = Mathf.Clamp(Mathf.CeilToInt(bounds.width * scale) + 4, 32, 1400); int h = Mathf.Clamp(Mathf.CeilToInt(bounds.height * scale) + 4, 32, 1800); canvas.scaleFactor = scale; SetTarget(w, h); } private static float ArtScale(GameObject go) { Dictionary votes = new Dictionary(); float root = Mathf.Max(0.0001f, Mathf.Abs(go.transform.lossyScale.x)); foreach (Image img in go.GetComponentsInChildren(true)) { if (img.sprite == null || img.type != Image.Type.Simple) continue; float sw = img.sprite.rect.width; if (sw < 4f) continue; float ratio = img.rectTransform.rect.width * Mathf.Abs(img.rectTransform.lossyScale.x) / root / sw; int key = Mathf.RoundToInt(ratio * 2f); if (key < 1 || key > 20) continue; int n; votes.TryGetValue(key, out n); votes[key] = n + 1; } int best = 0, bestN = 0; foreach (KeyValuePair kv in votes) if (kv.Value > bestN) { best = kv.Key; bestN = kv.Value; } if (best == 0) return 0.5f; return Mathf.Clamp(2f / (best * 0.5f), 0.25f, 1f); } private static Rect Bounds(GameObject go) { bool any = false; float minX = 0, minY = 0, maxX = 0, maxY = 0; Vector3[] c = new Vector3[4]; Transform ct = canvasGo.transform; foreach (Graphic g in go.GetComponentsInChildren(false)) { if (!g.enabled || g.color.a <= 0.01f) continue; g.rectTransform.GetWorldCorners(c); for (int i = 0; i < 4; i++) { Vector3 p = ct.InverseTransformPoint(c[i]); if (!any) { minX = maxX = p.x; minY = maxY = p.y; any = true; } else { minX = Mathf.Min(minX, p.x); maxX = Mathf.Max(maxX, p.x); minY = Mathf.Min(minY, p.y); maxY = Mathf.Max(maxY, p.y); } } } return any ? Rect.MinMaxRect(minX, minY, maxX, maxY) : new Rect(0, 0, 0, 0); } private static void SetTarget(int w, int h) { if (rt != null && rt.width == w && rt.height == h) return; if (rt != null) { cam.targetTexture = null; rt.Release(); Object.Destroy(rt); } if (readTex != null) Object.Destroy(readTex); rt = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32); rt.filterMode = FilterMode.Point; rt.Create(); cam.targetTexture = rt; readTex = new Texture2D(w, h, TextureFormat.RGBA32, false); readTex.filterMode = FilterMode.Point; width = w; height = h; } private static void Render() { PlayerCamera pc = PlayerCamera.main; Limb selected = pc != null ? pc.selectedLimb : null; clone.body = source.body; clone.limbLookingAt = source.limbLookingAt; clone.timeOpen = 100f; clone.checkTime += pendingDt; pendingDt = 0f; try { clone.UpdateView(); } finally { if (pc != null) pc.selectedLimb = selected; } Canvas.ForceUpdateCanvases(); cam.Render(); RenderTexture prev = RenderTexture.active; RenderTexture.active = rt; readTex.ReadPixels(new Rect(0, 0, width, height), 0, 0, false); readTex.Apply(false); RenderTexture.active = prev; byte[] png = ImageConversion.EncodeToPNG(readTex); Link.PostFrame("HFRAME " + width + " " + height + " " + Convert.ToBase64String(png)); } private static void SendVitals(Body b) { StringBuilder sb = new StringBuilder("VITALS "); CultureInfo ci = CultureInfo.InvariantCulture; int broken = 0, disloc = 0, shrap = 0, missing = 0; float infect = 0f; foreach (Limb l in b.limbs) { if (l == null) continue; if (l.dismembered) { if (!l.prostheticInfo.hasProsthetic) missing++; continue; } if (l.broken) broken++; if (l.dislocated) disloc++; if (l.hasShrapnel) shrap++; infect = Mathf.Max(infect, l.infectionAmount); } sb.Append("alive=").Append(b.alive ? 1 : 0); sb.Append("|crit=").Append(b.isCriticallyDying ? 1 : 0); sb.Append("|arrest=").Append(b.inCardiacArrest ? 1 : 0); sb.Append("|brain=").Append(b.brainHealth.ToString("0.#", ci)); sb.Append("|blood=").Append(b.bloodVolume.ToString("0.#", ci)); sb.Append("|bleed=").Append((b.bloodToLiters(b.totalBleedSpeed * b.bloodScale) * 60f).ToString("0.###", ci)); sb.Append("|oxy=").Append(b.bloodOxygen.ToString("0.#", ci)); sb.Append("|temp=").Append(b.temperature.ToString("0.#", ci)); sb.Append("|consc=").Append(b.consciousness.ToString("0.#", ci)); sb.Append("|pain=").Append(b.averagePain.ToString("0.#", ci)); sb.Append("|hunger=").Append(b.hunger.ToString("0.#", ci)); sb.Append("|thirst=").Append(b.thirst.ToString("0.#", ci)); sb.Append("|energy=").Append(b.energy.ToString("0.#", ci)); sb.Append("|sick=").Append(b.sicknessAmount.ToString("0.#", ci)); sb.Append("|rad=").Append((b.radiationSickness * 0.3f).ToString("0.#", ci)); sb.Append("|venom=").Append(b.venomCurrent.ToString("0.#", ci)); sb.Append("|infect=").Append(infect.ToString("0.#", ci)); sb.Append("|broken=").Append(broken).Append("|disloc=").Append(disloc).Append("|shrapnel=").Append(shrap).Append("|missing=").Append(missing); sb.Append("|mood=").Append(b.totalHappiness.ToString("0.#", ci)); sb.Append("|enc=").Append(b.overEncumberance > 0.01f ? 1 : 0); sb.Append("|radline=").Append(RadiationLine.line != null && RadiationLine.line.active ? 1 : 0); sb.Append("|hr=").Append(b.heartRate.ToString("0", ci)); Link.Send(sb.ToString()); } private static void DropClone() { if (cloneGo != null) { HashSet keep = new HashSet(); if (source != null) foreach (RawImage ri in source.GetComponentsInChildren(true)) if (ri.texture != null) keep.Add(ri.texture); foreach (ECGVisualizer e in cloneGo.GetComponentsInChildren(true)) { RawImage ri = e.GetComponent(); if (ri != null && ri.texture != null && !keep.Contains(ri.texture) && string.IsNullOrEmpty(ri.texture.name)) Object.Destroy(ri.texture); } Object.Destroy(cloneGo); } cloneGo = null; clone = null; source = null; sourceBody = null; } private static void Teardown() { DropClone(); if (rt != null) { if (cam != null) cam.targetTexture = null; rt.Release(); Object.Destroy(rt); rt = null; } if (readTex != null) { Object.Destroy(readTex); readTex = null; } if (rig != null) Object.Destroy(rig); rig = null; width = height = 0; } } [HarmonyPatch(typeof(MoodleManager), "UpdateMoodles")] internal static class MoodleUpdateHook { private static void Prefix(MoodleManager __instance) { if (__instance == MoodleManager.main) MoodleFeed.Begin(); } private static void Postfix(MoodleManager __instance) { if (__instance == MoodleManager.main) MoodleFeed.End(); } } [HarmonyPatch(typeof(MoodleManager), "AddMoodle")] internal static class MoodleAddHook { private static void Postfix(MoodleManager __instance, int intensity, string icon, string name, string desc, bool critical, bool chippedOnly) { if (__instance == MoodleManager.main) MoodleFeed.Add(__instance, intensity, icon, name, desc, critical, chippedOnly); } } internal static class MoodleFeed { private const char F = '\u001f'; private const char R = '\u001e'; private static readonly List rows = new List(); private static readonly HashSet sent = new HashSet(); private static readonly List pending = new List(); private static bool collecting; private static string last; private static float lastAt; public static void Reset() { sent.Clear(); pending.Clear(); last = null; } public static void Begin() { rows.Clear(); collecting = true; } public static void Add(MoodleManager m, int intensity, string icon, string name, string desc, bool critical, bool chippedOnly) { if (!collecting) return; if (chippedOnly && WorldGeneration.unchipped) return; if (rows.Count >= 60) return; Sprite bg = m.backgroundIcons != null && intensity >= 0 && intensity < m.backgroundIcons.Length ? m.backgroundIcons[intensity] : null; Sprite ic = null; if (m.icons != null && icon != null) m.icons.TryGetValue(icon, out ic); StringBuilder sb = new StringBuilder(); sb.Append(Id(bg)).Append(F).Append(Id(ic)).Append(F).Append(critical ? '1' : '0').Append(F).Append(m.sideMoodles ? '1' : '0').Append(F); sb.Append(Clean(name, 80)).Append(F).Append(Clean(desc, 400)); rows.Add(sb.ToString()); } public static void End() { collecting = false; if (!Link.Connected || HealthMirror.Mode == 0) return; string s = string.Join(R.ToString(), rows.ToArray()); if (s == last && Time.unscaledTime - lastAt < 5f) return; last = s; lastAt = Time.unscaledTime; Link.Send("MOODLES " + s); } private static string Id(Sprite s) { if (s == null) return ""; int id = s.GetInstanceID(); if (!sent.Contains(id)) { sent.Add(id); pending.Add(s); } return id.ToString(CultureInfo.InvariantCulture); } private static string Clean(string s, int max) { if (string.IsNullOrEmpty(s)) return ""; StringBuilder sb = new StringBuilder(); bool tag = false; foreach (char c in s) { if (c == '<') { tag = true; continue; } if (c == '>' && tag) { tag = false; continue; } if (tag) continue; if (c == F || c == R || c == '\n' || c == '\r') { sb.Append(' '); continue; } sb.Append(c); if (sb.Length >= max) break; } return sb.ToString().Trim(); } public static void Pump() { if (pending.Count == 0 || !Link.Connected) return; int n = 0; while (pending.Count > 0 && n < 4) { Sprite s = pending[0]; pending.RemoveAt(0); n++; if (s == null) continue; byte[] png = Png(s); if (png != null) Link.Post("MICON " + s.GetInstanceID().ToString(CultureInfo.InvariantCulture) + " " + Convert.ToBase64String(png)); } } private static byte[] Png(Sprite s) { Texture t = s.texture; if (t == null) return null; Rect r = s.textureRect; int w = Mathf.RoundToInt(r.width), h = Mathf.RoundToInt(r.height); if (w <= 0 || h <= 0 || w > 512 || h > 512) return null; RenderTexture rt = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGB32); RenderTexture prev = RenderTexture.active; Texture2D tex = null; try { rt.filterMode = FilterMode.Point; Graphics.Blit(t, rt, new Vector2(r.width / t.width, r.height / t.height), new Vector2(r.x / t.width, r.y / t.height)); RenderTexture.active = rt; tex = new Texture2D(w, h, TextureFormat.RGBA32, false); tex.ReadPixels(new Rect(0, 0, w, h), 0, 0); tex.Apply(); return tex.EncodeToPNG(); } catch (Exception) { return null; } finally { RenderTexture.active = prev; RenderTexture.ReleaseTemporary(rt); if (tex != null) Object.Destroy(tex); } } } internal static class BarkFeed { private static PantSound lastPs; private static string lastSet; private static float nextCheck; private static readonly List waiting = new List(); public static void Reset() { lastPs = null; lastSet = null; nextCheck = 0f; waiting.Clear(); } public static string Key(AudioClip c) { if (c == null || string.IsNullOrEmpty(c.name)) return null; StringBuilder sb = new StringBuilder(); foreach (char ch in c.name) { if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-') sb.Append(ch); if (sb.Length >= 40) break; } return sb.Length > 0 ? sb.ToString() : null; } public static void Tick() { if (!Link.Connected) return; Pump(); if (Time.unscaledTime < nextCheck) return; nextCheck = Time.unscaledTime + 1f; Body b = PlayerCamera.main != null && WorldGeneration.world != null ? PlayerCamera.main.body : null; if (b == null) return; PantSound ps = b.GetComponent(); if (ps == null || ps.barkSounds == null) return; List names = new List(); foreach (AudioClip c in ps.barkSounds) { string k = Key(c); if (k != null && !names.Contains(k)) names.Add(k); } if (names.Count == 0) return; string set = b.voicePitch.ToString("0.###", CultureInfo.InvariantCulture) + " " + string.Join(",", names.ToArray()); lastPs = ps; if (set == lastSet) return; lastSet = set; Link.Send("BARKSET " + set); } public static void Request(string name) { if (lastPs == null || lastPs.barkSounds == null || waiting.Count > 8) return; foreach (AudioClip c in lastPs.barkSounds) { if (c == null || Key(c) != name || waiting.Contains(c)) continue; if (c.loadState != AudioDataLoadState.Loaded) c.LoadAudioData(); waiting.Add(c); return; } } private static void Pump() { for (int i = waiting.Count - 1; i >= 0; i--) { AudioClip c = waiting[i]; if (c == null || c.loadState == AudioDataLoadState.Failed) { waiting.RemoveAt(i); continue; } if (c.loadState != AudioDataLoadState.Loaded) continue; waiting.RemoveAt(i); try { byte[] wav = Wav(c); if (wav != null) Link.Post("SFX " + Key(c) + " " + Convert.ToBase64String(wav)); } catch (Exception e) { Plugin.Log.LogWarning("Couldn't read " + c.name + ": " + e.Message); } } } private static byte[] Wav(AudioClip c) { int ch = c.channels, rate = c.frequency, samples = c.samples; if (ch < 1 || ch > 2 || rate < 8000 || rate > 96000 || samples <= 0 || samples > rate * 8) return null; float[] data = new float[samples * ch]; if (!c.GetData(data, 0)) return null; int bytes = data.Length * 2; byte[] o = new byte[44 + bytes]; Action i32 = delegate (int at, int v) { o[at] = (byte)v; o[at + 1] = (byte)(v >> 8); o[at + 2] = (byte)(v >> 16); o[at + 3] = (byte)(v >> 24); }; o[0] = (byte)'R'; o[1] = (byte)'I'; o[2] = (byte)'F'; o[3] = (byte)'F'; i32(4, 36 + bytes); o[8] = (byte)'W'; o[9] = (byte)'A'; o[10] = (byte)'V'; o[11] = (byte)'E'; o[12] = (byte)'f'; o[13] = (byte)'m'; o[14] = (byte)'t'; o[15] = (byte)' '; i32(16, 16); o[20] = 1; o[21] = 0; o[22] = (byte)ch; o[23] = 0; i32(24, rate); i32(28, rate * ch * 2); o[32] = (byte)(ch * 2); o[33] = 0; o[34] = 16; o[35] = 0; o[36] = (byte)'d'; o[37] = (byte)'a'; o[38] = (byte)'t'; o[39] = (byte)'a'; i32(40, bytes); int p = 44; for (int i = 0; i < data.Length; i++) { int v = (int)(Mathf.Clamp(data[i], -1f, 1f) * 32767f); o[p++] = (byte)v; o[p++] = (byte)(v >> 8); } return o; } } }