Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ModularCarpets v0.3.0
plugins/ModularCarpets.dll
Decompiled 5 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.1", FrameworkDisplayName = ".NET Framework 4.7.1")] [assembly: AssemblyVersion("0.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Carpets { [BepInPlugin("modularcarpets.valheim", "Modular Carpets", "0.3.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] internal class CarpetsPlugin : BaseUnityPlugin { private sealed class Variant { public readonly string Asset; public readonly string Kind; public readonly string Label; public readonly int Scraps; public Variant(string asset, string kind, string label, int scraps) { Asset = asset; Kind = kind; Label = label; Scraps = scraps; } } public const string PluginGuid = "modularcarpets.valheim"; public const string PluginName = "Modular Carpets"; public const string PluginVersion = "0.3.0"; private const string BundleResource = "carpets"; private const string PalettesResource = "palettes.txt"; private const string TemplatePrefab = "rug_straw"; private const string BaseItem = "LeatherScraps"; private const int IconSize = 64; private static readonly Variant[] Variants = new Variant[16] { new Variant("Carpet_Floor_2x2", "straight", "carpet", 4), new Variant("Carpet_Floor_2x2", "end", "carpet end", 4), new Variant("Carpet_Floor_2x2", "corner", "carpet corner", 4), new Variant("Carpet_Floor_2x2", "tee", "carpet T-junction", 4), new Variant("Carpet_Floor_2x2", "cross", "carpet crossing", 4), new Variant("Carpet_Floor_2x2", "edge", "carpet edge", 4), new Variant("Carpet_Floor_2x2", "outer_corner", "carpet outer corner", 4), new Variant("Carpet_Floor_2x2", "edge_inner_se", "carpet edge, inner corner left", 4), new Variant("Carpet_Floor_2x2", "edge_inner_ne", "carpet edge, inner corner right", 4), new Variant("Carpet_Floor_2x2", "fill", "carpet fill", 4), new Variant("Carpet_Floor_2x2", "fill_inner", "carpet fill, inner corner", 4), new Variant("Carpet_Floor_4x2", "reducer", "wide-to-narrow reducer", 8), new Variant("Carpet_Stair", "straight", "stair runner", 6), new Variant("Carpet_Stair", "edge_mirror", "stair runner, left edge", 6), new Variant("Carpet_Stair", "edge", "stair runner, right edge", 6), new Variant("Carpet_Stair", "fill", "stair runner, fill", 6) }; private static readonly string[] PatternOrder = new string[11] { "jute", "twill", "tartan", "crosses", "kilim", "jarl", "selbu", "peel", "hail", "cabin", "medallion" }; private AssetBundle _bundle; private ConfigEntry<bool> _fullResolution; public const string PrefabPrefix = "ModularCarpets_"; private void Awake() { //IL_0066: Unknown result type (might be due to invalid IL or missing references) _bundle = LoadEmbeddedBundle("carpets"); if ((Object)(object)_bundle == (Object)null) { ((BaseUnityPlugin)this).Logger.LogError((object)"Embedded AssetBundle 'carpets' not found"); return; } _fullResolution = ((BaseUnityPlugin)this).Config.Bind<bool>("Graphics", "Full resolution textures", false, "Paint carpets at 256 px per metre instead of 128. Uses four times the video memory (about 240 MB instead of 60 MB for all carpets). Takes effect after a restart."); PrefabManager.OnVanillaPrefabsAvailable += AddPieces; new Harmony("modularcarpets.valheim").PatchAll(typeof(CarpetsPlugin).Assembly); } private void AddPieces() { PrefabManager.OnVanillaPrefabsAvailable -= AddPieces; GameObject prefab = PrefabManager.Instance.GetPrefab("rug_straw"); if ((Object)(object)prefab == (Object)null) { ((BaseUnityPlugin)this).Logger.LogError((object)"Vanilla template 'rug_straw' not found"); return; } Stopwatch stopwatch = Stopwatch.StartNew(); CarpetPainter.Downscale = (_fullResolution.Value ? 1 : 2); CarpetPainter.Init(_bundle.LoadAllAssets<Texture2D>(), ((Renderer)prefab.GetComponentInChildren<MeshRenderer>(true)).sharedMaterial, ReadEmbeddedText("palettes.txt")); double totalSeconds = stopwatch.Elapsed.TotalSeconds; List<string> list = (from p in CarpetPainter.Patterns orderby (Array.IndexOf(PatternOrder, p) >= 0) ? Array.IndexOf(PatternOrder, p) : int.MaxValue, p select p).ToList(); CarpetPainter.PaintAll(from pattern in list from colour in Enumerable.Range(0, CarpetPainter.Palettes.Count) from variant2 in Variants let variant = variant2 where CarpetPainter.HasMask(pattern, variant.Kind) select new CarpetPainter.Job(pattern, variant.Kind, colour)); ((BaseUnityPlugin)this).Logger.LogInfo((object)($"Carpet textures: bundle {totalSeconds:0.00} s, read masks {CarpetPainter.ReadSeconds:0.00} s, " + $"paint {CarpetPainter.PaintSeconds:0.00} s on {CarpetPainter.Threads} threads, upload {CarpetPainter.UploadSeconds:0.00} s")); double totalSeconds2 = stopwatch.Elapsed.TotalSeconds; int num = 0; foreach (string item in list) { for (int num2 = 0; num2 < CarpetPainter.Palettes.Count; num2++) { Variant[] variants = Variants; foreach (Variant variant in variants) { if (!CarpetPainter.HasMask(item, variant.Kind)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Pattern '" + item + "' has no '" + variant.Kind + "' mask; skipping " + variant.Label)); } else if (AddPiece(prefab, variant, item, num2)) { num++; } } } } ((BaseUnityPlugin)this).Logger.LogInfo((object)($"Registered {num} carpet pieces ({list.Count} patterns x {CarpetPainter.Palettes.Count} colours) " + $"in {stopwatch.Elapsed.TotalSeconds:0.0} s (pieces and icons {stopwatch.Elapsed.TotalSeconds - totalSeconds2:0.00} s)")); } private static string PrefabName(Variant variant, string pattern, Palette palette) { return "ModularCarpets_" + variant.Asset.Substring("Carpet_".Length) + "_" + variant.Kind + "_" + pattern + "_" + palette.Id; } private bool AddPiece(GameObject template, Variant variant, string pattern, int colour) { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Expected O, but got Unknown //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Expected O, but got Unknown //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Expected O, but got Unknown //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Expected O, but got Unknown //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Expected O, but got Unknown //IL_0302: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Expected O, but got Unknown GameObject val = _bundle.LoadAsset<GameObject>(variant.Asset); if ((Object)(object)val == (Object)null) { ((BaseUnityPlugin)this).Logger.LogError((object)("Prefab '" + variant.Asset + "' missing from bundle")); return false; } Palette palette = CarpetPainter.Palettes[colour]; GameObject val2 = PrefabManager.Instance.CreateClonedPrefab(PrefabName(variant, pattern, palette), template); foreach (Transform item in ((IEnumerable)val2.transform).Cast<Transform>().ToList()) { Object.DestroyImmediate((Object)(object)((Component)item).gameObject); } foreach (Transform item2 in val.transform) { Transform val3 = item2; GameObject val4 = Object.Instantiate<GameObject>(((Component)val3).gameObject, val2.transform, false); ((Object)val4).name = ((Object)val3).name; } MeshRenderer component = ((Component)val2.transform.Find("model")).GetComponent<MeshRenderer>(); ((Renderer)component).sharedMaterial = CarpetPainter.Get(pattern, variant.Kind, colour); LODGroup component2 = val2.GetComponent<LODGroup>(); if ((Object)(object)component2 != (Object)null) { component2.SetLODs((LOD[])(object)new LOD[1] { new LOD(0.02f, (Renderer[])(object)new Renderer[1] { (Renderer)component }) }); } RequirementConfig[] array = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig("LeatherScraps", variant.Scraps, 0, true) }; if (palette.Item != "LeatherScraps") { array = array.Append(new RequirementConfig(palette.Item, DyeAmount(variant.Scraps), 0, true)).ToArray(); } PieceConfig val5 = new PieceConfig(); val5.Name = Title(pattern) + " " + variant.Label + " (" + palette.Label.ToLowerInvariant() + ")"; val5.Description = "A " + pattern.Replace('_', ' ') + " " + variant.Label + " in " + palette.Label.ToLowerInvariant() + " colours."; val5.PieceTable = "Hammer"; val5.Category = "Modular Carpets - " + Title(pattern); val5.CraftingStation = "piece_workbench"; val5.Requirements = array; PieceConfig val6 = val5; Sprite val7 = RenderManager.Instance.Render(new RenderRequest(val2) { Rotation = RenderManager.IsometricRotation, Width = 64, Height = 64, UseCache = true, TargetPlugin = ((BaseUnityPlugin)this).Info.Metadata }); if ((Object)(object)val7 != (Object)null) { val6.Icon = val7; } PieceManager.Instance.AddPiece(new CustomPiece(val2, false, val6)); return true; } private static int DyeAmount(int scraps) { return (scraps + 3) / 4; } private static AssetBundle LoadEmbeddedBundle(string resourceName) { byte[] array = ReadEmbedded(resourceName); if (array != null) { return AssetBundle.LoadFromMemory(array); } return null; } private static string ReadEmbeddedText(string resourceName) { return Encoding.UTF8.GetString(ReadEmbedded(resourceName) ?? new byte[0]); } private static byte[] ReadEmbedded(string resourceName) { using Stream stream = typeof(CarpetsPlugin).Assembly.GetManifestResourceStream(resourceName); if (stream == null) { return null; } byte[] array = new byte[stream.Length]; int num; for (int i = 0; i < array.Length; i += num) { num = stream.Read(array, i, array.Length - i); if (num <= 0) { break; } } return array; } private static string Title(string pattern) { return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(pattern.Replace('_', ' ')); } } internal sealed class Palette { public string Id; public string Item; public string Label; public Color[] Roles; } internal static class CarpetPainter { internal sealed class Job { public readonly string Pattern; public readonly string Kind; public readonly int Colour; internal byte[] Codes; internal byte[] Noise; internal byte[] Dxt; internal int Width; internal int Height; internal int OutWidth; internal int OutHeight; internal int MipCount; public Job(string pattern, string kind, int colour) { Pattern = pattern; Kind = kind; Colour = colour; } } private sealed class Scratch { public readonly float[] Lut = new float[768]; public readonly int[] Block = new int[48]; public readonly int[] Pal = new int[6]; private byte[] _level = new byte[0]; private byte[] _other = new byte[0]; public byte[] Level(int n) { if (_level.Length < n) { return _level = new byte[n]; } return _level; } public byte[] Other(int n) { if (_other.Length < n) { return _other = new byte[n]; } return _other; } } public static readonly List<Palette> Palettes = new List<Palette>(); public static int Downscale = 2; private static readonly Dictionary<string, Texture2D> Masks = new Dictionary<string, Texture2D>(); private static readonly Dictionary<string, byte[]> Noise = new Dictionary<string, byte[]>(); private static readonly Dictionary<string, Material> Cache = new Dictionary<string, Material>(); private static Material _base; private static Texture2D _flatNormal; public static double ReadSeconds; public static double PaintSeconds; public static double UploadSeconds; public static int Threads; private static readonly float[] Fibre = (from v in Enumerable.Range(0, 256) select (float)v / 255f + 0.5f).ToArray(); public static IEnumerable<string> Patterns => from n in Masks.Keys where n.EndsWith("__noise") select n.Substring("carpet_".Length, n.Length - "carpet_".Length - "__noise".Length); public static void Init(IEnumerable<Texture2D> masks, Material baseMaterial, string palettesText) { _base = baseMaterial; _flatNormal = CreateFlatNormalMap(); foreach (Texture2D mask in masks) { Masks[((Object)mask).name] = mask; } Palettes.Clear(); Palettes.AddRange(ParsePalettes(palettesText)); } public static bool HasMask(string pattern, string kind) { return Masks.ContainsKey(MaskName(pattern, kind)); } public static Material Get(string pattern, string kind, int colour) { if (!Cache.TryGetValue(Key(pattern, kind, colour), out var value) || (Object)(object)value == (Object)null) { PaintAll(new Job[1] { new Job(pattern, kind, colour) }); return Cache[Key(pattern, kind, colour)]; } return value; } public static void PaintAll(IEnumerable<Job> jobs) { //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Expected O, but got Unknown //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Expected O, but got Unknown List<Job> list = (from j in jobs where !Cache.ContainsKey(Key(j.Pattern, j.Kind, j.Colour)) group j by Key(j.Pattern, j.Kind, j.Colour) into g select g.First()).ToList(); for (int num = 0; num < list.Count; num += 240) { List<Job> range = list.GetRange(num, Math.Min(240, list.Count - num)); Stopwatch stopwatch = Stopwatch.StartNew(); Dictionary<string, byte[]> dictionary = new Dictionary<string, byte[]>(); foreach (Job item in range) { string key = MaskName(item.Pattern, item.Kind); Texture2D val = Masks[key]; if (!dictionary.TryGetValue(key, out item.Codes)) { dictionary[key] = (item.Codes = val.GetRawTextureData()); } item.Width = ((Texture)val).width; item.Height = ((Texture)val).height; item.Noise = NoiseOf(item.Pattern); } ReadSeconds += stopwatch.Elapsed.TotalSeconds; Stopwatch stopwatch2 = Stopwatch.StartNew(); RunOnAllCores(range, Math.Max(1, Downscale)); PaintSeconds += stopwatch2.Elapsed.TotalSeconds; stopwatch2 = Stopwatch.StartNew(); foreach (Job item2 in range) { Palette palette = Palettes[item2.Colour]; Texture2D val2 = new Texture2D(item2.OutWidth, item2.OutHeight, (TextureFormat)10, item2.MipCount, false); ((Object)val2).name = "carpet_" + item2.Pattern + "__" + item2.Kind + "__" + palette.Id; ((Texture)val2).wrapModeU = (TextureWrapMode)1; ((Texture)val2).wrapModeV = (TextureWrapMode)0; ((Texture)val2).anisoLevel = 4; ((Texture)val2).filterMode = (FilterMode)2; Texture2D val3 = val2; val3.LoadRawTextureData(item2.Dxt); val3.Apply(false, true); Material val4 = new Material(_base) { name = ((Object)val3).name }; val4.SetTexture("_MainTex", (Texture)(object)val3); val4.SetTexture("_BumpMap", (Texture)(object)_flatNormal); Cache[Key(item2.Pattern, item2.Kind, item2.Colour)] = val4; item2.Codes = (item2.Noise = (item2.Dxt = null)); } UploadSeconds += stopwatch2.Elapsed.TotalSeconds; } } private static void RunOnAllCores(List<Job> part, int s) { int next = -1; Exception failure = null; ThreadStart start = delegate { try { Scratch scratch = new Scratch(); int index; while (failure == null && (index = Interlocked.Increment(ref next)) < part.Count) { Render(part[index], s, scratch); } } catch (Exception ex) { failure = ex; } }; Threads = Math.Max(1, Math.Min(Environment.ProcessorCount, part.Count)); Thread[] array = new Thread[Threads]; for (int num = 0; num < array.Length; num++) { array[num] = new Thread(start) { IsBackground = true, Name = "CarpetPainter" }; array[num].Start(); } Thread[] array2 = array; foreach (Thread thread in array2) { thread.Join(); } if (failure != null) { throw new InvalidOperationException("Painting carpets failed", failure); } } private static string Key(string pattern, string kind, int colour) { return $"{pattern}|{kind}|{colour}"; } private static string MaskName(string pattern, string kind) { return "carpet_" + pattern + "__" + kind; } private static void Render(Job job, int s, Scratch scratch) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) Palette palette = Palettes[job.Colour]; float[] lut = scratch.Lut; for (int i = 0; i < 256; i++) { Color val = palette.Roles[i >> 6]; float num = (float)(i & 0x3F) / 32f * 255f; lut[i * 3] = val.r * num; lut[i * 3 + 1] = val.g * num; lut[i * 3 + 2] = val.b * num; } byte[] codes = job.Codes; byte[] noise = job.Noise; int width = job.Width; int num2 = width / s; int num3 = job.Height / s; int num4 = noise.Length / 256; float num5 = 1f / (float)(s * s); byte[] array = scratch.Level(num2 * num3 * 3); for (int j = 0; j < num3; j++) { for (int k = 0; k < num2; k++) { float num6 = 0f; float num7 = 0f; float num8 = 0f; for (int l = j * s; l < j * s + s; l++) { int num9 = l * width; int num10 = l % num4 * 256; for (int m = k * s; m < k * s + s; m++) { int num11 = codes[num9 + m] * 3; float num12 = Fibre[noise[num10 + (m & 0xFF)]]; num6 += lut[num11] * num12; num7 += lut[num11 + 1] * num12; num8 += lut[num11 + 2] * num12; } } int num13 = (j * num2 + k) * 3; array[num13] = Byte(num6 * num5); array[num13 + 1] = Byte(num7 * num5); array[num13 + 2] = Byte(num8 * num5); } } int num14 = 0; int num15 = 0; int num16 = num2; int num17 = num3; while (true) { num14 += Dxt1.Size(num16, num17); num15++; if (num16 == 1 && num17 == 1) { break; } num16 = Math.Max(1, num16 / 2); num17 = Math.Max(1, num17 / 2); } job.OutWidth = num2; job.OutHeight = num3; job.MipCount = num15; job.Dxt = new byte[num14]; byte[] array2 = scratch.Other(num2 * num3 * 3 / 4 + 3); int nw = num2; int nh = num3; int num18 = 0; while (true) { num18 += Dxt1.Encode(array, nw, nh, job.Dxt, num18, scratch.Block, scratch.Pal); if (nw != 1 || nh != 1) { HalfSize(array, nw, nh, array2, out nw, out nh); byte[] array3 = array; array = array2; array2 = array3; continue; } break; } } private static void HalfSize(byte[] src, int w, int h, byte[] dst, out int nw, out int nh) { nw = Math.Max(1, w / 2); nh = Math.Max(1, h / 2); for (int i = 0; i < nh; i++) { int num = Math.Min(i * 2, h - 1); int num2 = Math.Min(i * 2 + 1, h - 1); for (int j = 0; j < nw; j++) { int num3 = Math.Min(j * 2, w - 1); int num4 = Math.Min(j * 2 + 1, w - 1); for (int k = 0; k < 3; k++) { dst[(i * nw + j) * 3 + k] = (byte)(src[(num * w + num3) * 3 + k] + src[(num * w + num4) * 3 + k] + src[(num2 * w + num3) * 3 + k] + src[(num2 * w + num4) * 3 + k] + 2 >> 2); } } } } private static byte[] NoiseOf(string pattern) { if (!Noise.TryGetValue(pattern, out var value)) { value = (Noise[pattern] = (Masks.TryGetValue(MaskName(pattern, "noise"), out var value2) ? value2.GetRawTextureData() : Enumerable.Repeat((byte)128, 256).ToArray())); } return value; } private static byte Byte(float v) { return (byte)((v < 0f) ? 0f : ((v > 255f) ? 255f : (v + 0.5f))); } private static IEnumerable<Palette> ParsePalettes(string text) { string[] array = text.Split('\n'); foreach (string text2 in array) { string text3 = text2.Split('#')[0].Trim(); if (text3.Length != 0) { string[] array2 = text3.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (array2.Length < 7) { throw new FormatException("palettes.txt: bad line '" + text2.Trim() + "'"); } yield return new Palette { Id = array2[0], Item = array2[1], Label = string.Join(" ", array2.Skip(2).Take(array2.Length - 6)), Roles = array2.Skip(array2.Length - 4).Select(Hex).ToArray() }; } } } private static Color Hex(string h) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) return new Color((float)int.Parse(h.Substring(0, 2), NumberStyles.HexNumber) / 255f, (float)int.Parse(h.Substring(2, 2), NumberStyles.HexNumber) / 255f, (float)int.Parse(h.Substring(4, 2), NumberStyles.HexNumber) / 255f); } private static Texture2D CreateFlatNormalMap() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_002b: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(4, 4, (TextureFormat)4, false, true) { name = "carpet_flat_normal" }; val.SetPixels(Enumerable.Repeat<Color>(new Color(0.5f, 0.5f, 1f, 1f), 16).ToArray()); val.Apply(false, true); return val; } } internal static class Dxt1 { public static int Size(int w, int h) { return (w + 3) / 4 * ((h + 3) / 4) * 8; } public static int Encode(byte[] rgb, int w, int h, byte[] output, int offset, int[] block, int[] pal) { int num = (w + 3) / 4; int num2 = (h + 3) / 4; for (int i = 0; i < num2; i++) { for (int j = 0; j < num; j++) { for (int k = 0; k < 16; k++) { int num3 = Math.Min(j * 4 + (k & 3), w - 1); int num4 = Math.Min(i * 4 + (k >> 2), h - 1); int num5 = (num4 * w + num3) * 3; block[k * 3] = rgb[num5]; block[k * 3 + 1] = rgb[num5 + 1]; block[k * 3 + 2] = rgb[num5 + 2]; } EncodeBlock(block, pal, output, offset + (i * num + j) * 8); } } return num * num2 * 8; } private static void EncodeBlock(int[] px, int[] pal, byte[] output, int at) { float num = 0f; float num2 = 0f; float num3 = 0f; for (int i = 0; i < 16; i++) { num += (float)px[i * 3]; num2 += (float)px[i * 3 + 1]; num3 += (float)px[i * 3 + 2]; } num /= 16f; num2 /= 16f; num3 /= 16f; float num4 = 0f; float num5 = 0f; float num6 = 0f; float num7 = 0f; float num8 = 0f; float num9 = 0f; for (int j = 0; j < 16; j++) { float num10 = (float)px[j * 3] - num; float num11 = (float)px[j * 3 + 1] - num2; float num12 = (float)px[j * 3 + 2] - num3; num4 += num10 * num10; num5 += num10 * num11; num6 += num10 * num12; num7 += num11 * num11; num8 += num11 * num12; num9 += num12 * num12; } float num13 = 0.3f; float num14 = 0.59f; float num15 = 0.11f; for (int k = 0; k < 4; k++) { float num16 = num4 * num13 + num5 * num14 + num6 * num15; float num17 = num5 * num13 + num7 * num14 + num8 * num15; float num18 = num6 * num13 + num8 * num14 + num9 * num15; float num19 = Math.Max(Math.Abs(num16), Math.Max(Math.Abs(num17), Math.Abs(num18))); if (num19 < 1E-06f) { break; } num13 = num16 / num19; num14 = num17 / num19; num15 = num18 / num19; } int num20 = 0; int num21 = 0; float num22 = float.MaxValue; float num23 = float.MinValue; for (int l = 0; l < 16; l++) { float num24 = (float)px[l * 3] * num13 + (float)px[l * 3 + 1] * num14 + (float)px[l * 3 + 2] * num15; if (num24 < num22) { num22 = num24; num20 = l; } if (num24 > num23) { num23 = num24; num21 = l; } } int num25 = To565(px[num21 * 3], px[num21 * 3 + 1], px[num21 * 3 + 2]); int num26 = To565(px[num20 * 3], px[num20 * 3 + 1], px[num20 * 3 + 2]); if (num25 < num26) { int num27 = num25; num25 = num26; num26 = num27; } uint num28 = 0u; if (num25 != num26) { From565(num25, pal, 0); From565(num26, pal, 3); int num29 = pal[0] - pal[3]; int num30 = pal[1] - pal[4]; int num31 = pal[2] - pal[5]; int num32 = num29 * num29 + num30 * num30 + num31 * num31; for (int m = 0; m < 16; m++) { int num33 = 6 * ((px[m * 3] - pal[3]) * num29 + (px[m * 3 + 1] - pal[4]) * num30 + (px[m * 3 + 2] - pal[5]) * num31); uint num34 = ((num33 < num32) ? 1u : ((num33 < 3 * num32) ? 3u : ((num33 < 5 * num32) ? 2u : 0u))); num28 |= num34 << m * 2; } } output[at] = (byte)num25; output[at + 1] = (byte)(num25 >> 8); output[at + 2] = (byte)num26; output[at + 3] = (byte)(num26 >> 8); output[at + 4] = (byte)num28; output[at + 5] = (byte)(num28 >> 8); output[at + 6] = (byte)(num28 >> 16); output[at + 7] = (byte)(num28 >> 24); } private static int To565(int r, int g, int b) { return ((r * 31 + 127) / 255 << 11) | ((g * 63 + 127) / 255 << 5) | ((b * 31 + 127) / 255); } private static void From565(int c, int[] pal, int at) { int num = (c >> 11) & 0x1F; int num2 = (c >> 5) & 0x3F; int num3 = c & 0x1F; pal[at] = (num << 3) | (num >> 2); pal[at + 1] = (num2 << 2) | (num2 >> 4); pal[at + 2] = (num3 << 3) | (num3 >> 2); } } [HarmonyPatch(typeof(Player), "UpdatePlacementGhost")] internal static class StairSnapPatch { private const string Runner = "ModularCarpets_Stair_"; private static readonly HashSet<string> SupportedStairs = new HashSet<string> { "stone_stair", "piece_grausten_stonestair", "blackmarble_stair" }; private static readonly FieldRef<Player, GameObject> Ghost = AccessTools.FieldRefAccess<Player, GameObject>("m_placementGhost"); private static readonly FieldRef<Player, int> ManualSnapPoint = AccessTools.FieldRefAccess<Player, int>("m_manualSnapPoint"); private static readonly MethodInfo PieceRayTest = AccessTools.Method(typeof(Player), "PieceRayTest", (Type[])null, (Type[])null); private static void Postfix(Player __instance) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) GameObject val = Ghost.Invoke(__instance); if (!((Object)(object)val == (Object)null) && val.activeSelf && ManualSnapPoint.Invoke(__instance) < 0 && PrefabName(val).StartsWith("ModularCarpets_Stair_")) { Piece val2 = AimedStair(__instance); if ((Object)(object)val2 != (Object)null) { val.transform.SetPositionAndRotation(((Component)val2).transform.position, ((Component)val2).transform.rotation); } } } private static Piece AimedStair(Player player) { object[] array = new object[6] { null, null, null, null, null, false }; if (PieceRayTest == null || !(bool)PieceRayTest.Invoke(player, array)) { return null; } object obj = array[2]; Piece val = (Piece)((obj is Piece) ? obj : null); if (!((Object)(object)val != (Object)null) || !SupportedStairs.Contains(PrefabName(((Component)val).gameObject))) { return null; } return val; } private static string PrefabName(GameObject go) { string name = ((Object)go).name; int num = name.IndexOf("(Clone)"); if (num < 0) { return name; } return name.Substring(0, num).TrimEnd(); } } }