Decompiled source of PerformantTerrain v1.0.0

PerformantTerrain.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("PerformantTerrain")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PerformantTerrain")]
[assembly: AssemblyTitle("PerformantTerrain")]
[assembly: AssemblyVersion("1.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 PerformantTerrain
{
	[BepInPlugin("com.dreich.performantterrain", "Performant Terrain", "1.0.0")]
	public class PerformantTerrain : BaseUnityPlugin
	{
		public const string Guid = "com.dreich.performantterrain";

		public const string Name = "Performant Terrain";

		public const string Version = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<int> MaxCachedZones;

		internal static ConfigEntry<bool> LogStats;

		private float nextStats;

		private void Awake()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Keep the ground of zones you leave, so coming back doesn't have to rebuild its shape and collision.");
			MaxCachedZones = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxCachedZones", 64, new ConfigDescription("How many 64x64 m zones of ground to keep. Each one is about a third of a megabyte; the oldest are dropped first.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(8, 1024), Array.Empty<object>()));
			LogStats = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "LogStats", false, "Every 30 seconds, write how many zones of ground were reused and how many had to be rebuilt.");
			new Harmony("com.dreich.performantterrain").PatchAll();
		}

		private void Update()
		{
			TerrainCache.Tick();
			if (LogStats.Value && !(Time.time < nextStats))
			{
				nextStats = Time.time + 30f;
				TerrainCache.ReportStats();
			}
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct FloatBits
	{
		[FieldOffset(0)]
		public float Value;

		[FieldOffset(0)]
		public uint Bits;
	}
	internal static class TerrainCache
	{
		private sealed class Entry
		{
			public Vector3 Position;

			public int Width;

			public float Scale;

			public ulong Hash;

			public Mesh Collision;

			public Mesh Render;

			public Bounds Bounds;

			public BoundingSphere Sphere;

			public Task Bake;

			public LinkedListNode<Entry> Node;
		}

		private static readonly FieldRef<Heightmap, bool> IsDistantLod = AccessTools.FieldRefAccess<Heightmap, bool>("m_isDistantLod");

		private static readonly FieldRef<Heightmap, List<float>> Heights = AccessTools.FieldRefAccess<Heightmap, List<float>>("m_heights");

		private static readonly FieldRef<Heightmap, MeshCollider> Collider = AccessTools.FieldRefAccess<Heightmap, MeshCollider>("m_collider");

		private static readonly FieldRef<Heightmap, MeshFilter> Filter = AccessTools.FieldRefAccess<Heightmap, MeshFilter>("m_meshFilter");

		private static readonly FieldRef<Heightmap, Mesh> CollisionMesh = AccessTools.FieldRefAccess<Heightmap, Mesh>("m_collisionMesh");

		private static readonly FieldRef<Heightmap, Mesh> RenderMesh = AccessTools.FieldRefAccess<Heightmap, Mesh>("m_renderMesh");

		private static readonly FieldRef<Heightmap, Bounds> BoundsField = AccessTools.FieldRefAccess<Heightmap, Bounds>("m_bounds");

		private static readonly FieldRef<Heightmap, BoundingSphere> SphereField = AccessTools.FieldRefAccess<Heightmap, BoundingSphere>("m_boundingSphere");

		private static readonly List<Entry> entries = new List<Entry>();

		private static readonly LinkedList<Entry> order = new LinkedList<Entry>();

		private static readonly Dictionary<Heightmap, ulong> builtHash = new Dictionary<Heightmap, ulong>();

		private static readonly HashSet<Heightmap> reusedRender = new HashSet<Heightmap>();

		private static readonly List<Entry> pendingDestroy = new List<Entry>();

		private static int reused;

		private static int rebuilt;

		private static bool Usable(Heightmap heightmap)
		{
			if (PerformantTerrain.Enabled.Value && (Object)(object)heightmap != (Object)null && !IsDistantLod.Invoke(heightmap))
			{
				return (Object)(object)Collider.Invoke(heightmap) != (Object)null;
			}
			return false;
		}

		private static ulong HashHeights(List<float> heights)
		{
			ulong num = 14695981039346656037uL;
			for (int i = 0; i < heights.Count; i++)
			{
				uint bits = new FloatBits
				{
					Value = heights[i]
				}.Bits;
				num = (num ^ bits) * 1099511628211L;
			}
			return num ^ (ulong)heights.Count;
		}

		private static Entry Find(Heightmap heightmap, ulong hash)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)heightmap).transform.position;
			foreach (Entry entry in entries)
			{
				if (entry.Hash == hash && entry.Width == heightmap.m_width && Mathf.Approximately(entry.Scale, heightmap.m_scale))
				{
					Vector3 val = entry.Position - position;
					if (!(((Vector3)(ref val)).sqrMagnitude > 0.01f))
					{
						return entry;
					}
				}
			}
			return null;
		}

		internal static bool BeforeCollision(Heightmap heightmap)
		{
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			reusedRender.Remove(heightmap);
			if (!Usable(heightmap))
			{
				return true;
			}
			ulong num = HashHeights(Heights.Invoke(heightmap));
			builtHash[heightmap] = num;
			Entry entry = Find(heightmap, num);
			if (entry == null || (entry.Bake != null && !entry.Bake.IsCompleted) || (Object)(object)entry.Collision == (Object)null || (Object)(object)entry.Render == (Object)null)
			{
				rebuilt++;
				return true;
			}
			Take(entry);
			Mesh val = CollisionMesh.Invoke(heightmap);
			Mesh val2 = RenderMesh.Invoke(heightmap);
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			if ((Object)(object)val2 != (Object)null)
			{
				Object.Destroy((Object)(object)val2);
			}
			CollisionMesh.Invoke(heightmap) = entry.Collision;
			RenderMesh.Invoke(heightmap) = entry.Render;
			Collider.Invoke(heightmap).sharedMesh = entry.Collision;
			BoundsField.Invoke(heightmap) = entry.Bounds;
			SphereField.Invoke(heightmap) = entry.Sphere;
			reusedRender.Add(heightmap);
			reused++;
			return false;
		}

		internal static bool BeforeRender(Heightmap heightmap)
		{
			if (!reusedRender.Remove(heightmap))
			{
				return true;
			}
			Filter.Invoke(heightmap).sharedMesh = RenderMesh.Invoke(heightmap);
			return false;
		}

		internal static void BeforeDestroy(Heightmap heightmap)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			reusedRender.Remove(heightmap);
			if (!builtHash.TryGetValue(heightmap, out var value))
			{
				return;
			}
			builtHash.Remove(heightmap);
			if (!Usable(heightmap) || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			Mesh val = CollisionMesh.Invoke(heightmap);
			Mesh val2 = RenderMesh.Invoke(heightmap);
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null))
			{
				Entry entry = Find(heightmap, value);
				if (entry != null)
				{
					Drop(entry);
				}
				Entry entry2 = new Entry
				{
					Position = ((Component)heightmap).transform.position,
					Width = heightmap.m_width,
					Scale = heightmap.m_scale,
					Hash = value,
					Collision = val,
					Render = val2,
					Bounds = BoundsField.Invoke(heightmap),
					Sphere = SphereField.Invoke(heightmap)
				};
				int meshId = ((Object)val).GetInstanceID();
				MeshColliderCookingOptions options = Collider.Invoke(heightmap).cookingOptions;
				entry2.Bake = Task.Run(delegate
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					Physics.BakeMesh(meshId, false, options);
				});
				CollisionMesh.Invoke(heightmap) = null;
				RenderMesh.Invoke(heightmap) = null;
				entries.Add(entry2);
				entry2.Node = order.AddLast(entry2);
				while (entries.Count > PerformantTerrain.MaxCachedZones.Value && order.First != null)
				{
					Drop(order.First.Value);
				}
			}
		}

		private static void Take(Entry entry)
		{
			entries.Remove(entry);
			order.Remove(entry.Node);
		}

		private static void Drop(Entry entry)
		{
			Take(entry);
			pendingDestroy.Add(entry);
		}

		internal static void Tick()
		{
			for (int num = pendingDestroy.Count - 1; num >= 0; num--)
			{
				Entry entry = pendingDestroy[num];
				if (entry.Bake == null || entry.Bake.IsCompleted)
				{
					if ((Object)(object)entry.Collision != (Object)null)
					{
						Object.Destroy((Object)(object)entry.Collision);
					}
					if ((Object)(object)entry.Render != (Object)null)
					{
						Object.Destroy((Object)(object)entry.Render);
					}
					pendingDestroy.RemoveAt(num);
				}
			}
		}

		internal static void Clear()
		{
			foreach (Entry item in new List<Entry>(entries))
			{
				Drop(item);
			}
			builtHash.Clear();
			reusedRender.Clear();
		}

		internal static void ReportStats()
		{
			PerformantTerrain.Log.LogInfo((object)("Ground in the last 30 s: " + reused + " zones reused, " + rebuilt + " rebuilt. Zones kept: " + entries.Count + "."));
			reused = 0;
			rebuilt = 0;
		}
	}
	[HarmonyPatch(typeof(Heightmap), "RebuildCollisionMesh")]
	internal static class RebuildCollisionMeshPatch
	{
		private static bool Prefix(Heightmap __instance)
		{
			return TerrainCache.BeforeCollision(__instance);
		}
	}
	[HarmonyPatch(typeof(Heightmap), "RebuildRenderMesh")]
	internal static class RebuildRenderMeshPatch
	{
		private static bool Prefix(Heightmap __instance)
		{
			return TerrainCache.BeforeRender(__instance);
		}
	}
	[HarmonyPatch(typeof(Heightmap), "OnDestroy")]
	internal static class HeightmapDestroyPatch
	{
		private static void Prefix(Heightmap __instance)
		{
			TerrainCache.BeforeDestroy(__instance);
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnDestroy")]
	internal static class WorldClosedPatch
	{
		private static void Postfix()
		{
			TerrainCache.Clear();
		}
	}
}