Decompiled source of GeosPerformance v0.1.0

GeosPerformance.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("GeosPerformance")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Higher frame rates in large factories")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+a2afa3d962886bb25a72d1d0ae45167e1d694804")]
[assembly: AssemblyProduct("GeosPerformance")]
[assembly: AssemblyTitle("GeosPerformance")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 GeosPerformance
{
	internal static class AnimUploads
	{
		private sealed class Uploaded
		{
			public Array? Pool;

			public long Tick = -1L;

			public int Count = -1;
		}

		public static bool Enabled = true;

		private static readonly ConditionalWeakTable<ComputeBuffer, Uploaded> State = new ConditionalWeakTable<ComputeBuffer, Uploaded>();

		private static PlanetFactory? _factory;

		[HarmonyPatch(typeof(FactoryModel), "DrawInstancedBatches")]
		[HarmonyPrefix]
		private static void Before(FactoryModel __instance)
		{
			_factory = __instance.planet?.factory;
		}

		[HarmonyPatch(typeof(FactoryModel), "DrawInstancedBatches")]
		[HarmonyPostfix]
		private static void After()
		{
			_factory = null;
		}

		[HarmonyPatch(typeof(FactoryModel), "DrawInstancedBatches")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo setData = AccessTools.Method(typeof(ComputeBuffer), "SetData", new Type[1] { typeof(Array) }, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, setData))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = AccessTools.Method(typeof(AnimUploads), "SetData", (Type[])null, (Type[])null);
				}
				yield return instruction;
			}
		}

		private static int Cursor(PlanetFactory f, Array pool)
		{
			if (pool == f.entityAnimPool || pool == f.entitySignPool)
			{
				return f.entityCursor;
			}
			if (pool == f.craftAnimPool)
			{
				return f.craftCursor;
			}
			if (pool == f.veinAnimPool)
			{
				return f.veinCursor;
			}
			if (pool == f.enemyAnimPool)
			{
				return f.enemyCursor;
			}
			return -1;
		}

		private static void SetData(ComputeBuffer buffer, Array pool)
		{
			int num = ((Enabled && _factory != null) ? Cursor(_factory, pool) : (-1));
			if (num < 0 || num > pool.Length)
			{
				buffer.SetData(pool);
				return;
			}
			Uploaded value = State.GetValue(buffer, (ComputeBuffer _) => new Uploaded());
			long gameTick = GameMain.gameTick;
			if (value.Pool != pool || value.Count != num || value.Tick != gameTick || GameMain.isPaused)
			{
				buffer.SetData(pool, 0, 0, num);
				Uploaded uploaded = value;
				Uploaded uploaded2 = value;
				int count = num;
				long tick = gameTick;
				uploaded.Pool = pool;
				uploaded2.Count = count;
				value.Tick = tick;
			}
		}
	}
	internal static class BeltCulling
	{
		public static bool Enabled = true;

		private static readonly ConditionalWeakTable<BeltRenderingBatch, BeltTarget> Targets = new ConditionalWeakTable<BeltRenderingBatch, BeltTarget>();

		[HarmonyPatch(typeof(BeltRenderingBatch), "Free")]
		[HarmonyPrefix]
		private static void Free(BeltRenderingBatch __instance)
		{
			if (Targets.TryGetValue(__instance, out BeltTarget value))
			{
				value.Release();
				Targets.Remove(__instance);
			}
		}

		[HarmonyPatch(typeof(BeltRenderingBatch), "AddNode")]
		[HarmonyPatch(typeof(BeltRenderingBatch), "AddNodeNoRefresh")]
		[HarmonyPatch(typeof(BeltRenderingBatch), "RemoveNode")]
		[HarmonyPostfix]
		private static void NodesChanged(BeltRenderingBatch __instance)
		{
			if (Targets.TryGetValue(__instance, out BeltTarget value))
			{
				value.Changed = true;
			}
		}

		private static bool OnLocalPlanet(BeltRenderingBatch batch)
		{
			BeltRenderingBatch[] array = GameMain.localPlanet?.factory?.cargoTraffic?.beltRenderingBatch;
			if (array == null)
			{
				return false;
			}
			BeltRenderingBatch[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				if (array2[i] == batch)
				{
					return true;
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(BeltRenderingBatch), "Draw")]
		[HarmonyPrefix]
		private static bool Draw(BeltRenderingBatch __instance, Camera _cam)
		{
			if (!Enabled || (Object)(object)_cam == (Object)null || (Object)(object)_cam != (Object)(object)GameCamera.main || !OnLocalPlanet(__instance))
			{
				return true;
			}
			if (__instance.nodeCursor - __instance.nodeRecycleCursor <= 0)
			{
				return false;
			}
			BeltTarget value = Targets.GetValue(__instance, (BeltRenderingBatch key) => new BeltTarget(key));
			value.Draw(_cam);
			FrameCulling.Register(value);
			return false;
		}
	}
	internal sealed class BeltTarget : ICullTarget
	{
		private static readonly Bounds Everywhere = new Bounds(Vector3.zero, new Vector3(10000f, 10000f, 10000f));

		private static readonly int AnchorId = Shader.PropertyToID("_Buffer");

		private static readonly int StateId = Shader.PropertyToID("_BeltStateBuffer");

		private const int ChunkSize = 8192;

		private readonly BeltRenderingBatch _batch;

		private ComputeBuffer? _anchorBuffer;

		private ComputeBuffer? _stateBuffer;

		private readonly ComputeBuffer _args = new ComputeBuffer(5, 4, (ComputeBufferType)256);

		private readonly uint[] _argArray = new uint[5];

		private readonly MaterialPropertyBlock _props = new MaterialPropertyBlock();

		private BeltAnchor[] _anchorStaging = (BeltAnchor[])(object)new BeltAnchor[128];

		private float[] _stateStaging = new float[128];

		private int[] _counts = new int[4];

		private BeltAnchor[] _anchors;

		private float[] _states;

		private int _width;

		private int _instances;

		private int _chunks;

		private View _view;

		private int _pending;

		private int _total;

		private BeltAnchor[] _anchorPacked = (BeltAnchor[])(object)new BeltAnchor[128];

		private float[] _statePacked = new float[128];

		private byte[] _cascade = new byte[128];

		private readonly CascadeCounts _cascades = new CascadeCounts();

		private readonly int[] _bucket = new int[5];

		private const float BeltReach = 1.5f;

		private float[] _spheres = new float[128];

		private BeltAnchor[]? _bounded;

		private bool _rebuild;

		public bool Changed = true;

		public int LastDrawn { get; private set; } = -1;

		public bool Alive { get; private set; } = true;

		public int Visible { get; private set; }

		public int Total { get; private set; }

		public BeltTarget(BeltRenderingBatch batch)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			_batch = batch;
		}

		public void Release()
		{
			Alive = false;
			ComputeBuffer? anchorBuffer = _anchorBuffer;
			if (anchorBuffer != null)
			{
				anchorBuffer.Release();
			}
			ComputeBuffer? stateBuffer = _stateBuffer;
			if (stateBuffer != null)
			{
				stateBuffer.Release();
			}
			_anchorBuffer = (_stateBuffer = null);
			_args.Release();
			_cascades.Release();
		}

		public void Draw(Camera camera)
		{
			//IL_010f: 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_0063: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			LastDrawn = Time.frameCount;
			BeltRenderingBatch batch = _batch;
			if (_anchorBuffer == null || _anchorBuffer.count < batch.nodeCapacity)
			{
				ComputeBuffer? anchorBuffer = _anchorBuffer;
				if (anchorBuffer != null)
				{
					anchorBuffer.Release();
				}
				ComputeBuffer? stateBuffer = _stateBuffer;
				if (stateBuffer != null)
				{
					stateBuffer.Release();
				}
				_anchorBuffer = new ComputeBuffer(batch.nodeCapacity, 32, (ComputeBufferType)0);
				_stateBuffer = new ComputeBuffer(batch.nodeCapacity, 4, (ComputeBufferType)0);
				_argArray[1] = 0u;
			}
			Mesh val = Configs.builtin.beltMesh[batch.batchIndex];
			if ((Object)(object)batch.beltMat == (Object)null)
			{
				batch.beltMat = Object.Instantiate<Material>(Configs.builtin.beltMat[batch.batchIndex]);
			}
			_argArray[0] = val.GetIndexCount(0);
			_args.SetData((Array)_argArray);
			_props.SetBuffer(AnchorId, _anchorBuffer);
			_props.SetBuffer(StateId, _stateBuffer);
			Graphics.DrawMeshInstancedIndirect(val, 0, batch.beltMat, Everywhere, _args, 0, _props, (ShadowCastingMode)1, true, 0, camera, (LightProbeUsage)1);
		}

		public int Prepare(View view)
		{
			_chunks = 0;
			BeltRenderingBatch batch = _batch;
			if (batch.nodePool == null || batch.statePool == null || !Alive)
			{
				return 0;
			}
			_anchors = batch.nodePool;
			_states = batch.statePool;
			_width = batch.nodeWidth;
			_instances = Math.Min(batch.nodeCursor, Math.Min(_anchors.Length, _states.Length)) / _width;
			_view = view;
			_chunks = (_instances + 8192 - 1) / 8192;
			if (_anchorStaging.Length < _anchors.Length)
			{
				_anchorStaging = (BeltAnchor[])(object)new BeltAnchor[_anchors.Length];
			}
			if (_stateStaging.Length < _anchors.Length)
			{
				_stateStaging = new float[_anchors.Length];
			}
			if (_anchorPacked.Length < _anchors.Length)
			{
				_anchorPacked = (BeltAnchor[])(object)new BeltAnchor[_anchors.Length];
			}
			if (_statePacked.Length < _anchors.Length)
			{
				_statePacked = new float[_anchors.Length];
			}
			if (_cascade.Length < _instances)
			{
				_cascade = new byte[_anchors.Length / _width + 1];
			}
			_rebuild = Changed || _bounded != _anchors || _spheres.Length < _instances * 5;
			if (_spheres.Length < _instances * 5)
			{
				_spheres = new float[(_anchors.Length / _width + 1) * 5];
			}
			Changed = false;
			_bounded = _anchors;
			if (_counts.Length < _chunks)
			{
				_counts = new int[_chunks];
			}
			Total = _instances;
			_pending = _chunks;
			return _chunks;
		}

		public unsafe void Run(int k)
		{
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			int width = _width;
			int num = k * 8192;
			int num2 = Math.Min(_instances, num + 8192);
			View view = _view;
			int num3 = 0;
			fixed (BeltAnchor* anchors = _anchors)
			{
				fixed (float* states = _states)
				{
					fixed (BeltAnchor* anchorStaging = _anchorStaging)
					{
						fixed (float* stateStaging = _stateStaging)
						{
							BeltAnchor* ptr = (BeltAnchor*)((byte*)anchorStaging + (nint)(num * width) * (nint)Unsafe.SizeOf<BeltAnchor>());
							float* ptr2 = stateStaging + num * width;
							bool rebuild = _rebuild;
							fixed (float* spheres = _spheres)
							{
								for (int i = num; i < num2; i++)
								{
									BeltAnchor* ptr3 = (BeltAnchor*)((byte*)anchors + (nint)(i * width) * (nint)Unsafe.SizeOf<BeltAnchor>());
									float* ptr4 = spheres + i * 5;
									if (rebuild)
									{
										Bound(ptr3, width, ptr4);
									}
									float num4 = ptr4[3];
									if (num4 < 0f)
									{
										continue;
									}
									float x = *ptr4;
									float y = ptr4[1];
									float z = ptr4[2];
									if (view.ContainsOrShadows(x, y, z, num4, ptr4[4]))
									{
										_cascade[num + num3] = (byte)view.Cascades.First(x, y, z, 0f, num4);
										float* ptr5 = states + i * width;
										for (int j = 0; j < width; j++)
										{
											Unsafe.Write((byte*)ptr + (nint)(num3 * width + j) * (nint)Unsafe.SizeOf<BeltAnchor>(), ((BeltAnchor*)ptr3)[j]);
											ptr2[num3 * width + j] = ptr5[j];
										}
										num3++;
									}
								}
							}
						}
					}
				}
			}
			_counts[k] = num3;
			if (Interlocked.Decrement(ref _pending) == 0)
			{
				Pack();
			}
		}

		private unsafe static void Bound(BeltAnchor* a, int width, float* sphere)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			if (((BeltAnchor)a).t <= 1f)
			{
				sphere[3] = -1f;
				return;
			}
			float num = ((Vector3)(&((BeltAnchor)a).pos)).x;
			float num2 = ((Vector3)(&((BeltAnchor)a).pos)).y;
			float num3 = ((Vector3)(&((BeltAnchor)a).pos)).z;
			float num4 = num;
			float num5 = num2;
			float num6 = num3;
			for (int i = 1; i < width; i++)
			{
				Vector3 pos = ((BeltAnchor)((byte*)a + (nint)i * (nint)Unsafe.SizeOf<BeltAnchor>())).pos;
				num = Math.Min(num, pos.x);
				num2 = Math.Min(num2, pos.y);
				num3 = Math.Min(num3, pos.z);
				num4 = Math.Max(num4, pos.x);
				num5 = Math.Max(num5, pos.y);
				num6 = Math.Max(num6, pos.z);
			}
			float num7 = (num + num4) * 0.5f;
			float num8 = (num2 + num5) * 0.5f;
			float num9 = (num3 + num6) * 0.5f;
			float num10 = 0f;
			for (int j = 0; j < width; j++)
			{
				float num11 = ((Vector3)(&((BeltAnchor)((byte*)a + (nint)j * (nint)Unsafe.SizeOf<BeltAnchor>())).pos)).x - num7;
				float num12 = ((Vector3)(&((BeltAnchor)((byte*)a + (nint)j * (nint)Unsafe.SizeOf<BeltAnchor>())).pos)).y - num8;
				float num13 = ((Vector3)(&((BeltAnchor)((byte*)a + (nint)j * (nint)Unsafe.SizeOf<BeltAnchor>())).pos)).z - num9;
				num10 = Math.Max(num10, num11 * num11 + num12 * num12 + num13 * num13);
			}
			float num14 = Mathf.Sqrt(num10) + 1.5f;
			float num15 = Mathf.Sqrt(num7 * num7 + num8 * num8 + num9 * num9) + num14;
			ref float reference = ref *sphere;
			ref float reference2 = ref sphere[1];
			ref float reference3 = ref sphere[2];
			ref float reference4 = ref sphere[3];
			float* num16 = sphere + 4;
			float num17 = num7;
			float num18 = num8;
			float num19 = num9;
			float num20 = num14;
			float num21 = num15 * num15;
			reference = num17;
			reference2 = num18;
			reference3 = num19;
			reference4 = num20;
			*num16 = num21;
		}

		private unsafe void Pack()
		{
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			int width = _width;
			int[] bucket = _bucket;
			Array.Clear(bucket, 0, bucket.Length);
			for (int i = 0; i < _chunks; i++)
			{
				int j = i * 8192;
				for (int num = j + _counts[i]; j < num; j++)
				{
					bucket[_cascade[j]]++;
				}
			}
			int[] prefix = _cascades.Prefix;
			int num2 = 0;
			for (int k = 0; k <= 4; k++)
			{
				int num3 = bucket[k];
				bucket[k] = num2;
				num2 = (prefix[k] = num2 + num3);
			}
			fixed (BeltAnchor* anchorStaging = _anchorStaging)
			{
				fixed (BeltAnchor* anchorPacked = _anchorPacked)
				{
					fixed (float* stateStaging = _stateStaging)
					{
						fixed (float* statePacked = _statePacked)
						{
							fixed (byte* cascade = _cascade)
							{
								for (int l = 0; l < _chunks; l++)
								{
									int m = l * 8192;
									for (int num4 = m + _counts[l]; m < num4; m++)
									{
										int num5 = bucket[cascade[m]]++;
										BeltAnchor* ptr = (BeltAnchor*)((byte*)anchorStaging + (nint)(m * width) * (nint)Unsafe.SizeOf<BeltAnchor>());
										BeltAnchor* ptr2 = (BeltAnchor*)((byte*)anchorPacked + (nint)(num5 * width) * (nint)Unsafe.SizeOf<BeltAnchor>());
										float* ptr3 = stateStaging + m * width;
										float* ptr4 = statePacked + num5 * width;
										for (int n = 0; n < width; n++)
										{
											Unsafe.Write((byte*)ptr2 + (nint)n * (nint)Unsafe.SizeOf<BeltAnchor>(), ((BeltAnchor*)ptr)[n]);
											ptr4[n] = ptr3[n];
										}
									}
								}
							}
						}
					}
				}
			}
			_total = num2;
		}

		public void Upload()
		{
			if (!Alive || _anchorBuffer == null || _stateBuffer == null)
			{
				return;
			}
			int width = _width;
			int num = ((_chunks != 0) ? Math.Min(_total, _anchorBuffer.count / width) : 0);
			if (num > 0)
			{
				_anchorBuffer.SetData((Array)_anchorPacked, 0, 0, num * width);
				_stateBuffer.SetData((Array)_statePacked, 0, 0, num * width);
			}
			_argArray[1] = (uint)num;
			_args.SetData((Array)_argArray);
			Visible = num;
			_anchors = null;
			_states = null;
			if (num != 0)
			{
				int[] prefix = _cascades.Prefix;
				for (int i = 0; i <= 4; i++)
				{
					prefix[i] = Math.Min(prefix[i], num);
				}
				_cascades.Upload();
				ShadowCounts.Add(_args, 4, _cascades);
			}
		}
	}
	internal static class CargoCulling
	{
		public static bool Enabled = true;

		public static bool DistantShadows;

		private static readonly ConditionalWeakTable<CargoContainer, CargoTarget> Targets = new ConditionalWeakTable<CargoContainer, CargoTarget>();

		[HarmonyPatch(typeof(CargoContainer), "Free")]
		[HarmonyPostfix]
		private static void Free(CargoContainer __instance)
		{
			Release(__instance);
		}

		[HarmonyPatch(typeof(PlanetFactory), "UnloadDisplay")]
		[HarmonyPostfix]
		private static void UnloadDisplay(PlanetFactory __instance)
		{
			if (__instance.cargoContainer != null)
			{
				Release(__instance.cargoContainer);
			}
		}

		private static void Release(CargoContainer container)
		{
			if (Targets.TryGetValue(container, out CargoTarget value))
			{
				value.Release();
				Targets.Remove(container);
			}
		}

		[HarmonyPatch(typeof(CargoContainer), "Draw")]
		[HarmonyPrefix]
		private static bool Draw(CargoContainer __instance, Camera _cam)
		{
			if (!Enabled || (Object)(object)_cam == (Object)null || (Object)(object)_cam != (Object)(object)GameCamera.main || GameMain.localPlanet?.factory?.cargoContainer != __instance)
			{
				return true;
			}
			if (__instance.cargoCount <= 0)
			{
				return false;
			}
			CargoTarget value = Targets.GetValue(__instance, (CargoContainer key) => new CargoTarget(key));
			value.Draw(_cam);
			FrameCulling.Register(value);
			return false;
		}
	}
	internal sealed class CargoTarget : ICullTarget
	{
		private sealed class Batch
		{
			public ComputeBuffer? Buffer;

			public readonly ComputeBuffer Args = new ComputeBuffer(5, 4, (ComputeBufferType)256);

			public readonly uint[] ArgArray = new uint[5];

			public readonly MaterialPropertyBlock Props = new MaterialPropertyBlock();

			public Cargo[] Staging = (Cargo[])(object)new Cargo[1024];

			public int[] Counts = new int[4];

			public Cargo[] Packed = (Cargo[])(object)new Cargo[1024];

			public byte[] Cascade = new byte[1024];

			public int Total;

			public void Release()
			{
				ComputeBuffer? buffer = Buffer;
				if (buffer != null)
				{
					buffer.Release();
				}
				Buffer = null;
				Args.Release();
			}
		}

		private static readonly Bounds Everywhere = new Bounds(Vector3.zero, new Vector3(10000f, 10000f, 10000f));

		private static readonly int BufferId = Shader.PropertyToID("_Buffer");

		private const int ChunkSize = 16384;

		private readonly CargoContainer _container;

		private readonly Batch _near = new Batch();

		private readonly Batch _far = new Batch();

		private Cargo[] _pool;

		private int _cursor;

		private int _chunks;

		private View _view;

		private float _nearShadow2;

		private int _pending;

		private readonly CascadeCounts _cascades = new CascadeCounts();

		private readonly int[] _bucket = new int[5];

		public int LastDrawn { get; private set; } = -1;

		public bool Alive { get; private set; } = true;

		public int Visible { get; private set; }

		public int Total { get; private set; }

		public CargoTarget(CargoContainer container)
		{
			_container = container;
		}

		public void Release()
		{
			Alive = false;
			_near.Release();
			_far.Release();
			_cascades.Release();
		}

		public void Draw(Camera camera)
		{
			LastDrawn = Time.frameCount;
			CargoContainer container = _container;
			if ((Object)(object)container.cargoMatInst == (Object)null)
			{
				container.cargoMatInst = Object.Instantiate<Material>(Configs.builtin.cargoMat);
			}
			container.cargoMatInst.SetTexture("_MainTex", (Texture)(object)GameMain.iconSet.texture);
			container.cargoMatInst.SetBuffer("_IndexBuffer", GameMain.iconSet.itemIconIndexBuffer);
			Mesh cargoMesh = Configs.builtin.cargoMesh;
			Submit(_near, cargoMesh, (ShadowCastingMode)1, camera);
			Submit(_far, cargoMesh, (ShadowCastingMode)0, camera);
		}

		private void Submit(Batch b, Mesh mesh, ShadowCastingMode shadows, Camera camera)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			if (b.Buffer == null || b.Buffer.count < _container.poolCapacity)
			{
				ComputeBuffer? buffer = b.Buffer;
				if (buffer != null)
				{
					buffer.Release();
				}
				b.Buffer = new ComputeBuffer(_container.poolCapacity, 32, (ComputeBufferType)0);
				b.ArgArray[1] = 0u;
			}
			b.ArgArray[0] = mesh.GetIndexCount(0);
			b.Args.SetData((Array)b.ArgArray);
			b.Props.SetBuffer(BufferId, b.Buffer);
			Graphics.DrawMeshInstancedIndirect(mesh, 0, _container.cargoMatInst, Everywhere, b.Args, 0, b.Props, shadows, true, 0, camera, (LightProbeUsage)1);
		}

		public int Prepare(View view)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			_chunks = 0;
			Cargo[] cargoPool = _container.cargoPool;
			if (cargoPool == null || !Alive)
			{
				return 0;
			}
			_pool = cargoPool;
			_cursor = Math.Min(_container.cursor, cargoPool.Length);
			_view = view;
			float num = (CargoCulling.DistantShadows ? float.MaxValue : (QualitySettings.shadowDistance * QualitySettings.shadowCascade4Split.z));
			_nearShadow2 = num * num;
			_chunks = (_cursor + 16384 - 1) / 16384;
			Prepare(_near, cargoPool.Length);
			Prepare(_far, cargoPool.Length);
			if (_near.Cascade.Length < _cursor)
			{
				_near.Cascade = new byte[cargoPool.Length];
			}
			Total = _container.cargoCount;
			_pending = _chunks;
			return _chunks;
		}

		private void Prepare(Batch b, int capacity)
		{
			if (b.Staging.Length < _cursor)
			{
				b.Staging = (Cargo[])(object)new Cargo[capacity];
			}
			if (b.Packed.Length < _cursor)
			{
				b.Packed = (Cargo[])(object)new Cargo[capacity];
			}
			if (b.Counts.Length < _chunks)
			{
				b.Counts = new int[_chunks];
			}
		}

		public unsafe void Run(int k)
		{
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			int num = k * 16384;
			int num2 = Math.Min(_cursor, num + 16384);
			View view = _view;
			float nearShadow = _nearShadow2;
			int num3 = 0;
			int num4 = 0;
			fixed (Cargo* pool = _pool)
			{
				fixed (Cargo* staging = _near.Staging)
				{
					fixed (Cargo* staging2 = _far.Staging)
					{
						fixed (byte* cascade = _near.Cascade)
						{
							Cargo* ptr = (Cargo*)((byte*)staging + (nint)num * (nint)Unsafe.SizeOf<Cargo>());
							Cargo* ptr2 = (Cargo*)((byte*)staging2 + (nint)num * (nint)Unsafe.SizeOf<Cargo>());
							byte* ptr3 = cascade + num;
							Cargo* ptr4 = (Cargo*)((byte*)pool + (nint)num * (nint)Unsafe.SizeOf<Cargo>());
							for (Cargo* ptr5 = (Cargo*)((byte*)pool + (nint)num2 * (nint)Unsafe.SizeOf<Cargo>()); ptr4 < ptr5; ptr4 = (Cargo*)((byte*)ptr4 + Unsafe.SizeOf<Cargo>()))
							{
								if (((Cargo)ptr4).item == 0)
								{
									continue;
								}
								float x = ((Vector3)(&((Cargo)ptr4).position)).x;
								float y = ((Vector3)(&((Cargo)ptr4).position)).y;
								float z = ((Vector3)(&((Cargo)ptr4).position)).z;
								if (view.DistanceSquared(x, y, z) < nearShadow)
								{
									if (view.ContainsOrShadows(x, y, z))
									{
										ptr3[num3] = (byte)view.Cascades.First(x, y, z, 0.3f, 0.3f);
										Unsafe.Write((byte*)ptr + (nint)num3++ * (nint)Unsafe.SizeOf<Cargo>(), *ptr4);
									}
								}
								else if (view.Contains(x, y, z))
								{
									Unsafe.Write((byte*)ptr2 + (nint)num4++ * (nint)Unsafe.SizeOf<Cargo>(), *ptr4);
								}
							}
						}
					}
				}
			}
			_near.Counts[k] = num3;
			_far.Counts[k] = num4;
			if (Interlocked.Decrement(ref _pending) == 0)
			{
				Pack();
			}
		}

		private void Pack()
		{
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			Batch far = _far;
			int num = 0;
			for (int i = 0; i < _chunks; i++)
			{
				Array.Copy(far.Staging, i * 16384, far.Packed, num, far.Counts[i]);
				num += far.Counts[i];
			}
			far.Total = num;
			Batch near = _near;
			int[] bucket = _bucket;
			Array.Clear(bucket, 0, bucket.Length);
			for (int j = 0; j < _chunks; j++)
			{
				int k = j * 16384;
				for (int num2 = k + near.Counts[j]; k < num2; k++)
				{
					bucket[near.Cascade[k]]++;
				}
			}
			int[] prefix = _cascades.Prefix;
			int num3 = 0;
			for (int l = 0; l <= 4; l++)
			{
				int num4 = bucket[l];
				bucket[l] = num3;
				num3 = (prefix[l] = num3 + num4);
			}
			for (int m = 0; m < _chunks; m++)
			{
				int n = m * 16384;
				for (int num5 = n + near.Counts[m]; n < num5; n++)
				{
					near.Packed[bucket[near.Cascade[n]]++] = near.Staging[n];
				}
			}
			near.Total = num3;
		}

		public void Upload()
		{
			if (!Alive)
			{
				return;
			}
			int num = Upload(_near);
			Visible = num + Upload(_far);
			_pool = null;
			if (_chunks != 0 && _near.Buffer != null)
			{
				int[] prefix = _cascades.Prefix;
				for (int i = 0; i <= 4; i++)
				{
					prefix[i] = Math.Min(prefix[i], num);
				}
				_cascades.Upload();
				ShadowCounts.Add(_near.Args, 4, _cascades);
			}
		}

		private int Upload(Batch b)
		{
			if (b.Buffer == null)
			{
				return 0;
			}
			int num = ((_chunks != 0) ? Math.Min(b.Total, b.Buffer.count) : 0);
			if (num > 0)
			{
				b.Buffer.SetData((Array)b.Packed, 0, 0, num);
			}
			b.ArgArray[1] = (uint)num;
			b.Args.SetData((Array)b.ArgArray);
			return num;
		}
	}
	internal readonly struct Cascades
	{
		public const int Count = 4;

		public const int None = 4;

		private static readonly int[] SphereIds = new int[4]
		{
			Shader.PropertyToID("unity_ShadowSplitSpheres0"),
			Shader.PropertyToID("unity_ShadowSplitSpheres1"),
			Shader.PropertyToID("unity_ShadowSplitSpheres2"),
			Shader.PropertyToID("unity_ShadowSplitSpheres3")
		};

		private static readonly float[] Along = new float[4];

		private static readonly float[] Radius = new float[4];

		private static bool _observed;

		private static bool _posed;

		private static Vector3 _lastEye;

		private static Vector3 _lastForward;

		private static float _lastDistance;

		private readonly float _c0x;

		private readonly float _c0y;

		private readonly float _c0z;

		private readonly float _r0;

		private readonly float _c1x;

		private readonly float _c1y;

		private readonly float _c1z;

		private readonly float _r1;

		private readonly float _c2x;

		private readonly float _c2y;

		private readonly float _c2z;

		private readonly float _r2;

		private readonly float _c3x;

		private readonly float _c3y;

		private readonly float _c3z;

		private readonly float _r3;

		private readonly float _lx;

		private readonly float _ly;

		private readonly float _lz;

		private readonly float _ground;

		public readonly bool Valid;

		public Cascades(Camera camera, Vector3 light, float groundRadius, float slack, float turn)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			this = default(Cascades);
			if (!(light == Vector3.zero) && QualitySettings.shadowCascades == 4 && (int)QualitySettings.shadowProjection == 1 && !camera.orthographic && camera.projectionMatrix.m02 == 0f && camera.projectionMatrix.m12 == 0f)
			{
				Transform transform = ((Component)camera).transform;
				Vector3 position = transform.position;
				Vector3 forward = transform.forward;
				float fieldOfView = camera.fieldOfView;
				float aspect = camera.aspect;
				float num = Mathf.Min(QualitySettings.shadowDistance, camera.farClipPlane);
				Vector3 shadowCascade4Split = QualitySettings.shadowCascade4Split;
				float nearClipPlane = camera.nearClipPlane;
				float rad = turn * ((float)Math.PI / 180f);
				if (!_observed)
				{
					(_c0x, _c0y, _c0z, _r0) = Sphere(position, forward, fieldOfView, aspect, nearClipPlane, num * shadowCascade4Split.x, slack, turn, rad);
					(_c1x, _c1y, _c1z, _r1) = Sphere(position, forward, fieldOfView, aspect, num * shadowCascade4Split.x, num * shadowCascade4Split.y, slack, turn, rad);
					(_c2x, _c2y, _c2z, _r2) = Sphere(position, forward, fieldOfView, aspect, num * shadowCascade4Split.y, num * shadowCascade4Split.z, slack, turn, rad);
					(_c3x, _c3y, _c3z, _r3) = Sphere(position, forward, fieldOfView, aspect, num * shadowCascade4Split.z, num, slack, turn, rad);
				}
				else
				{
					float widen = Mathf.Tan(Mathf.Min(fieldOfView * 0.5f + turn, 89f) * ((float)Math.PI / 180f)) / Mathf.Tan(fieldOfView * 0.5f * ((float)Math.PI / 180f));
					(_c0x, _c0y, _c0z, _r0) = Observed(0, position, forward, num, slack, rad, widen);
					(_c1x, _c1y, _c1z, _r1) = Observed(1, position, forward, num, slack, rad, widen);
					(_c2x, _c2y, _c2z, _r2) = Observed(2, position, forward, num, slack, rad, widen);
					(_c3x, _c3y, _c3z, _r3) = Observed(3, position, forward, num, slack, rad, widen);
				}
				float x = light.x;
				float y = light.y;
				float z = light.z;
				_lx = x;
				_ly = y;
				_lz = z;
				_ground = groundRadius;
				Valid = true;
			}
		}

		public static void Observe(Camera camera)
		{
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)camera).transform;
			float num = Mathf.Min(QualitySettings.shadowDistance, camera.farClipPlane);
			Vector3 lastEye;
			if (_posed)
			{
				_observed = true;
				for (int i = 0; i < 4; i++)
				{
					if (!_observed)
					{
						break;
					}
					Vector4 globalVector = Shader.GetGlobalVector(SphereIds[i]);
					Vector3 val = new Vector3(globalVector.x, globalVector.y, globalVector.z) - _lastEye;
					float num2 = Vector3.Dot(val, _lastForward);
					int observed;
					if (globalVector.w > 0f)
					{
						lastEye = val - _lastForward * num2;
						observed = ((((Vector3)(ref lastEye)).sqrMagnitude < 0.01f) ? 1 : 0);
					}
					else
					{
						observed = 0;
					}
					_observed = (byte)observed != 0;
					Along[i] = num2 / _lastDistance;
					Radius[i] = Mathf.Sqrt(globalVector.w) / _lastDistance;
				}
			}
			lastEye = transform.position;
			Vector3 forward = transform.forward;
			float lastDistance = num;
			_lastEye = lastEye;
			_lastForward = forward;
			_lastDistance = lastDistance;
			_posed = true;
		}

		private static (float, float, float, float) Observed(int k, Vector3 eye, Vector3 fwd, float distance, float slack, float rad, float widen)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			float num = Along[k] * distance;
			float num2 = Radius[k] * distance * widen;
			num2 = num2 * 1.02f + 0.5f + slack + (num + num2) * rad;
			Vector3 val = eye + fwd * num;
			return (val.x, val.y, val.z, num2);
		}

		private static (float, float, float, float) Sphere(Vector3 eye, Vector3 fwd, float fov, float aspect, float near, float far, float slack, float turn, float rad)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			(float, float) tuple = SliceSphere(fov, aspect, near, far);
			float item = tuple.Item1;
			float item2 = tuple.Item2;
			(float, float) tuple2 = SliceSphere(Mathf.Min(fov + 2f * turn, 170f), aspect, near, far);
			float item3 = tuple2.Item1;
			float item4 = tuple2.Item2;
			float num = (item + item3) * 0.5f;
			float num2 = Mathf.Abs(item3 - item) * 0.5f + Mathf.Max(item2, item4);
			num2 = num2 * 1.5f + 5f + slack + (num + num2) * rad;
			Vector3 val = eye + fwd * num;
			return (val.x, val.y, val.z, num2);
		}

		private static (float, float) SliceSphere(float fov, float aspect, float near, float far)
		{
			float num = Mathf.Tan(fov * 0.5f * ((float)Math.PI / 180f));
			float num2 = num * aspect;
			float num3 = num * num + num2 * num2;
			float num4 = Mathf.Min((far + near) * (1f + num3) * 0.5f, far);
			float num5 = Mathf.Max(near * near * num3 + (num4 - near) * (num4 - near), far * far * num3 + (far - num4) * (far - num4));
			return (num4, Mathf.Sqrt(num5));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public int First(float x, float y, float z, float height, float radius)
		{
			if (!Valid)
			{
				return 0;
			}
			float num = height * 0.5f;
			float num2 = ((num > 0f) ? (num / Mathf.Sqrt(x * x + y * y + z * z)) : 0f);
			float num3 = x + x * num2;
			float num4 = y + y * num2;
			float num5 = z + z * num2;
			float num6 = num3 + x * num2;
			float num7 = num4 + y * num2;
			float num8 = num5 + z * num2;
			float num9 = num6 * _lx + num7 * _ly + num8 * _lz;
			float length = 0f;
			float num10 = num6 * num6 + num7 * num7 + num8 * num8 - _ground * _ground;
			if (num9 < 0f && num10 > 0f)
			{
				length = Mathf.Min(num10 / (0f - num9), 300f);
			}
			float num11 = radius + num;
			if (Reaches(_c0x, _c0y, _c0z, _r0 + num11, num3, num4, num5, length))
			{
				return 0;
			}
			if (Reaches(_c1x, _c1y, _c1z, _r1 + num11, num3, num4, num5, length))
			{
				return 1;
			}
			if (Reaches(_c2x, _c2y, _c2z, _r2 + num11, num3, num4, num5, length))
			{
				return 2;
			}
			if (Reaches(_c3x, _c3y, _c3z, _r3 + num11, num3, num4, num5, length))
			{
				return 3;
			}
			return 4;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool Reaches(float cx, float cy, float cz, float r, float x, float y, float z, float length)
		{
			float num = cx - x;
			float num2 = cy - y;
			float num3 = cz - z;
			float num4 = num * _lx + num2 * _ly + num3 * _lz;
			if (num4 < 0f)
			{
				num4 = 0f;
			}
			else if (num4 > length)
			{
				num4 = length;
			}
			float num5 = num - _lx * num4;
			num2 -= _ly * num4;
			num3 -= _lz * num4;
			return num5 * num5 + num2 * num2 + num3 * num3 <= r * r;
		}
	}
	internal sealed class CascadeCounts
	{
		public readonly ComputeBuffer[] Counters = (ComputeBuffer[])(object)new ComputeBuffer[5];

		private readonly int[] _set = new int[5];

		public readonly int[] Prefix = new int[5];

		public CascadeCounts()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			for (int i = 0; i <= 4; i++)
			{
				Counters[i] = new ComputeBuffer(1, 4, (ComputeBufferType)2);
				Counters[i].SetCounterValue(0u);
			}
		}

		public void Upload()
		{
			for (int i = 0; i <= 4; i++)
			{
				if (_set[i] != Prefix[i])
				{
					Counters[i].SetCounterValue((uint)Prefix[i]);
					_set[i] = Prefix[i];
				}
			}
		}

		public void Release()
		{
			ComputeBuffer[] counters = Counters;
			for (int i = 0; i < counters.Length; i++)
			{
				counters[i].Release();
			}
		}
	}
	internal static class ShadowCounts
	{
		public static bool Enabled;

		private static readonly CommandBuffer[] Before;

		private static readonly CommandBuffer After;

		private static readonly List<(ComputeBuffer args, int offset, CascadeCounts counts)> Sites;

		private static Light? _attached;

		static ShadowCounts()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			Enabled = true;
			Before = (CommandBuffer[])(object)new CommandBuffer[4];
			After = new CommandBuffer
			{
				name = "GeosPerformance shadow counts restore"
			};
			Sites = new List<(ComputeBuffer, int, CascadeCounts)>();
			for (int i = 0; i < 4; i++)
			{
				Before[i] = new CommandBuffer
				{
					name = $"GeosPerformance shadow counts {i}"
				};
			}
		}

		public static void Add(ComputeBuffer args, int offset, CascadeCounts counts)
		{
			if (Enabled && counts.Prefix[0] != counts.Prefix[4])
			{
				Sites.Add((args, offset, counts));
			}
		}

		public static void OnPreCull(Camera cam)
		{
			if ((Object)(object)cam != (Object)(object)GameCamera.main)
			{
				return;
			}
			Cascades.Observe(cam);
			CommandBuffer[] before = Before;
			for (int i = 0; i < before.Length; i++)
			{
				before[i].Clear();
			}
			After.Clear();
			foreach (var site in Sites)
			{
				ComputeBuffer item = site.args;
				int item2 = site.offset;
				CascadeCounts item3 = site.counts;
				int num = item3.Prefix[4];
				for (int j = 0; j < 4; j++)
				{
					if (item3.Prefix[j] != num)
					{
						Before[j].CopyCounterValue(item3.Counters[j], item, (uint)item2);
						num = item3.Prefix[j];
					}
				}
				After.CopyCounterValue(item3.Counters[4], item, (uint)item2);
			}
			Sites.Clear();
			UniverseSimulator universeSimulator = GameMain.universeSimulator;
			Attach((universeSimulator == null) ? null : universeSimulator.LocalStarSimulator()?.sunLight);
		}

		public static void OnPostRender(Camera cam)
		{
			if ((Object)(object)cam == (Object)(object)GameCamera.main)
			{
				Detach();
			}
		}

		private static void Attach(Light? sun)
		{
			if ((Object)(object)_attached == (Object)(object)sun)
			{
				return;
			}
			Detach();
			if (!((Object)(object)sun == (Object)null))
			{
				for (int i = 0; i < 4; i++)
				{
					sun.AddCommandBuffer((LightEvent)4, Before[i], (ShadowMapPass)(64 << i));
				}
				sun.AddCommandBuffer((LightEvent)5, After, (ShadowMapPass)512);
				_attached = sun;
			}
		}

		public static void Detach()
		{
			if (!((Object)(object)_attached == (Object)null))
			{
				CommandBuffer[] before = Before;
				foreach (CommandBuffer val in before)
				{
					_attached.RemoveCommandBuffer((LightEvent)4, val);
				}
				_attached.RemoveCommandBuffer((LightEvent)5, After);
				_attached = null;
			}
		}
	}
	internal static class EntityCulling
	{
		private sealed class Target
		{
			public ObjectRenderer Renderer;

			public float CullingRadius;

			public int Frame = -1;

			public int FirstChunk;

			public int ChunkCount;

			public readonly uint[][] Lists = new uint[4][];

			public int[] ChunkCounts = new int[4];

			public readonly int[] Counts = new int[4];

			public readonly bool[] Shadowless = new bool[4];

			public bool Shadows;

			public float Height;

			public float Radius;

			public bool Measured;

			public readonly byte[][] Cascade = new byte[4][];

			public readonly uint[][] Merged = new uint[4][];

			public readonly CascadeCounts?[] CascadeCounts = new CascadeCounts[4];
		}

		[HarmonyPatch]
		private static class RenderPatch
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				return RenderMethods;
			}

			private static void Prefix(ObjectRenderer __instance, Vector3 camPos, Vector3 camFwd, float camCullDot, float planetRadius, float cullingRadius)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				_current = null;
				if (Job.Count != 0 && Targets.TryGetValue(__instance, out Target value) && value.Frame == Time.frameCount && !(camPos != _eye) && !(camFwd != _fwd) && camCullDot == _cullDot && planetRadius == _radius && cullingRadius == value.CullingRadius)
				{
					_current = value;
				}
			}

			private static void Postfix()
			{
				_current = null;
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				foreach (CodeInstruction instruction in instructions)
				{
					if ((instruction.opcode == OpCodes.Callvirt || instruction.opcode == OpCodes.Call) && instruction.operand is MethodInfo key && Replacements.TryGetValue(key, out MethodInfo value))
					{
						instruction.opcode = OpCodes.Call;
						instruction.operand = value;
					}
					yield return instruction;
				}
			}
		}

		public static bool Enabled = true;

		private const int ChunkSize = 1024;

		private const int MaxLods = 4;

		private static readonly int LodMulId = Shader.PropertyToID("_Global_LOD_Culling_Mul");

		private static readonly ConditionalWeakTable<ObjectRenderer, Target> Targets = new ConditionalWeakTable<ObjectRenderer, Target>();

		private static readonly List<Target> Job = new List<Target>();

		private static readonly List<(Target target, int start, int end, int chunk)> Chunks = new List<(Target, int, int, int)>();

		private static Vector3 _eye;

		private static Vector3 _fwd;

		private static float _cullDot;

		private static float _radius;

		private static float _lodMul;

		private static Cascades _cascades;

		private static Target? _current;

		private static int _launched = -1;

		private static GPUInstancingManager? _launchedFor;

		private static Vector3 _lastEye;

		private static Quaternion _lastRot;

		private static float _lastFov;

		private static bool _posed;

		private static readonly int[] Bucket = new int[5];

		private static readonly Action<int> RunChunk = delegate(int i)
		{
			var (t, start, end, chunk) = Chunks[i];
			Cull(t, start, end, chunk);
		};

		private static readonly MethodBase[] RenderMethods = new MethodBase[5]
		{
			AccessTools.DeclaredMethod(typeof(ObjectRenderer), "Render", (Type[])null, (Type[])null),
			AccessTools.DeclaredMethod(typeof(InserterRenderer), "Render", (Type[])null, (Type[])null),
			AccessTools.DeclaredMethod(typeof(LabRenderer), "Render", (Type[])null, (Type[])null),
			AccessTools.DeclaredMethod(typeof(DynamicRenderer), "Render", (Type[])null, (Type[])null),
			AccessTools.DeclaredMethod(typeof(VegeRenderer), "Render", (Type[])null, (Type[])null)
		};

		private static readonly Dictionary<MethodInfo, MethodInfo> Replacements = new Dictionary<MethodInfo, MethodInfo>
		{
			[AccessTools.Method(typeof(ComputeShader), "Dispatch", new Type[4]
			{
				typeof(int),
				typeof(int),
				typeof(int),
				typeof(int)
			}, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "Dispatch", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(ComputeShader), "SetVector", new Type[2]
			{
				typeof(string),
				typeof(Vector4)
			}, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "SetVector", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(ComputeShader), "SetFloat", new Type[2]
			{
				typeof(string),
				typeof(float)
			}, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "SetFloat", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(ComputeShader), "SetInt", new Type[2]
			{
				typeof(string),
				typeof(int)
			}, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "SetInt", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(ComputeShader), "SetBuffer", new Type[3]
			{
				typeof(int),
				typeof(string),
				typeof(ComputeBuffer)
			}, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "SetBuffer", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(BatchRenderer), "Render", (Type[])null, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "RenderBatch", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(BatchRenderer), "SetAdditionalBuffer", new Type[2]
			{
				typeof(string),
				typeof(ComputeBuffer)
			}, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "SetAdditionalBufferByName", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(BatchRenderer), "SetAdditionalBuffer", new Type[2]
			{
				typeof(int),
				typeof(ComputeBuffer)
			}, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "SetAdditionalBufferById", (Type[])null, (Type[])null),
			[AccessTools.Method(typeof(BatchRenderer), "SetAdditionalFloat", (Type[])null, (Type[])null)] = AccessTools.Method(typeof(EntityCulling), "SetAdditionalFloat", (Type[])null, (Type[])null)
		};

		public static void Patch(Harmony harmony)
		{
			harmony.PatchAll(typeof(EntityCulling));
			harmony.CreateClassProcessor(typeof(RenderPatch)).Patch();
		}

		public static void BeginFrame()
		{
			GPUInstancingManager val = GameMain.localPlanet?.factoryModel?.gpuiManager;
			if (Enabled && ((val != null) ? val.activeFactory : null) != null)
			{
				Launch(val);
			}
		}

		[HarmonyPatch(typeof(GPUInstancingManager), "Render")]
		[HarmonyPrefix]
		private static void BeforeRender(GPUInstancingManager __instance)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled || __instance.activeFactory == null)
			{
				Workers.Wait(Workers.Entities);
				Job.Clear();
				Chunks.Clear();
				return;
			}
			if (_launched == Time.frameCount && _launchedFor == __instance)
			{
				(Vector3, Vector3, float, float, float) tuple = Inputs(__instance);
				Vector3 eye = _eye;
				Vector3 fwd = _fwd;
				float cullDot = _cullDot;
				float radius = _radius;
				float lodMul = _lodMul;
				if (!(tuple.Item1 != eye) && !(tuple.Item2 != fwd) && tuple.Item3 == cullDot && tuple.Item4 == radius && tuple.Item5 == lodMul)
				{
					return;
				}
			}
			Launch(__instance);
		}

		private static (Vector3, Vector3, float, float, float) Inputs(GPUInstancingManager gpui)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Camera main = GameCamera.main;
			float item = Mathf.Cos(Mathf.Atan(Mathf.Tan(main.fieldOfView * ((float)Math.PI / 180f) * 0.5f) * main.aspect * 1.05f));
			return (((Component)main).transform.position, ((Component)main).transform.forward, item, gpui.activePlanet.realRadius, Shader.GetGlobalFloat(LodMulId));
		}

		private static void Launch(GPUInstancingManager gpui)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Invalid comparison between Unknown and I4
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Invalid comparison between Unknown and I4
			Workers.Wait(Workers.Entities);
			Job.Clear();
			Chunks.Clear();
			PlanetData activePlanet = gpui.activePlanet;
			(Vector3, Vector3, float, float, float) tuple = Inputs(gpui);
			_eye = tuple.Item1;
			_fwd = tuple.Item2;
			_cullDot = tuple.Item3;
			_radius = tuple.Item4;
			_lodMul = tuple.Item5;
			Camera main = GameCamera.main;
			Quaternion rotation = ((Component)main).transform.rotation;
			float num = (_posed ? (Quaternion.Angle(_lastRot, rotation) + Mathf.Abs(main.fieldOfView - _lastFov)) : 0f);
			float num2;
			if (!_posed)
			{
				num2 = 0f;
			}
			else
			{
				Vector3 val = _eye - _lastEye;
				num2 = ((Vector3)(ref val)).magnitude;
			}
			float num3 = num2;
			Vector3 eye = _eye;
			Quaternion lastRot = rotation;
			float fieldOfView = main.fieldOfView;
			_lastEye = eye;
			_lastRot = lastRot;
			_lastFov = fieldOfView;
			_posed = true;
			_cascades = new Cascades(main, FrameCulling.LightDirection(), _radius - 5f, num3 * 1.5f + 1f, num * 1.5f + 2f);
			float cullingRadius = ((ProtoSet<ThemeProto>)(object)LDB.themes).Select(activePlanet.theme).CullingRadius;
			float num4 = (GameMain.data.gameDesc.isSandboxMode ? (cullingRadius - 10f) : cullingRadius);
			ObjectRenderer[] objectRenderers = gpui.objectRenderers;
			ObjectRenderer[] prebuildRenderers = gpui.prebuildRenderers;
			for (int i = 0; i < objectRenderers.Length; i++)
			{
				float cullingRadius2 = cullingRadius;
				ObjectRenderer val2 = objectRenderers[i];
				if (val2 != null)
				{
					EObjectType val3 = gpui.objectTypes[i];
					if ((int)val3 == 1 || (int)val3 == 2)
					{
						cullingRadius2 = num4;
					}
					Add(val2, cullingRadius2);
				}
				if (prebuildRenderers[i] != null)
				{
					Add(prebuildRenderers[i], cullingRadius2);
				}
			}
			_launched = Time.frameCount;
			_launchedFor = gpui;
			if (Chunks.Count > 0)
			{
				Workers.Begin(Workers.Entities, Chunks.Count, RunChunk);
			}
		}

		private static void Add(ObjectRenderer r, float cullingRadius)
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			if (r.instCursor <= 1 || r.lodBatches == null || r.objectDesc == null || r.objectDesc.lodCount == 0)
			{
				return;
			}
			Target value = Targets.GetValue(r, (ObjectRenderer key) => new Target
			{
				Renderer = key
			});
			value.CullingRadius = cullingRadius;
			value.Frame = Time.frameCount;
			int num = Math.Min(r.instCursor, r.instPool.Length);
			if (!value.Measured)
			{
				float num2 = r.objectDesc.cullingHeight;
				float num3 = 0f;
				for (int num4 = 0; num4 < r.objectDesc.lodCount; num4++)
				{
					Bounds bounds = r.objectDesc.lodMeshes[num4].bounds;
					num2 = Mathf.Max(num2, ((Bounds)(ref bounds)).max.y);
					num3 = Mathf.Max(num3, Mathf.Sqrt(Mathf.Max(((Bounds)(ref bounds)).min.x * ((Bounds)(ref bounds)).min.x, ((Bounds)(ref bounds)).max.x * ((Bounds)(ref bounds)).max.x) + Mathf.Max(((Bounds)(ref bounds)).min.z * ((Bounds)(ref bounds)).min.z, ((Bounds)(ref bounds)).max.z * ((Bounds)(ref bounds)).max.z)));
				}
				value.Height = num2;
				value.Radius = num3 + 1f;
				if (r is VegeRenderer)
				{
					value.Height *= 3f;
					value.Radius *= 3f;
				}
				else if (r is InserterRenderer)
				{
					value.Radius += 5f;
				}
				value.Measured = true;
			}
			value.Shadows = false;
			if (_cascades.Valid)
			{
				BatchRenderer[] lodBatches = r.lodBatches;
				foreach (BatchRenderer val in lodBatches)
				{
					value.Shadows |= val.castShadow > 0;
				}
			}
			for (int num6 = 0; num6 < Math.Min(r.objectDesc.lodCount, 4); num6++)
			{
				if (value.Lists[num6] == null || value.Lists[num6].Length < r.instPool.Length)
				{
					value.Lists[num6] = new uint[r.instPool.Length];
					value.Merged[num6] = new uint[r.instPool.Length];
					value.Cascade[num6] = new byte[r.instPool.Length];
				}
			}
			value.FirstChunk = Chunks.Count;
			value.ChunkCount = (num + 1024 - 1) / 1024;
			if (value.ChunkCounts.Length < value.ChunkCount * 4)
			{
				value.ChunkCounts = new int[value.ChunkCount * 4];
			}
			for (int num7 = 0; num7 < value.ChunkCount; num7++)
			{
				Chunks.Add((value, num7 * 1024, Math.Min(num, (num7 + 1) * 1024), num7));
			}
			Job.Add(value);
		}

		[HarmonyPatch(typeof(ObjectRenderer), "Free")]
		[HarmonyPostfix]
		private static void Free(ObjectRenderer __instance)
		{
			if (Targets.TryGetValue(__instance, out Target value))
			{
				CascadeCounts[] cascadeCounts = value.CascadeCounts;
				for (int i = 0; i < cascadeCounts.Length; i++)
				{
					cascadeCounts[i]?.Release();
				}
				Targets.Remove(__instance);
			}
		}

		[HarmonyPatch(typeof(GPUInstancingManager), "Render")]
		[HarmonyPostfix]
		private static void AfterRender()
		{
			Workers.Wait(Workers.Entities);
			Job.Clear();
			Chunks.Clear();
			_current = null;
		}

		private unsafe static void Cull(Target t, int start, int end, int chunk)
		{
			ObjectRenderer renderer = t.Renderer;
			PrefabDesc objectDesc = renderer.objectDesc;
			int num = Math.Min(objectDesc.lodCount, 4);
			float cullingHeight = objectDesc.cullingHeight;
			float x = _eye.x;
			float y = _eye.y;
			float z = _eye.z;
			float x2 = _fwd.x;
			float y2 = _fwd.y;
			float z2 = _fwd.z;
			float cullDot = _cullDot;
			float num2 = _radius + t.CullingRadius;
			float num3 = num2 * num2;
			float num4 = x * x + y * y + z * z;
			bool flag = num3 >= num4;
			float num5 = objectDesc.lodDistances[0] * objectDesc.lodDistances[0] * _lodMul;
			float num6 = ((num > 1) ? (objectDesc.lodDistances[1] * objectDesc.lodDistances[1] * _lodMul) : (-1f));
			float num7 = ((num > 2) ? (objectDesc.lodDistances[2] * objectDesc.lodDistances[2] * _lodMul) : (-1f));
			float num8 = ((num > 3) ? (objectDesc.lodDistances[3] * objectDesc.lodDistances[3] * _lodMul) : (-1f));
			int num9 = start;
			int num10 = start;
			int num11 = start;
			int num12 = start;
			uint[] array = t.Lists[0];
			uint[] array2 = ((num > 1) ? t.Lists[1] : array);
			uint[] array3 = ((num > 2) ? t.Lists[2] : array);
			uint[] array4 = ((num > 3) ? t.Lists[3] : array);
			byte[] array5 = t.Cascade[0];
			byte[] array6 = ((num > 1) ? t.Cascade[1] : array5);
			byte[] array7 = ((num > 2) ? t.Cascade[2] : array5);
			byte[] array8 = ((num > 3) ? t.Cascade[3] : array5);
			bool shadows = t.Shadows;
			Cascades cascades = _cascades;
			float height = t.Height;
			float radius = t.Radius;
			fixed (GPUOBJECT* instPool = renderer.instPool)
			{
				for (int i = start; i < end; i++)
				{
					GPUOBJECT* ptr = (GPUOBJECT*)((byte*)instPool + (nint)i * (nint)Unsafe.SizeOf<GPUOBJECT>());
					if (((GPUOBJECT)ptr).objId == 0)
					{
						continue;
					}
					float posx = ((GPUOBJECT)ptr).posx;
					float posy = ((GPUOBJECT)ptr).posy;
					float posz = ((GPUOBJECT)ptr).posz;
					float num13 = cullingHeight / Mathf.Sqrt(posx * posx + posy * posy + posz * posz);
					float num14 = posx * num13 + posx - x;
					float num15 = posy * num13 + posy - y;
					float num16 = posz * num13 + posz - z;
					float num17 = Mathf.Sqrt(num14 * num14 + num15 * num15 + num16 * num16);
					if (num17 >= 0.1f)
					{
						float num18 = 1f / num17;
						if (((num14 * x2 + num15 * y2 + num16 * z2) * num18 < cullDot - cullingHeight * num18 * 2f && num17 > 30f && (num17 > 70f || num17 > cullingHeight * 3f)) || flag)
						{
							continue;
						}
						float num19 = (0f - (num14 * x + num15 * y + num16 * z)) * num18;
						if (num19 > 0f && num2 >= num19 - num17)
						{
							float num20 = num3 - (num4 - num19 * num19);
							if (num20 >= 0f && num17 >= num19 - Mathf.Sqrt(num20))
							{
								continue;
							}
						}
					}
					float num21 = posx - x;
					float num22 = posy - y;
					float num23 = posz - z;
					float num24 = num21 * num21 + num22 * num22 + num23 * num23;
					if (!(num24 >= num5) || !(num24 >= num6) || !(num24 >= num7) || !(num24 >= num8))
					{
						byte b = (byte)(shadows ? ((byte)cascades.First(posx, posy, posz, height, radius)) : 0);
						if (num24 < num5)
						{
							array5[num9] = b;
							array[num9++] = (uint)i;
						}
						else if (num24 < num6)
						{
							array6[num10] = b;
							array2[num10++] = (uint)i;
						}
						else if (num24 < num7)
						{
							array7[num11] = b;
							array3[num11++] = (uint)i;
						}
						else
						{
							array8[num12] = b;
							array4[num12++] = (uint)i;
						}
					}
				}
			}
			int num25 = chunk * 4;
			t.ChunkCounts[num25] = num9 - start;
			t.ChunkCounts[num25 + 1] = num10 - start;
			t.ChunkCounts[num25 + 2] = num11 - start;
			t.ChunkCounts[num25 + 3] = num12 - start;
		}

		private static void SetVector(ComputeShader cs, string name, Vector4 value)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (_current == null)
			{
				cs.SetVector(name, value);
			}
		}

		private static void SetFloat(ComputeShader cs, string name, float value)
		{
			if (_current == null)
			{
				cs.SetFloat(name, value);
			}
		}

		private static void SetInt(ComputeShader cs, string name, int value)
		{
			if (_current == null)
			{
				cs.SetInt(name, value);
			}
		}

		private static void SetBuffer(ComputeShader cs, int kernel, string name, ComputeBuffer buffer)
		{
			if (_current == null)
			{
				cs.SetBuffer(kernel, name, buffer);
			}
		}

		private static void Dispatch(ComputeShader cs, int kernel, int x, int y, int z)
		{
			Target current = _current;
			if (current == null)
			{
				cs.Dispatch(kernel, x, y, z);
				return;
			}
			Workers.Wait(Workers.Entities);
			if (Workers.Entities.Error != null)
			{
				Plugin.Log.LogError((object)$"Culling failed and is now off: {Workers.Entities.Error}");
				Workers.Entities.Error = null;
				Plugin.DisableCulling();
			}
			BatchRenderer[] lodBatches = current.Renderer.lodBatches;
			for (int i = 0; i < lodBatches.Length && i < 4; i++)
			{
				BatchRenderer val = lodBatches[i];
				ComputeBuffer idBuffer = val.idBuffer;
				int val2 = Merge(current, i, val.castShadow > 0);
				val2 = Math.Min(val2, idBuffer.count);
				current.Counts[i] = val2;
				if (val2 > 0)
				{
					idBuffer.SetData((Array)current.Merged[i], 0, 0, val2);
				}
				idBuffer.SetCounterValue((uint)val2);
				current.Shadowless[i] = false;
				if (val2 != 0 && current.Shadows && val.castShadow > 0)
				{
					ref CascadeCounts reference = ref current.CascadeCounts[i];
					CascadeCounts cascadeCounts = reference ?? (reference = new CascadeCounts());
					current.Shadowless[i] = cascadeCounts.Prefix[3] == 0;
					for (int j = 0; j <= 4; j++)
					{
						cascadeCounts.Prefix[j] = Math.Min(cascadeCounts.Prefix[j], val2);
					}
					cascadeCounts.Upload();
					for (int k = 0; k < Math.Min(val.castShadow, val.subCount); k++)
					{
						ShadowCounts.Add(val.argBuffer, (val.argOffset + k * 5 + 1) * 4, cascadeCounts);
					}
				}
			}
		}

		private static int Merge(Target t, int lod, bool shadows)
		{
			uint[] array = t.Lists[lod];
			uint[] array2 = t.Merged[lod];
			if (!shadows || !t.Shadows)
			{
				int num = 0;
				for (int i = 0; i < t.ChunkCount; i++)
				{
					int num2 = t.ChunkCounts[i * 4 + lod];
					Array.Copy(array, i * 1024, array2, num, num2);
					num += num2;
				}
				return num;
			}
			byte[] array3 = t.Cascade[lod];
			int[] bucket = Bucket;
			Array.Clear(bucket, 0, bucket.Length);
			for (int j = 0; j < t.ChunkCount; j++)
			{
				int k = j * 1024;
				for (int num3 = k + t.ChunkCounts[j * 4 + lod]; k < num3; k++)
				{
					bucket[array3[k]]++;
				}
			}
			ref CascadeCounts reference = ref t.CascadeCounts[lod];
			CascadeCounts cascadeCounts = reference ?? (reference = new CascadeCounts());
			int num4 = 0;
			for (int l = 0; l <= 4; l++)
			{
				int num5 = bucket[l];
				bucket[l] = num4;
				num4 += num5;
				cascadeCounts.Prefix[l] = num4;
			}
			for (int m = 0; m < t.ChunkCount; m++)
			{
				int n = m * 1024;
				for (int num6 = n + t.ChunkCounts[m * 4 + lod]; n < num6; n++)
				{
					array2[bucket[array3[n]]++] = array[n];
				}
			}
			return num4;
		}

		private static bool Empty(BatchRenderer b)
		{
			if (_current != null && b.lod < 4)
			{
				return _current.Counts[b.lod] == 0;
			}
			return false;
		}

		private static void RenderBatch(BatchRenderer b)
		{
			if (!Empty(b))
			{
				if (_current == null || b.lod >= 4 || !_current.Shadowless[b.lod])
				{
					b.Render();
					return;
				}
				int castShadow = b.castShadow;
				b.castShadow = 0;
				b.Render();
				b.castShadow = castShadow;
			}
		}

		private static void SetAdditionalBufferByName(BatchRenderer b, string name, ComputeBuffer buffer)
		{
			if (!Empty(b))
			{
				b.SetAdditionalBuffer(name, buffer);
			}
		}

		private static void SetAdditionalBufferById(BatchRenderer b, int id, ComputeBuffer buffer)
		{
			if (!Empty(b))
			{
				b.SetAdditionalBuffer(id, buffer);
			}
		}

		private static void SetAdditionalFloat(BatchRenderer b, string name, float value)
		{
			if (!Empty(b))
			{
				b.SetAdditionalFloat(name, value);
			}
		}
	}
	internal interface ICullTarget
	{
		int LastDrawn { get; }

		bool Alive { get; }

		int Visible { get; }

		int Total { get; }

		int Prepare(View view);

		void Run(int chunk);

		void Upload();
	}
	internal static class FrameCulling
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static CameraCallback <0>__OnPreCull;

			public static CameraCallback <1>__OnPreCull;

			public static CameraCallback <2>__OnPostRender;
		}

		private static readonly List<ICullTarget> Targets = new List<ICullTarget>();

		private static readonly List<ICullTarget> Job = new List<ICullTarget>();

		private static readonly List<ICullTarget> Late = new List<ICullTarget>();

		private static int[] _starts = new int[16];

		private static int _jobFrame = -1;

		private static bool _haveView;

		private static View _next;

		private static bool _prevValid;

		private static Quaternion _baseRot;

		private static Vector3 _baseEye;

		private static float _baseFov;

		private static float _baseAspect;

		private static float _widen;

		private static float _slack;

		private static ManualLogSource _log = null;

		public static readonly Stats Stats = new Stats();

		private static readonly Action<int> RunChunk = delegate(int chunk)
		{
			int num = Job.Count - 1;
			while (_starts[num] > chunk)
			{
				num--;
			}
			Job[num].Run(chunk - _starts[num]);
		};

		public static void Install(ManualLogSource log)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			_log = log;
			CameraCallback onPreCull = Camera.onPreCull;
			object obj = <>O.<0>__OnPreCull;
			if (obj == null)
			{
				CameraCallback val = OnPreCull;
				<>O.<0>__OnPreCull = val;
				obj = (object)val;
			}
			Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)onPreCull, (Delegate?)obj);
			CameraCallback onPreCull2 = Camera.onPreCull;
			object obj2 = <>O.<1>__OnPreCull;
			if (obj2 == null)
			{
				CameraCallback val2 = ShadowCounts.OnPreCull;
				<>O.<1>__OnPreCull = val2;
				obj2 = (object)val2;
			}
			Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)onPreCull2, (Delegate?)obj2);
			CameraCallback onPostRender = Camera.onPostRender;
			object obj3 = <>O.<2>__OnPostRender;
			if (obj3 == null)
			{
				CameraCallback val3 = ShadowCounts.OnPostRender;
				<>O.<2>__OnPostRender = val3;
				obj3 = (object)val3;
			}
			Camera.onPostRender = (CameraCallback)Delegate.Combine((Delegate?)(object)onPostRender, (Delegate?)obj3);
		}

		public static void Uninstall()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			CameraCallback onPreCull = Camera.onPreCull;
			object obj = <>O.<0>__OnPreCull;
			if (obj == null)
			{
				CameraCallback val = OnPreCull;
				<>O.<0>__OnPreCull = val;
				obj = (object)val;
			}
			Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)onPreCull, (Delegate?)obj);
			CameraCallback onPreCull2 = Camera.onPreCull;
			object obj2 = <>O.<1>__OnPreCull;
			if (obj2 == null)
			{
				CameraCallback val2 = ShadowCounts.OnPreCull;
				<>O.<1>__OnPreCull = val2;
				obj2 = (object)val2;
			}
			Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)onPreCull2, (Delegate?)obj2);
			CameraCallback onPostRender = Camera.onPostRender;
			object obj3 = <>O.<2>__OnPostRender;
			if (obj3 == null)
			{
				CameraCallback val3 = ShadowCounts.OnPostRender;
				<>O.<2>__OnPostRender = val3;
				obj3 = (object)val3;
			}
			Camera.onPostRender = (CameraCallback)Delegate.Remove((Delegate?)(object)onPostRender, (Delegate?)obj3);
			ShadowCounts.Detach();
			Workers.Stop();
			Targets.Clear();
			Job.Clear();
			Late.Clear();
			_haveView = (_prevValid = false);
		}

		public static void Register(ICullTarget target)
		{
			if (!Targets.Contains(target))
			{
				Targets.Add(target);
			}
		}

		public static void BeginFrame()
		{
			if (!_haveView)
			{
				return;
			}
			long timestamp = Stopwatch.GetTimestamp();
			Workers.Wait(Workers.Frame);
			for (int num = Targets.Count - 1; num >= 0; num--)
			{
				ICullTarget cullTarget = Targets[num];
				if (!cullTarget.Alive || cullTarget.LastDrawn < Time.frameCount - 2)
				{
					Targets.RemoveAt(num);
				}
			}
			if (Launch(Targets, _next))
			{
				_jobFrame = Time.frameCount;
			}
			Stats.Main(timestamp);
		}

		[HarmonyPatch(typeof(GameMain), "FixedUpdate")]
		[HarmonyPrefix]
		private static void BeforeSimulation()
		{
			Workers.Wait(Workers.Frame);
			Workers.Wait(Workers.Entities);
		}

		private static bool Launch(List<ICullTarget> targets, View view)
		{
			Job.Clear();
			int num = 0;
			foreach (ICullTarget target in targets)
			{
				int num2 = target.Prepare(view);
				if (num2 != 0)
				{
					if (_starts.Length <= Job.Count)
					{
						Array.Resize(ref _starts, Job.Count * 2);
					}
					_starts[Job.Count] = num;
					Job.Add(target);
					num += num2;
				}
			}
			if (num == 0)
			{
				return false;
			}
			Workers.Begin(Workers.Frame, num, RunChunk);
			return true;
		}

		private static void OnPreCull(Camera cam)
		{
			//IL_00cf: 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_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)cam != (Object)(object)GameCamera.main || GameMain.localPlanet == null || Targets.Count == 0)
			{
				return;
			}
			long timestamp = Stopwatch.GetTimestamp();
			bool flag = _jobFrame == Time.frameCount;
			if (flag)
			{
				Workers.Wait(Workers.Frame);
				Stats.Wait(timestamp);
				if (!Covers(cam))
				{
					flag = false;
					Stats.Miss();
				}
			}
			float realRadius = GameMain.localPlanet.realRadius;
			Late.Clear();
			foreach (ICullTarget target in Targets)
			{
				if (!flag || !Job.Contains(target))
				{
					Late.Add(target);
				}
			}
			if (Late.Count > 0)
			{
				Vector3 light = LightDirection();
				if (Launch(view: new View(cam.projectionMatrix * cam.worldToCameraMatrix, ((Component)cam).transform.position, realRadius, 0f, light, new Cascades(cam, light, realRadius - 5f, 0f, 0f)), targets: Late))
				{
					Workers.Wait(Workers.Frame);
				}
			}
			if (Workers.Frame.Error != null)
			{
				_log.LogError((object)$"Culling failed and is now off: {Workers.Frame.Error}");
				Workers.Frame.Error = null;
				Plugin.DisableCulling();
				return;
			}
			int num = 0;
			int num2 = 0;
			foreach (ICullTarget target2 in Targets)
			{
				target2.Upload();
				num += target2.Visible;
				num2 += target2.Total;
			}
			_next = Predict(cam, realRadius);
			_haveView = true;
			Stats.Main(timestamp);
			Stats.Frame(num, num2);
		}

		private static bool Covers(Camera cam)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)cam).transform;
			if (Quaternion.Angle(_baseRot, transform.rotation) + Mathf.Abs(cam.fieldOfView - _baseFov) <= _widen)
			{
				Vector3 val = transform.position - _baseEye;
				if (((Vector3)(ref val)).magnitude <= _slack && Mathf.Approximately(cam.aspect, _baseAspect))
				{
					return cam.projectionMatrix.m02 == 0f;
				}
			}
			return false;
		}

		private static View Predict(Camera cam, float radius)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)cam).transform;
			Quaternion rotation = transform.rotation;
			Vector3 position = transform.position;
			float fieldOfView = cam.fieldOfView;
			float num = (_prevValid ? (Quaternion.Angle(_baseRot, rotation) + Mathf.Abs(fieldOfView - _baseFov)) : 0f);
			float num2;
			Vector3 baseEye;
			if (!_prevValid)
			{
				num2 = 0f;
			}
			else
			{
				baseEye = position - _baseEye;
				num2 = ((Vector3)(ref baseEye)).magnitude;
			}
			_widen = num * 1.5f + 2f;
			_slack = num2 * 1.5f + 1f;
			baseEye = position;
			float baseFov = fieldOfView;
			float aspect = cam.aspect;
			_baseRot = rotation;
			_baseEye = baseEye;
			_baseFov = baseFov;
			_baseAspect = aspect;
			_prevValid = true;
			float num3 = Mathf.Atan(Mathf.Tan(fieldOfView * 0.5f * ((float)Math.PI / 180f)) * cam.aspect) * 57.29578f;
			_widen = Mathf.Min(new float[3]
			{
				_widen,
				89f - fieldOfView * 0.5f,
				89f - num3
			});
			float num4 = fieldOfView * 0.5f + _widen;
			float num5 = Mathf.Tan((num3 + _widen) * ((float)Math.PI / 180f)) / Mathf.Tan(num4 * ((float)Math.PI / 180f));
			Matrix4x4 val = Matrix4x4.Perspective(num4 * 2f, num5, cam.nearClipPlane, cam.farClipPlane);
			Vector3 light = LightDirection();
			return new View(val * cam.worldToCameraMatrix, position, radius, _slack, light, new Cascades(cam, light, radius - 5f, _slack, _widen));
		}

		internal static Vector3 LightDirection()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			UniverseSimulator universeSimulator = GameMain.universeSimulator;
			Light val = ((universeSimulator == null) ? null : universeSimulator.LocalStarSimulator()?.sunLight);
			if (!((Object)(object)val != (Object)null) || !((Behaviour)val).isActiveAndEnabled || (int)val.shadows == 0 || (int)QualitySettings.shadows == 0)
			{
				return Vector3.zero;
			}
			return ((Component)val).transform.forward;
		}
	}
	internal sealed class Stats
	{
		private long _mainTicks;

		private long _waitTicks;

		private long _frames;

		private long _misses;

		private long _visible;

		private long _total;

		public void Miss()
		{
			_misses++;
		}

		public void Main(long start)
		{
			_mainTicks += Stopwatch.GetTimestamp() - start;
		}

		public void Wait(long start)
		{
			_waitTicks += Stopwatch.GetTimestamp() - start;
		}

		public void Frame(int visible, int total)
		{
			_frames++;
			_visible += visible;
			_total += total;
		}

		public void Reset()
		{
			_mainTicks = (_waitTicks = (_frames = (_misses = (_visible = (_total = 0L)))));
		}

		public override string ToString()
		{
			if (_frames != 0L)
			{
				return $"culling main_ms={(double)_mainTicks * 1000.0 / (double)Stopwatch.Frequency / (double)_frames:F3} wait_ms={(double)_waitTicks * 1000.0 / (double)Stopwatch.Frequency / (double)_frames:F3} visible={_visible / _frames} total={_total / _frames} recull={(double)_misses * 100.0 / (double)_frames:F1}%";
			}
			return "culling none";
		}
	}
	internal static class Picking
	{
		public static bool Enabled = true;

		[HarmonyPatch(typeof(Phys), "RayCastOBB")]
		[HarmonyPrefix]
		private static bool RayCastOBB(Vector3 origin, Vector3 dir, float length, Vector3 extents, Vector3 center, out RCHCPU rch, ref bool __result)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			rch = default(RCHCPU);
			if (!Enabled)
			{
				return true;
			}
			Vector3 val = dir;
			Vector3 val2 = center - origin;
			float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
			if (sqrMagnitude <= 0f)
			{
				return true;
			}
			float num = Mathf.Clamp(Vector3.Dot(val2, val) / sqrMagnitude, 0f, length);
			Vector3 val3 = val2 - val * num;
			if (((Vector3)(ref val3)).sqrMagnitude <= Vector3.Dot(extents, extents) * 1.001f + 0.0001f)
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	[BepInPlugin("com.geostyx.dsp.geosperformance", "GeosPerformance", "0.1.0")]
	[DefaultExecutionOrder(31000)]
	public class Plugin : BaseUnityPlugin
	{
		private static ConfigEntry<bool> _cullCargo;

		private static ConfigEntry<bool> _cullBelts;

		private static ConfigEntry<bool> _distantItemShadows;

		private static bool _failed;

		internal static ManualLogSource Log;

		private Harmony? _harmony;

		private void Awake()
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			_cullCargo = ((BaseUnityPlugin)this).Config.Bind<bool>("Rendering", "CullCargo", true, "Draw only the items on belts that the camera can see.");
			_cullBelts = ((BaseUnityPlugin)this).Config.Bind<bool>("Rendering", "CullBelts", true, "Draw only the belts that the camera can see.");
			_distantItemShadows = ((BaseUnityPlugin)this).Config.Bind<bool>("Rendering", "DistantItemShadows", false, "Draw shadows of items on belts more than about 120 m away. Their shadows are a few pixels across, and drawing them costs about 10 fps in a large factory.");
			_cullCargo.SettingChanged += delegate
			{
				ApplySettings();
			};
			_cullBelts.SettingChanged += delegate
			{
				ApplySettings();
			};
			_distantItemShadows.SettingChanged += delegate
			{
				ApplySettings();
			};
			ApplySettings();
			_harmony = new Harmony("com.geostyx.dsp.geosperformance");
			try
			{
				_harmony.PatchAll(typeof(CargoCulling));
				_harmony.PatchAll(typeof(BeltCulling));
				_harmony.PatchAll(typeof(FrameCulling));
				_harmony.PatchAll(typeof(Picking));
				_harmony.PatchAll(typeof(AnimUploads));
				EntityCulling.Patch(_harmony);
				FrameCulling.Install(((BaseUnityPlugin)this).Logger);
			}
			catch
			{
				FrameCulling.Uninstall();
				_harmony.UnpatchSelf();
				_harmony = null;
				throw;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"GeosPerformance 0.1.0 loaded");
		}

		private static void ApplySettings()
		{
			CargoCulling.Enabled = _cullCargo.Value && !_failed;
			BeltCulling.Enabled = _cullBelts.Value && !_failed;
			EntityCulling.Enabled = !_failed;
			CargoCulling.DistantShadows = _distantItemShadows.Value;
		}

		internal static void DisableCulling()
		{
			_failed = true;
			CargoCulling.Enabled = false;
			BeltCulling.Enabled = false;
			EntityCulling.Enabled = false;
		}

		private void Update()
		{
			Workers.BeginBatch();
			try
			{
				EntityCulling.BeginFrame();
				FrameCulling.BeginFrame();
			}
			finally
			{
				Workers.EndBatch();
			}
		}

		private void OnDestroy()
		{
			FrameCulling.Uninstall();
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_harmony = null;
		}
	}
	internal readonly struct View
	{
		private const float FrustumMargin = 4f;

		private const float OccluderInset = 5f;

		private static readonly Plane[] Planes = (Plane[])(object)new Plane[6];

		private readonly float _n0x;

		private readonly float _n0y;

		private readonly float _n0z;

		private readonly float _d0;

		private readonly float _n1x;

		private readonly float _n1y;

		private readonly float _n1z;

		private readonly float _d1;

		private readonly float _n2x;

		private readonly float _n2y;

		private readonly float _n2z;

		private readonly float _d2;

		private readonly float _n3x;

		private readonly float _n3y;

		private readonly float _n3z;

		private readonly float _d3;

		private readonly float _ex;

		private readonly float _ey;

		private readonly float _ez;

		private readonly float _k;

		private readonly float _eye2;

		private readonly float _occluder;

		private readonly bool _horizon;

		private readonly float _lx;

		private readonly float _ly;

		private readonly float _lz;

		private readonly float _ground;

		private readonly bool _shadows;

		private readonly float _q0;

		private readonly float _q1;

		private readonly float _q2;

		private readonly float _q3;

		public readonly Cascades Cascades;

		internal const float MaxShadowLength = 300f;

		public View(Matrix4x4 worldToProjection, Vector3 eye, float planetRadius, float slack, Vector3 light, Cascades cascades)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			Cascades = cascades;
			GeometryUtility.CalculateFrustumPlanes(worldToProjection, Planes);
			float num = 4f + slack;
			float x = ((Plane)(ref Planes[0])).normal.x;
			float y = ((Plane)(ref Planes[0])).normal.y;
			float z = ((Plane)(ref Planes[0])).normal.z;
			float d = ((Plane)(ref Planes[0])).distance + num;
			_n0x = x;
			_n0y = y;
			_n0z = z;
			_d0 = d;
			d = ((Plane)(ref Planes[1])).normal.x;
			z = ((Plane)(ref Planes[1])).normal.y;
			y = ((Plane)(ref Planes[1])).normal.z;
			x = ((Plane)(ref Planes[1])).distance + num;
			_n1x = d;
			_n1y = z;
			_n1z = y;
			_d1 = x;
			x = ((Plane)(ref Planes[2])).normal.x;
			y = ((Plane)(ref Planes[2])).normal.y;
			z = ((Plane)(ref Planes[2])).normal.z;
			d = ((Plane)(ref Planes[2])).distance + num;
			_n2x = x;
			_n2y = y;
			_n2z = z;
			_d2 = d;
			d = ((Plane)(ref Planes[3])).normal.x;
			z = ((Plane)(ref Planes[3])).normal.y;
			y = ((Plane)(ref Planes[3])).normal.z;
			x = ((Plane)(ref Planes[3])).distance + num;
			_n3x = d;
			_n3y = z;
			_n3z = y;
			_d3 = x;
			x = eye.x;
			y = eye.y;
			z = eye.z;
			_ex = x;
			_ey = y;
			_ez = z;
			float num2 = Mathf.Max(0f, planetRadius - 5f - slack);
			_eye2 = ((Vector3)(ref eye)).sqrMagnitude;
			_occluder = num2;
			_k = _eye2 - num2 * num2;
			_horizon = _k > 0f;
			z = light.x;
			y = light.y;
			x = light.z;
			_lx = z;
			_ly = y;
			_lz = x;
			_shadows = light != Vector3.zero;
			_ground = planetRadius - 5f;
			_q0 = Mathf.Max(0f, _n0x * _lx + _n0y * _ly + _n0z * _lz);
			_q1 = Mathf.Max(0f, _n1x * _lx + _n1y * _ly + _n1z * _lz);
			_q2 = Mathf.Max(0f, _n2x * _lx + _n2y * _ly + _n2z * _lz);
			_q3 = Mathf.Max(0f, _n3x * _lx + _n3y * _ly + _n3z * _lz);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool Contains(float x, float y, float z)
		{
			if (_n0x * x + _n0y * y + _n0z * z + _d0 < 0f)
			{
				return false;
			}
			if (_n1x * x + _n1y * y + _n1z * z + _d1 < 0f)
			{
				return false;
			}
			if (_n2x * x + _n2y * y + _n2z * z + _d2 < 0f)
			{
				return false;
			}
			if (_n3x * x + _n3y * y + _n3z * z + _d3 < 0f)
			{
				return false;
			}
			return !BehindHorizon(x, y, z);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool BehindHorizon(float x, float y, float z)
		{
			return BehindHorizon(x, y, z, _k);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool BehindHorizon(float x, float y, float z, float k)
		{
			if (!_horizon || k <= 0f)
			{
				return false;
			}
			float num = x - _ex;
			float num2 = y - _ey;
			float num3 = z - _ez;
			float num4 = 0f - (num * _ex + num2 * _ey + num3 * _ez);
			if (num4 > k)
			{
				return num4 * num4 > k * (num * num + num2 * num2 + num3 * num3);
			}
			return false;
		}

		public bool ContainsOrShadows(float x, float y, float z, float radius = 0f, float top2 = 0f)
		{
			float num = _n0x * x + _n0y * y + _n0z * z + _d0 + radius;
			float num2 = _n1x * x + _n1y * y + _n1z * z + _d1 + radius;
			float num3 = _n2x * x + _n2y * y + _n2z * z + _d2 + radius;
			float num4 = _n3x * x + _n3y * y + _n3z * z + _d3 + radius;
			float k = _k;
			if (radius > 0f)
			{
				float num5 = _occluder - radius;
				k = ((num5 > 0f) ? (_eye2 - num5 * num5) : 0f);
			}
			if (num >= 0f && num2 >= 0f && num3 >= 0f && num4 >= 0f && !BehindHorizon(x, y, z, k))
			{
				return true;
			}
			if (!_shadows)
			{
				return false;
			}
			float num6 = x * _lx + y * _ly + z * _lz;
			if (num6 >= 0f)
			{
				return false;
			}
			float num7 = top2;
			if (num7 <= 0f)
			{
				num7 = x * x + y * y + z * z;
				if (radius > 0f)
				{
					float num8 = Mathf.Sqrt(num7) + radius;
					num7 = num8 * num8;
				}
			}
			float num9 = num7 - _ground * _ground;
			if (num9 <= 0f)
			{
				return false;
			}
			float num10 = Mathf.Min(num9 / (0f - num6), 300f);
			if (num + _q0 * num10 < 0f || num2 + _q1 * num10 < 0f || num3 + _q2 * num10 < 0f || num4 + _q3 * num10 < 0f)
			{
				return false;
			}
			float num11 = num6 * num6 - num9;
			float num12 = ((num11 >= 0f) ? Mathf.Min(0f - num6 - Mathf.Sqrt(num11), 300f) : 300f);
			float t = 0f;
			float t2 = num12;
			if (!Clip(_n0x, _n0y, _n0z, num, ref t, ref t2))
			{
				return false;
			}
			if (!Clip(_n1x, _n1y, _n1z, num2, ref t, ref t2))
			{
				return false;
			}
			if (!Clip(_n2x, _n2y, _n2z, num3, ref t, ref t2))
			{
				return false;
			}
			if (!Clip(_n3x, _n3y, _n3z, num4, ref t, ref t2))
			{
				return false;
			}
			if (BehindHorizon(x + _lx * t, y + _ly * t, z + _lz * t, k))
			{
				return !BehindHorizon(x + _lx * t2, y + _ly * t2, z + _lz * t2, k);
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool Clip(float nx, float ny, float nz, float start, ref float t0, ref float t1)
		{
			float num = nx * _lx + ny * _ly + nz * _lz;
			if (num == 0f)
			{
				return start >= 0f;
			}
			float num2 = (0f - start) / num;
			if (num > 0f)
			{
				if (num2 > t0)
				{
					t0 = num2;
				}
			}
			else if (num2 < t1)
			{
				t1 = num2;
			}
			return t0 <= t1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public float DistanceSquared(float x, float y, float z)
		{
			return (x - _ex) * (x - _ex) + (y - _ey) * (y - _ey) + (z - _ez) * (z - _ez);
		}
	}
	internal sealed class WorkerJob
	{
		internal Action<int> Body;

		internal int Remaining;

		internal bool Running;

		internal long State;

		private long _run;

		public Exception? Error;

		internal bool Drain()
		{
			bool result = false;
			while (true)
			{
				long num = Volatile.Read(in State);
				int num2 = (int)(num & 0xFFFFFF);
				int num3 = (int)((num >> 24) & 0xFFFFFF);
				if (num2 >= num3)
				{
					break;
				}
				if (Interlocked.CompareExchange(ref State, num + 1, num) == num)
				{
					result = true;
					try
					{
						Body(num2);
					}
					catch (Exception value)
					{
						Interlocked.CompareExchange(ref Error, value, null);
					}
					Interlocked.Decrement(ref Remaining);
				}
			}
			return result;
		}

		internal void Open(int chunks)
		{
			_run = (_run + 1) & 0xFFFF;
			Volatile.Write(ref State, (_run << 48) | ((long)chunks << 24));
		}
	}
	internal static class Workers
	{
		public static readonly int Count = Math.Max(1, Math.Min(8, Environment.ProcessorCount / 3));

		public static readonly WorkerJob Frame = new WorkerJob();

		public static readonly WorkerJob Entities = new WorkerJob();

		private static readonly WorkerJob[] Jobs = new WorkerJob[2] { Entities, Frame };

		private static readonly SemaphoreSlim Wake = new SemaphoreSlim(0);

		private static Thread[]? _threads;

		private static volatile bool _stopping;

		private static bool _batching;

		private static int _pendingWakes;

		public static void Begin(WorkerJob job, int chunks, Action<int> body)
		{
			Wait(job);
			Start();
			job.Body = body;
			Volatile.Write(ref job.Remaining, chunks);
			job.Running = true;
			job.Open(chunks);
			if (_batching)
			{
				_pendingWakes += chunks;
			}
			else
			{
				Wake.Release(Math.Min(Count, chunks));
			}
		}

		public static void BeginBatch()
		{
			_batching = true;
		}

		public static void EndBatch()
		{
			_batch