using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ItemDockFix;
internal static class DockLayout
{
private const float MinCellMPX = 15f;
private const float IdealCellMPX = 18f;
private const float SideMarginMPX = 6f;
private const float MinBottomMarginMPX = 2f;
private const int MaxItemsPerRow = 32;
private const int MaxRowsPerPage = 8;
private static readonly Vector3 ParkedPosition = new Vector3(-5000f, -5000f, 0f);
internal static int CurrentPage;
private static string lastLayoutLog;
private static bool loggedFallback;
internal static int RowsPerPageValue => Mathf.Clamp((Plugin.RowsPerPage != null) ? Plugin.RowsPerPage.Value : 3, 1, 8);
internal static int ResolvePerRow(MinimapUIController ui)
{
int num = ((Plugin.ItemsPerRow != null) ? Plugin.ItemsPerRow.Value : 0);
num = Mathf.Clamp(num, 0, 32);
float num2 = BarWidthMPX(ui);
if (num2 <= 0f)
{
if (num <= 0)
{
return 12;
}
return num;
}
float num3 = num2 - 12f;
int num4 = Mathf.Max(1, Mathf.FloorToInt(num3 / 18f));
if (num > 0)
{
return Mathf.Min(num, num4);
}
return num4;
}
internal static float PitchMPX(MinimapUIController ui)
{
int num = Mathf.Max(1, ResolvePerRow(ui));
float num2 = BarWidthMPX(ui);
if (num2 <= 0f)
{
return 18f;
}
float num3 = Mathf.Max((float)num, num2 - 12f);
float num4 = num3 / (float)num;
if (num4 < 15f)
{
num4 = 15f;
}
if (float.IsNaN(num4) || float.IsInfinity(num4) || num4 <= 0f)
{
return 15f;
}
return num4;
}
internal static int EffectiveRows(MinimapUIController ui)
{
int rowsPerPageValue = RowsPerPageValue;
float num = CellWorldSize((dfControl)(object)(((Object)(object)ui != (Object)null) ? ui.DockPanel : null));
if (num <= 0f)
{
return rowsPerPageValue;
}
float num2 = PanelHeightWorld(ui);
if (num2 <= 0f)
{
return rowsPerPageValue;
}
float num3 = PitchMPX(ui) * num;
if (num3 <= 0f || float.IsNaN(num3) || float.IsInfinity(num3))
{
return rowsPerPageValue;
}
int num4 = Mathf.FloorToInt((num2 - 2f * num) / num3);
if (num4 < 1)
{
num4 = 1;
}
return Mathf.Clamp(rowsPerPageValue, 1, Mathf.Min(8, num4));
}
internal static int Capacity(MinimapUIController ui)
{
return Mathf.Max(1, ResolvePerRow(ui) * EffectiveRows(ui));
}
internal static int PageCountFor(MinimapUIController ui, int count)
{
int num = Capacity(ui);
return Mathf.Max(1, (count + num - 1) / num);
}
internal static int PageStart(MinimapUIController ui)
{
return CurrentPage * Capacity(ui);
}
internal static void ClampPage(MinimapUIController ui, int count)
{
int num = PageCountFor(ui, count);
if (CurrentPage < 0)
{
CurrentPage = 0;
}
if (CurrentPage >= num)
{
CurrentPage = num - 1;
}
}
internal static bool IsOnCurrentPage(MinimapUIController ui, int index, int count)
{
int num = PageStart(ui);
if (index >= num && index < num + Capacity(ui))
{
return index < count;
}
return false;
}
private static float CellWorldSize(dfControl panel)
{
if ((Object)(object)panel == (Object)null || (Object)(object)Pixelator.Instance == (Object)null)
{
return 0f;
}
return panel.PixelsToUnits() * Pixelator.Instance.CurrentTileScale;
}
private static float WidthMPX(dfControl control, float num)
{
if ((Object)(object)control == (Object)null || num <= 0f)
{
return 0f;
}
Vector3[] corners = control.GetCorners();
if (corners == null || corners.Length < 3)
{
return 0f;
}
float num2 = (corners[1].x - corners[2].x) / num;
if (float.IsNaN(num2) || float.IsInfinity(num2) || num2 <= 0f)
{
return 0f;
}
return num2;
}
private static float PanelHeightWorld(MinimapUIController ui)
{
if ((Object)(object)ui == (Object)null || (Object)(object)ui.DockPanel == (Object)null)
{
return 0f;
}
Vector3[] corners = ((dfControl)ui.DockPanel).GetCorners();
if (corners == null || corners.Length < 3)
{
return 0f;
}
float num = corners[0].y - corners[2].y;
if (float.IsNaN(num) || float.IsInfinity(num) || num <= 0f)
{
return 0f;
}
return num;
}
private static float BarWidthMPX(MinimapUIController ui)
{
if ((Object)(object)ui == (Object)null || (Object)(object)ui.DockPanel == (Object)null)
{
return 0f;
}
float num = CellWorldSize((dfControl)(object)ui.DockPanel);
if (num <= 0f)
{
return 0f;
}
float num2 = WidthMPX((dfControl)(object)ui.DockSprite, num);
if (num2 > 0f && num2 > num * 40f)
{
return num2;
}
return 0f;
}
internal static void Apply(MinimapUIController ui, List<Tuple<tk2dSprite, PassiveItem>> items, int targetIndex)
{
//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
//IL_024b: Unknown result type (might be due to invalid IL or missing references)
//IL_0250: Unknown result type (might be due to invalid IL or missing references)
//IL_0255: Unknown result type (might be due to invalid IL or missing references)
//IL_0295: 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)
if ((Object)(object)ui == (Object)null || items == null || items.Count == 0 || targetIndex != 0)
{
return;
}
dfControl dockPanel = (dfControl)(object)ui.DockPanel;
if ((Object)(object)dockPanel == (Object)null || (Object)(object)Pixelator.Instance == (Object)null)
{
return;
}
float num = CellWorldSize(dockPanel);
if (num <= 0f)
{
return;
}
int count = items.Count;
ClampPage(ui, count);
int num2 = Mathf.Max(1, ResolvePerRow(ui));
int num3 = EffectiveRows(ui);
int num4 = num2 * num3;
int num5 = CurrentPage * num4;
int num6 = Mathf.Max(0, Mathf.Min(num4, count - num5));
Vector3[] corners = dockPanel.GetCorners();
if (corners == null || corners.Length < 3)
{
return;
}
float x = corners[2].x;
float y = corners[2].y;
float x2 = corners[1].x;
float num7 = (x + x2) * 0.5f;
float num8 = BarWidthMPX(ui);
if (num8 <= 0f)
{
if (!loggedFallback)
{
loggedFallback = true;
Plugin.Log.LogWarning((object)"[layout] DockSprite width unavailable, using fixed spacing");
}
num8 = (float)num2 * 18f;
}
float num9 = PitchMPX(ui);
float num10 = num9 * num;
if (float.IsNaN(num10) || float.IsInfinity(num10) || num10 <= 0f)
{
return;
}
float num11 = (float)num2 * num10;
float num12 = PanelHeightWorld(ui);
float num13 = num12 - (float)num3 * num10;
if (num13 < 0f)
{
num13 = 0f;
}
float num14 = Mathf.Max(2f * num, num13 * 0.5f);
float num15 = y + num14;
int num16 = 0;
for (int i = 0; i < count; i++)
{
tk2dSprite val = ((items[i] != null) ? items[i].First : null);
if ((Object)(object)val == (Object)null)
{
continue;
}
try
{
if (i < num5 || i >= num5 + num6)
{
if (((BraveBehaviour)val).transform.position != ParkedPosition)
{
((BraveBehaviour)val).transform.position = ParkedPosition;
}
continue;
}
int num17 = i - num5;
int num18 = num17 / num2;
int num19 = num17 % num2;
int num20 = Mathf.Min(num2, num6 - num18 * num2);
float num21 = num7 - (float)num20 * num10 * 0.5f;
float num22 = num21 + ((float)num19 + 0.5f) * num10;
float num23 = num15 + ((float)num18 + 0.5f) * num10;
Vector3 val2 = Vector2.op_Implicit(((tk2dBaseSprite)val).WorldCenter);
float num24 = num22 - val2.x;
float num25 = num23 - val2.y;
if (!(Mathf.Abs(num24) < 0.0001f) || !(Mathf.Abs(num25) < 0.0001f))
{
Transform transform = ((BraveBehaviour)val).transform;
transform.position += new Vector3(num24, num25, 0f);
num16++;
}
}
catch (Exception ex)
{
Plugin.Log.LogWarning((object)("[layout] skipped one icon: " + ex.Message));
}
}
if (Plugin.DebugLog != null && Plugin.DebugLog.Value)
{
string text = $"{num2}|{num3}|{CurrentPage}|{count}|{num16}";
if (text != lastLayoutLog)
{
lastLayoutLog = text;
Plugin.Log.LogInfo((object)$"[layout] count={count} page={CurrentPage + 1}/{PageCountFor(ui, count)} visible={num6} perRow={num2} rows={num3}/{RowsPerPageValue} pitch={num10:F3} barW={num8:F1}MPX panelW={(x2 - x) / num:F1}MPX gridW={num11:F2} gridBottom={num15:F2} moved={num16}");
}
}
}
}
internal class DockProbe
{
private readonly ManualLogSource log;
public DockProbe(ManualLogSource logger)
{
log = logger;
}
public void Update()
{
if (Input.GetKeyDown((KeyCode)287))
{
GrantRandomPassives(1);
}
else if (Input.GetKeyDown((KeyCode)288))
{
GrantRandomPassives(10);
}
else if (Input.GetKeyDown((KeyCode)289))
{
DumpDock();
}
else if (Input.GetKeyDown((KeyCode)290))
{
DumpPassiveRegistry();
}
else if (Input.GetKeyDown((KeyCode)291))
{
ForceRearrange();
}
else if (Input.GetKeyDown((KeyCode)292))
{
GrantRandomPassives(20);
}
}
private void ForceRearrange()
{
MinimapUIController val = (((Object)(object)Minimap.Instance != (Object)null) ? Minimap.Instance.UIMinimap : null);
if ((Object)(object)val == (Object)null)
{
log.LogWarning((object)"[probe] 找不到 MinimapUIController");
return;
}
List<Tuple<tk2dSprite, PassiveItem>> list = Reflect.GetField(val, "dockItems") as List<Tuple<tk2dSprite, PassiveItem>>;
MethodInfo method = typeof(MinimapUIController).GetMethod("ArrangeDockItems", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (list == null || (object)method == null)
{
log.LogWarning((object)"[probe] 无法强制重排(字段或方法没找到)");
return;
}
method.Invoke(val, new object[3] { list, val.DockSprite, 0 });
log.LogInfo((object)$"[probe] forced rearrange, count={list.Count}");
}
private void GrantRandomPassives(int count)
{
GameManager instance = GameManager.Instance;
if ((Object)(object)instance == (Object)null || (Object)(object)instance.PrimaryPlayer == (Object)null)
{
log.LogInfo((object)"[probe] 不在局内(没有 PrimaryPlayer),无法添加被动");
return;
}
PickupObjectDatabase instance2 = PickupObjectDatabase.Instance;
if ((Object)(object)instance2 == (Object)null || ((ObjectDatabase<PickupObject>)(object)instance2).Objects == null)
{
log.LogWarning((object)"[probe] PickupObjectDatabase 未就绪");
return;
}
PlayerController primaryPlayer = instance.PrimaryPlayer;
HashSet<int> hashSet = new HashSet<int>();
if (primaryPlayer.passiveItems != null)
{
for (int i = 0; i < primaryPlayer.passiveItems.Count; i++)
{
PassiveItem val = primaryPlayer.passiveItems[i];
if ((Object)(object)val != (Object)null)
{
hashSet.Add(((PickupObject)val).PickupObjectId);
}
}
}
List<PassiveItem> list = new List<PassiveItem>();
for (int j = 0; j < ((ObjectDatabase<PickupObject>)(object)instance2).Objects.Count; j++)
{
PickupObject val2 = ((ObjectDatabase<PickupObject>)(object)instance2).Objects[j];
if (!((Object)(object)val2 == (Object)null))
{
PassiveItem component = ((Component)val2).GetComponent<PassiveItem>();
if (!((Object)(object)component == (Object)null) && ((PickupObject)component).PickupObjectId >= 0 && !hashSet.Contains(((PickupObject)component).PickupObjectId) && (!((Object)(object)((BraveBehaviour)component).encounterTrackable != (Object)null) || !((BraveBehaviour)component).encounterTrackable.SuppressInInventory))
{
list.Add(component);
}
}
}
if (list.Count == 0)
{
log.LogWarning((object)"[probe] 没有可添加的被动(可能已经全收集)");
return;
}
log.LogInfo((object)$"[probe] 候选被动 {list.Count} 个,本次添加 {count} 个");
int num = 0;
for (int k = 0; k < count; k++)
{
if (list.Count <= 0)
{
break;
}
int index = Random.Range(0, list.Count);
PassiveItem val3 = list[index];
list.RemoveAt(index);
log.LogInfo((object)$"[probe] +grant id={((PickupObject)val3).PickupObjectId} name={((Object)val3).name}");
primaryPlayer.AcquirePassiveItemPrefabDirectly(val3);
num++;
}
log.LogInfo((object)$"[probe] granted {num} passive(s); dockRows should grow");
}
private void DumpDock()
{
//IL_0159: Unknown result type (might be due to invalid IL or missing references)
//IL_0489: Unknown result type (might be due to invalid IL or missing references)
//IL_0497: Unknown result type (might be due to invalid IL or missing references)
//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
//IL_02af: Unknown result type (might be due to invalid IL or missing references)
//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
//IL_0370: Unknown result type (might be due to invalid IL or missing references)
//IL_0385: Unknown result type (might be due to invalid IL or missing references)
//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
GameManager instance = GameManager.Instance;
if ((Object)(object)instance == (Object)null || (Object)(object)instance.PrimaryPlayer == (Object)null)
{
log.LogInfo((object)"[probe] 不在局内,F8 无意义");
return;
}
MinimapUIController val = (((Object)(object)Minimap.Instance != (Object)null) ? Minimap.Instance.UIMinimap : null);
if ((Object)(object)val == (Object)null)
{
val = Object.FindObjectOfType<MinimapUIController>();
}
if ((Object)(object)val == (Object)null)
{
log.LogWarning((object)"[probe] 找不到 MinimapUIController");
return;
}
log.LogInfo((object)"================ DOCK DUMP BEGIN ================");
log.LogInfo((object)$"screen={Screen.width}x{Screen.height} tileScale={(((Object)(object)Pixelator.Instance != (Object)null) ? Pixelator.Instance.CurrentTileScale : (-1f))}");
log.LogInfo((object)$"mapHeldDown={Input.GetKey((KeyCode)9)}");
dfGUIManager val2 = (((Object)(object)val.DockPanel != (Object)null) ? ((dfControl)val.DockPanel).GUIManager : null);
if ((Object)(object)val2 != (Object)null)
{
log.LogInfo((object)$"manager: ppu={val2.PixelsToUnits():F6} uiScale={val2.UIScale:F4} tk2dDfScale={GameUIUtility.GetCurrentTK2D_DFScale(val2):F4} screen={val2.GetScreenSize()}");
}
DescribeControl("DockPanel", (dfControl)(object)val.DockPanel);
DescribeControl("DockSprite", (dfControl)(object)val.DockSprite);
DumpCorners("DockPanel", (dfControl)(object)val.DockPanel);
DumpCorners("DockSprite", (dfControl)(object)val.DockSprite);
DescribeControl("DropItemButton", (dfControl)(object)val.DropItemButton);
DescribeControl("ItemPanel_PC", (dfControl)(object)val.ItemPanel_PC);
DescribeControl("GrabbyPanel", (dfControl)(object)val.GrabbyPanel);
List<Tuple<tk2dSprite, PassiveItem>> list = Reflect.GetField(val, "dockItems") as List<Tuple<tk2dSprite, PassiveItem>>;
int num = list?.Count ?? 0;
log.LogInfo((object)$"dockItems.Count = {num}");
Vector2[] array = (Vector2[])(object)new Vector2[num];
float[] array2 = new float[num];
for (int i = 0; i < num; i++)
{
tk2dSprite val3 = ((list[i] != null) ? list[i].First : null);
PassiveItem val4 = ((list[i] != null) ? list[i].Second : null);
if ((Object)(object)val3 == (Object)null)
{
log.LogInfo((object)$" [{i}] sprite=null");
continue;
}
Bounds bounds = ((tk2dBaseSprite)val3).GetBounds();
Vector3 scale = ((tk2dBaseSprite)val3).scale;
ref Vector2 reference = ref array[i];
reference = ((tk2dBaseSprite)val3).WorldCenter;
array2[i] = 0.5f * ((Bounds)(ref bounds)).size.x * scale.x;
log.LogInfo((object)string.Format(" [{0}] name={1} id={2} center=({3:F3},{4:F3}) bounds=({5:F3},{6:F3}) meshScale={7:F3} worldW={8:F3} localPos=({9:F2},{10:F2}) parent={11} canDrop={12}", i, ((Object)(object)val4 != (Object)null) ? ((Object)val4).name : "?", ((Object)(object)val4 != (Object)null) ? ((PickupObject)val4).PickupObjectId : (-1), array[i].x, array[i].y, ((Bounds)(ref bounds)).size.x, ((Bounds)(ref bounds)).size.y, scale.x, ((Bounds)(ref bounds)).size.x * scale.x, ((BraveBehaviour)val3).transform.localPosition.x, ((BraveBehaviour)val3).transform.localPosition.y, ((Object)(object)((BraveBehaviour)val3).transform.parent != (Object)null) ? ((Object)((BraveBehaviour)val3).transform.parent).name : "null", (Object)(object)val4 != (Object)null && ((PickupObject)val4).CanActuallyBeDropped(val4.Owner)));
}
int num2 = 0;
float num3 = float.MaxValue;
for (int j = 0; j < num; j++)
{
for (int k = j + 1; k < num; k++)
{
float num4 = Vector2.Distance(array[j], array[k]);
if (num4 < num3)
{
num3 = num4;
}
float num5 = Mathf.Min(array2[j], array2[k]);
if (num4 < num5)
{
num2++;
}
}
}
log.LogInfo((object)$"overlappingPairs={num2} minCenterDistance={((num > 1) ? num3 : (-1f)):F3}");
log.LogInfo((object)"================= DOCK DUMP END =================");
}
private void DescribeControl(string label, dfControl control)
{
//IL_0043: Unknown result type (might be due to invalid IL or missing references)
//IL_0056: Unknown result type (might be due to invalid IL or missing references)
//IL_0069: 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_008f: Unknown result type (might be due to invalid IL or missing references)
//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
//IL_014e: Unknown result type (might be due to invalid IL or missing references)
//IL_0161: 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_0187: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)control == (Object)null)
{
log.LogInfo((object)$"{label} = null");
return;
}
log.LogInfo((object)$"{label}: name={((Object)control).name} size=({control.Size.x:F1},{control.Size.y:F1}) relPos=({control.RelativePosition.x:F1},{control.RelativePosition.y:F1},{control.RelativePosition.z:F1}) worldPos=({((Component)control).transform.position.x:F2},{((Component)control).transform.position.y:F2},{((Component)control).transform.position.z:F2}) visible={control.IsVisible} enabled={control.IsEnabled} ppu={control.PixelsToUnits():F3}");
dfControl parent = control.Parent;
if ((Object)(object)parent != (Object)null)
{
log.LogInfo((object)$" parent: {((Object)parent).name} size=({parent.Size.x:F1},{parent.Size.y:F1}) relPos=({parent.RelativePosition.x:F1},{parent.RelativePosition.y:F1})");
}
}
private void DumpCorners(string label, dfControl control)
{
if ((Object)(object)control == (Object)null)
{
log.LogInfo((object)$"{label} corners = null");
return;
}
Vector3[] corners = control.GetCorners();
if (corners == null || corners.Length == 0)
{
log.LogInfo((object)$"{label} corners = empty");
return;
}
string text = "";
for (int i = 0; i < corners.Length; i++)
{
text += $"[{i}]({corners[i].x:F3},{corners[i].y:F3}) ";
}
log.LogInfo((object)$"{label} corners: {text}");
}
private void DumpPassiveRegistry()
{
log.LogInfo((object)"============ PASSIVE REGISTRY BEGIN =============");
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
int num = 0;
foreach (Assembly assembly in assemblies)
{
string name = assembly.GetName().Name;
if (name == "mscorlib" || name == "System" || name.StartsWith("System.") || name.StartsWith("UnityEngine") || name.StartsWith("Mono."))
{
continue;
}
log.LogInfo((object)$" assembly: {assembly.FullName}");
Type[] types;
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
types = ex.Types;
}
if (types == null)
{
continue;
}
int num2 = 0;
foreach (Type type in types)
{
if ((object)type != null && !type.IsAbstract && !type.ContainsGenericParameters && typeof(PassiveItem).IsAssignableFrom(type))
{
num2++;
}
}
if (num2 > 0)
{
log.LogInfo((object)$" -> {num2} PassiveItem subclass(es)");
num += num2;
}
}
log.LogInfo((object)$"total PassiveItem subclasses across all mods = {num}");
PickupObjectDatabase instance = PickupObjectDatabase.Instance;
if ((Object)(object)instance == (Object)null || ((ObjectDatabase<PickupObject>)(object)instance).Objects == null)
{
log.LogWarning((object)" PickupObjectDatabase not ready");
return;
}
int num3 = 0;
for (int k = 0; k < ((ObjectDatabase<PickupObject>)(object)instance).Objects.Count; k++)
{
PickupObject val = ((ObjectDatabase<PickupObject>)(object)instance).Objects[k];
if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).GetComponent<PassiveItem>() != (Object)null)
{
num3++;
}
}
log.LogInfo((object)$"registered passive pickups = {num3} / database objects = {((ObjectDatabase<PickupObject>)(object)instance).Objects.Count}");
log.LogInfo((object)"============= PASSIVE REGISTRY END ==============");
}
}
internal static class HarmonyPatches
{
private const BindingFlags PrivateStatic = BindingFlags.Static | BindingFlags.NonPublic;
private static float lastAppliedScale = 1f;
private static float IconScaleFactor
{
get
{
float num = ((Plugin.IconScale != null) ? Plugin.IconScale.Value : 1f);
return Mathf.Clamp(num, 0.3f, 1.5f);
}
}
internal static void Apply(Harmony harmony)
{
Patch(harmony, "ArrangeDockItems", new Type[3]
{
typeof(List<Tuple<tk2dSprite, PassiveItem>>),
typeof(dfSprite),
typeof(int)
}, null, "ArrangeDockItemsPostfix");
Patch(harmony, "ToggleState", new Type[1] { typeof(bool) }, "ToggleStatePrefix", null);
Patch(harmony, "SelectDockItem", new Type[2]
{
typeof(int),
typeof(int)
}, "SelectDockItemPrefix", null);
Patch(harmony, "DropSelectedItem", Type.EmptyTypes, null, "DropSelectedItemPostfix");
Patch(harmony, "Update", Type.EmptyTypes, "UpdatePrefix", null);
Patch(harmony, "UpdateDockItemSpriteScales", Type.EmptyTypes, null, "UpdateDockItemSpriteScalesPostfix");
}
private static void Patch(Harmony harmony, string methodName, Type[] paramTypes, string prefixName, string postfixName)
{
//IL_005c: 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)
MethodInfo methodInfo = AccessTools.Method(typeof(MinimapUIController), methodName, paramTypes, (Type[])null);
if ((object)methodInfo == null)
{
methodInfo = AccessTools.Method(typeof(MinimapUIController), methodName, (Type[])null, (Type[])null);
}
if ((object)methodInfo == null)
{
Plugin.Log.LogError((object)("[patch] MinimapUIController." + methodName + " NOT FOUND"));
return;
}
HarmonyMethod val = ((prefixName == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(HarmonyPatches).GetMethod(prefixName, BindingFlags.Static | BindingFlags.NonPublic)));
HarmonyMethod val2 = ((postfixName == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(HarmonyPatches).GetMethod(postfixName, BindingFlags.Static | BindingFlags.NonPublic)));
harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
Plugin.Log.LogInfo((object)("[patch] hooked MinimapUIController." + methodName));
}
private static void ArrangeDockItemsPostfix(MinimapUIController __instance, List<Tuple<tk2dSprite, PassiveItem>> targetDockItems, dfSprite targetDockSprite, int targetIndex)
{
try
{
DockLayout.Apply(__instance, targetDockItems, targetIndex);
}
catch (Exception ex)
{
Plugin.Log.LogError((object)("[patch] ArrangeDockItems postfix failed: " + ex));
}
}
private static void ToggleStatePrefix(bool active)
{
if (active)
{
DockLayout.CurrentPage = 0;
}
}
private static void SelectDockItemPrefix(MinimapUIController __instance, ref int i, int targetPlayerID)
{
try
{
if (targetPlayerID != 0)
{
return;
}
List<Tuple<tk2dSprite, PassiveItem>> dockItems = GetDockItems(__instance);
if (dockItems == null || dockItems.Count == 0)
{
return;
}
if (Input.GetMouseButtonDown(0))
{
int num = FindNearestIndex(__instance, dockItems);
if (num >= 0)
{
i = num;
}
}
DockLayout.ClampPage(__instance, dockItems.Count);
int num2 = DockLayout.Capacity(__instance);
int num3 = ((num2 > 0) ? (i / num2) : 0);
if (num3 != DockLayout.CurrentPage)
{
DockLayout.CurrentPage = num3;
DockLayout.ClampPage(__instance, dockItems.Count);
DockLayout.Apply(__instance, dockItems, 0);
}
}
catch (Exception ex)
{
Plugin.Log.LogError((object)("[patch] SelectDockItem prefix failed: " + ex));
}
}
private static void DropSelectedItemPostfix(MinimapUIController __instance)
{
try
{
List<Tuple<tk2dSprite, PassiveItem>> dockItems = GetDockItems(__instance);
if (dockItems != null && dockItems.Count > 0)
{
DockLayout.Apply(__instance, dockItems, 0);
}
}
catch (Exception ex)
{
Plugin.Log.LogError((object)("[patch] DropSelectedItem postfix failed: " + ex));
}
}
private static void UpdatePrefix(MinimapUIController __instance)
{
try
{
bool mapActive = (bool)Reflect.GetField(__instance, "m_active");
HandleKeyboard(__instance, mapActive);
PageLabel.Refresh(__instance, mapActive);
}
catch (Exception ex)
{
Plugin.Log.LogError((object)("[patch] keyboard handler failed: " + ex));
}
}
private static void HandleKeyboard(MinimapUIController ui, bool mapActive)
{
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
if (!mapActive)
{
return;
}
GameManager instance = GameManager.Instance;
if ((Object)(object)instance == (Object)null || (int)instance.CurrentGameType != 0)
{
return;
}
BraveInput primaryPlayerInstance = BraveInput.PrimaryPlayerInstance;
if ((Object)(object)primaryPlayerInstance == (Object)null || !primaryPlayerInstance.IsKeyboardAndMouse(false))
{
return;
}
List<Tuple<tk2dSprite, PassiveItem>> dockItems = GetDockItems(ui);
if (dockItems != null && dockItems.Count != 0)
{
DeselectIfOffPage(ui, dockItems.Count);
if (Input.GetKeyDown((KeyCode)273) || Input.GetKeyDown((KeyCode)274))
{
ChangePage(ui, dockItems, Input.GetKeyDown((KeyCode)274) ? 1 : (-1));
}
else if (Input.GetKeyDown((KeyCode)275) || Input.GetKeyDown((KeyCode)276))
{
MoveSelection(ui, dockItems, Input.GetKeyDown((KeyCode)275) ? 1 : (-1));
}
else if (Input.GetKeyDown((KeyCode)102))
{
DropSelected(ui, dockItems);
}
}
}
private static void DropSelected(MinimapUIController ui, List<Tuple<tk2dSprite, PassiveItem>> items)
{
int num = (int)Reflect.GetField(ui, "m_selectedDockItemIndex");
if (num < 0 || num >= items.Count)
{
Plugin.Log.LogInfo((object)("[drop] ignored: nothing selected (index=" + num + ")"));
return;
}
if (!DockLayout.IsOnCurrentPage(ui, num, items.Count))
{
Plugin.Log.LogInfo((object)"[drop] ignored: selected item is not on the current page");
return;
}
PassiveItem val = ((items[num] != null) ? items[num].Second : null);
if ((Object)(object)val == (Object)null || (Object)(object)val.Owner == (Object)null)
{
Plugin.Log.LogInfo((object)"[drop] ignored: item or owner is null");
return;
}
if (!((PickupObject)val).CanActuallyBeDropped(val.Owner))
{
Plugin.Log.LogInfo((object)("[drop] ignored: " + ((Object)val).name + " cannot be dropped"));
return;
}
Plugin.Log.LogInfo((object)("[drop] F: " + ((Object)val).name + " id=" + ((PickupObject)val).PickupObjectId));
ui.DropSelectedItem();
DockLayout.Apply(ui, items, 0);
}
private static void ChangePage(MinimapUIController ui, List<Tuple<tk2dSprite, PassiveItem>> items, int direction)
{
int num = DockLayout.PageCountFor(ui, items.Count);
if (num > 1)
{
DockLayout.CurrentPage = (DockLayout.CurrentPage + direction + num) % num;
DockLayout.Apply(ui, items, 0);
DeselectIfOffPage(ui, items.Count);
Plugin.Log.LogInfo((object)("[page] " + (DockLayout.CurrentPage + 1) + "/" + num + ", items=" + items.Count));
}
}
private static void MoveSelection(MinimapUIController ui, List<Tuple<tk2dSprite, PassiveItem>> items, int direction)
{
int count = items.Count;
int num = DockLayout.PageStart(ui);
int num2 = Mathf.Max(0, Mathf.Min(DockLayout.Capacity(ui), count - num));
if (num2 > 0)
{
int num3 = (int)Reflect.GetField(ui, "m_selectedDockItemIndex");
int num4 = ((num3 >= num && num3 < num + num2) ? (num + (num3 - num + direction + num2) % num2) : ((direction > 0) ? num : (num + num2 - 1)));
Reflect.CallTyped(ui, "SelectDockItem", new Type[2]
{
typeof(int),
typeof(int)
}, num4, 0);
Plugin.Log.LogInfo((object)("[select] " + num4 + ", page=" + (DockLayout.CurrentPage + 1)));
}
}
private static void DeselectIfOffPage(MinimapUIController ui, int count)
{
int num = (int)Reflect.GetField(ui, "m_selectedDockItemIndex");
if (num >= 0 && !DockLayout.IsOnCurrentPage(ui, num, count))
{
Reflect.CallTyped(ui, "DeselectDockItem", Type.EmptyTypes);
}
}
private static void UpdateDockItemSpriteScalesPostfix(MinimapUIController __instance)
{
try
{
float iconScaleFactor = IconScaleFactor;
if (!(Mathf.Abs(iconScaleFactor - 1f) < 0.001f))
{
ScaleList(GetDockItems(__instance), iconScaleFactor);
ScaleList(Reflect.GetField(__instance, "secondaryDockItems") as List<Tuple<tk2dSprite, PassiveItem>>, iconScaleFactor);
if ((bool)Reflect.GetField(__instance, "m_active") && Mathf.Abs(iconScaleFactor - lastAppliedScale) > 0.001f)
{
lastAppliedScale = iconScaleFactor;
DockLayout.Apply(__instance, GetDockItems(__instance), 0);
}
}
}
catch (Exception ex)
{
Plugin.Log.LogError((object)("[patch] UpdateDockItemSpriteScales postfix failed: " + ex));
}
}
private static void ScaleList(List<Tuple<tk2dSprite, PassiveItem>> list, float factor)
{
//IL_002e: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_0057: Unknown result type (might be due to invalid IL or missing references)
//IL_0088: Unknown result type (might be due to invalid IL or missing references)
if (list == null)
{
return;
}
Vector3 scale2 = default(Vector3);
for (int i = 0; i < list.Count; i++)
{
tk2dSprite val = ((list[i] != null) ? list[i].First : null);
if ((Object)(object)val == (Object)null)
{
continue;
}
Vector3 scale = ((tk2dBaseSprite)val).scale;
((Vector3)(ref scale2))..ctor(scale.x * factor, scale.y * factor, scale.z * factor);
((tk2dBaseSprite)val).scale = scale2;
if (!SpriteOutlineManager.HasOutline((tk2dBaseSprite)(object)val))
{
continue;
}
tk2dSprite[] outlineSprites = SpriteOutlineManager.GetOutlineSprites((tk2dBaseSprite)(object)val);
if (outlineSprites == null)
{
continue;
}
for (int j = 0; j < outlineSprites.Length; j++)
{
if ((Object)(object)outlineSprites[j] != (Object)null)
{
((tk2dBaseSprite)outlineSprites[j]).scale = scale2;
}
}
}
}
private static int FindNearestIndex(MinimapUIController ui, List<Tuple<tk2dSprite, PassiveItem>> items)
{
//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_00a4: Unknown result type (might be due to invalid IL or missing references)
//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
//IL_00be: Unknown result type (might be due to invalid IL or missing references)
//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
Camera minimapCamera = ui.minimapCamera;
dfControl dockPanel = (dfControl)(object)ui.DockPanel;
if ((Object)(object)minimapCamera == (Object)null || (Object)(object)dockPanel == (Object)null || items == null)
{
return -1;
}
float num = dockPanel.PixelsToUnits();
if (num <= 0f)
{
return -1;
}
float num2 = 20f * Pixelator.Instance.CurrentTileScale / 2f * num;
Vector3 val = minimapCamera.ScreenToWorldPoint(Input.mousePosition);
Vector2 val2 = default(Vector2);
((Vector2)(ref val2))..ctor(val.x, val.y);
int result = -1;
float num3 = num2;
for (int i = 0; i < items.Count; i++)
{
tk2dSprite val3 = ((items[i] != null) ? items[i].First : null);
if (!((Object)(object)val3 == (Object)null))
{
Vector3 val4 = Vector2.op_Implicit(((tk2dBaseSprite)val3).WorldCenter);
float num4 = Vector2.Distance(new Vector2(val4.x, val4.y), val2);
if (num4 < num3)
{
num3 = num4;
result = i;
}
}
}
return result;
}
private static List<Tuple<tk2dSprite, PassiveItem>> GetDockItems(MinimapUIController ui)
{
return Reflect.GetField(ui, "dockItems") as List<Tuple<tk2dSprite, PassiveItem>>;
}
}
internal static class PageLabel
{
private static dfLabel label;
private static bool created;
private static bool waitedForFont;
private static string lastText;
internal static void Ensure(MinimapUIController ui)
{
//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
//IL_0161: Unknown result type (might be due to invalid IL or missing references)
if (created && (Object)(object)label == (Object)null)
{
created = false;
lastText = null;
}
if (created)
{
return;
}
dfGUIManager val = ResolveManager(ui);
if ((Object)(object)val == (Object)null)
{
return;
}
dfFontBase defaultFont = val.DefaultFont;
if ((Object)(object)defaultFont == (Object)null && (Object)(object)GameUIRoot.Instance != (Object)null && (Object)(object)GameUIRoot.Instance.Manager != (Object)null)
{
defaultFont = GameUIRoot.Instance.Manager.DefaultFont;
}
if ((Object)(object)defaultFont == (Object)null)
{
if (!waitedForFont)
{
waitedForFont = true;
if (Plugin.Log != null)
{
Plugin.Log.LogWarning((object)"[label] dfGUI font not ready yet, will retry");
}
}
return;
}
label = val.AddControl<dfLabel>();
label.Font = defaultFont;
label.TextScale = 2f;
label.AutoSize = true;
((dfControl)label).Pivot = (dfPivotPoint)0;
((dfControl)label).Color = Color32.op_Implicit(Color.white);
((dfControl)label).IsLocalized = false;
label.Text = "1/1";
((dfControl)label).PerformLayout();
((dfControl)label).BringToFront();
created = true;
lastText = null;
if (Plugin.Log != null)
{
Plugin.Log.LogInfo((object)("[label] created manager=" + ((Object)val).name + " size=" + ((dfControl)label).Size));
}
}
internal static void Refresh(MinimapUIController ui, bool mapActive)
{
//IL_0034: Unknown result type (might be due to invalid IL or missing references)
//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
//IL_00f5: 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)
//IL_0113: Unknown result type (might be due to invalid IL or missing references)
//IL_0129: Unknown result type (might be due to invalid IL or missing references)
//IL_0143: 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_01be: Unknown result type (might be due to invalid IL or missing references)
//IL_021f: Unknown result type (might be due to invalid IL or missing references)
try
{
if (!mapActive || (Object)(object)ui == (Object)null || (Object)(object)ui.DockPanel == (Object)null)
{
Hide();
return;
}
GameManager instance = GameManager.Instance;
if ((Object)(object)instance == (Object)null || (int)instance.CurrentGameType != 0)
{
Hide();
}
else if (Reflect.GetField(ui, "dockItems") is List<Tuple<tk2dSprite, PassiveItem>> { Count: not 0 } list)
{
int num = DockLayout.PageCountFor(ui, list.Count);
if (num <= 1)
{
Hide();
return;
}
Ensure(ui);
if (!created || (Object)(object)label == (Object)null)
{
return;
}
string text = DockLayout.CurrentPage + 1 + "/" + num;
if (text != lastText)
{
label.Text = text;
((dfControl)label).PerformLayout();
lastText = text;
}
Vector3 absolutePosition = ((dfControl)ui.DockPanel).GetAbsolutePosition();
Vector2 val = (Vector2)(((Object)(object)((dfControl)label).GUIManager != (Object)null) ? ((dfControl)label).GUIManager.GetScreenSize() : new Vector2(1920f, 1080f));
float num2 = absolutePosition.x + ((dfControl)ui.DockPanel).Width - ((dfControl)label).Size.x - 8f;
float num3 = absolutePosition.y + 8f;
if (float.IsNaN(num2) || float.IsNaN(num3) || float.IsInfinity(num2) || float.IsInfinity(num3))
{
Hide();
return;
}
float num4 = val.x - ((dfControl)label).Size.x - 4f;
float num5 = val.y - ((dfControl)label).Size.y - 4f;
if (num4 < 4f)
{
num4 = 4f;
}
if (num5 < 4f)
{
num5 = 4f;
}
num2 = Mathf.Clamp(num2, 4f, num4);
num3 = Mathf.Clamp(num3, 4f, num5);
((dfControl)label).RelativePosition = new Vector3(num2, num3, 0f);
((dfControl)label).IsVisible = true;
((dfControl)label).BringToFront();
}
else
{
Hide();
}
}
catch (Exception ex)
{
Hide();
if (Plugin.Log != null)
{
Plugin.Log.LogError((object)("[label] refresh failed: " + ex.Message));
}
}
}
private static dfGUIManager ResolveManager(MinimapUIController ui)
{
if ((Object)(object)GameUIRoot.Instance != (Object)null && (Object)(object)GameUIRoot.Instance.Manager != (Object)null)
{
return GameUIRoot.Instance.Manager;
}
if ((Object)(object)ui != (Object)null && (Object)(object)ui.DockPanel != (Object)null)
{
return ((dfControl)ui.DockPanel).GUIManager;
}
return null;
}
private static void Hide()
{
if (created && (Object)(object)label != (Object)null)
{
((dfControl)label).IsVisible = false;
}
}
}
[BepInPlugin("hawkhao.etg.itemdockfix", "ItemDockFix", "1.1.2")]
public class Plugin : BaseUnityPlugin
{
internal static Plugin Instance;
internal static ManualLogSource Log;
internal static ConfigEntry<int> ItemsPerRow;
internal static ConfigEntry<int> RowsPerPage;
internal static ConfigEntry<float> IconScale;
internal static ConfigEntry<bool> DebugLog;
internal static ConfigEntry<bool> DebugHotkeys;
private Harmony harmony;
private DockProbe probe;
private void Awake()
{
//IL_0035: Unknown result type (might be due to invalid IL or missing references)
//IL_003f: Expected O, but got Unknown
//IL_0067: Unknown result type (might be due to invalid IL or missing references)
//IL_0071: Expected O, but got Unknown
//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
//IL_00af: Expected O, but got Unknown
//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
//IL_0104: Expected O, but got Unknown
Instance = this;
Log = ((BaseUnityPlugin)this).Logger;
ItemsPerRow = ((BaseUnityPlugin)this).Config.Bind<int>("Layout", "ItemsPerRow", 0, new ConfigDescription("Items per row in the dock. 0 = fill the vanilla dock bar width automatically; a positive value is an upper limit (the auto value still wins when it is narrower).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 32), new object[0]));
RowsPerPage = ((BaseUnityPlugin)this).Config.Bind<int>("Layout", "RowsPerPage", 3, new ConfigDescription("Maximum rows per page. The effective value is clamped further so the grid never grows outside the dock panel (it adapts to the panel height).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8), new object[0]));
IconScale = ((BaseUnityPlugin)this).Config.Bind<float>("Layout", "IconScale", 0.8f, new ConfigDescription("Scale of the passive icons in the dock, relative to vanilla (1.0 = vanilla size).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.4f, 1.2f), new object[0]));
DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogLayout", false, "Log one geometry line every time the dock is rearranged. Only for troubleshooting.");
DebugHotkeys = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "EnableDebugHotkeys", false, "Enable dev hotkeys F6-F11 (grant random passives, dump dock geometry, dump passive registry, force rearrange). For testing only.");
harmony = new Harmony("hawkhao.etg.itemdockfix");
HarmonyPatches.Apply(harmony);
probe = new DockProbe(Log);
Log.LogInfo((object)string.Format("{0} v{1} loaded. ItemsPerRow={2} RowsPerPage={3} IconScale={4}", "ItemDockFix", "1.1.2", ItemsPerRow.Value, RowsPerPage.Value, IconScale.Value));
}
private void Update()
{
if (probe != null && DebugHotkeys != null && DebugHotkeys.Value)
{
probe.Update();
}
}
private void OnDestroy()
{
if (harmony != null)
{
harmony.UnpatchSelf();
harmony = null;
}
}
}
internal static class PluginInfo
{
public const string Guid = "hawkhao.etg.itemdockfix";
public const string Name = "ItemDockFix";
public const string Version = "1.1.2";
}
internal static class Reflect
{
private const BindingFlags All = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public static object GetField(object target, string name)
{
if (target == null)
{
return null;
}
Type type = target.GetType();
while ((object)type != null && (object)type != typeof(object))
{
FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if ((object)field != null)
{
return field.GetValue(target);
}
type = type.BaseType;
}
return null;
}
public static object Call(object target, string name, params object[] args)
{
if (target == null)
{
return null;
}
Type type = target.GetType();
while ((object)type != null && (object)type != typeof(object))
{
MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if ((object)method != null)
{
try
{
return method.Invoke(target, args);
}
catch (Exception ex)
{
return "EXC: " + ex;
}
}
type = type.BaseType;
}
return null;
}
public static object CallTyped(object target, string name, Type[] paramTypes, params object[] args)
{
if (target == null)
{
return null;
}
Type type = target.GetType();
while ((object)type != null && (object)type != typeof(object))
{
MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, paramTypes, null);
if ((object)method != null)
{
try
{
return method.Invoke(target, args);
}
catch (Exception ex)
{
return "EXC: " + ex;
}
}
type = type.BaseType;
}
return null;
}
}