forked from TehCheat/HighlightedItems
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathHighlightedItems.cs
More file actions
643 lines (556 loc) · 23.5 KB
/
HighlightedItems.cs
File metadata and controls
643 lines (556 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
using System.Windows.Forms;
using HighlightedItems.Utils;
using ExileCore;
using ExileCore.PoEMemory.Elements.InventoryElements;
using ExileCore.PoEMemory.MemoryObjects;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ExileCore.Shared.Enums;
using ImGuiNET;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using ExileCore.PoEMemory.Components;
using ExileCore.Shared;
using ExileCore.Shared.Helpers;
using ItemFilterLibrary;
using SharpDX;
using Vector2 = System.Numerics.Vector2;
namespace HighlightedItems;
public class HighlightedItems : BaseSettingsPlugin<Settings>
{
private SyncTask<bool> _currentOperation;
private string _customStashFilter = "";
private string _customInventoryFilter = "";
private record QueryOrException(ItemQuery Query, Exception Exception);
private readonly ConditionalWeakTable<string, QueryOrException> _queries = [];
private bool MoveCancellationRequested => Settings.CancelWithRightMouseButton && (Control.MouseButtons & MouseButtons.Right) != 0;
private IngameState InGameState => GameController.IngameState;
private SharpDX.Vector2 WindowOffset => GameController.Window.GetWindowRectangleTimeCache.TopLeft;
public override bool Initialise()
{
Graphics.InitImage(Path.Combine(DirectoryFullName, "images\\pick.png").Replace('\\', '/'), false);
Graphics.InitImage(Path.Combine(DirectoryFullName, "images\\pickL.png").Replace('\\', '/'), false);
return true;
}
public override void AreaChange(AreaInstance area)
{
_mouseStateForRect.Clear();
}
public override void DrawSettings()
{
base.DrawSettings();
DrawIgnoredCellsSettings();
}
private Predicate<Entity> GetPredicate(string windowTitle, ref string filterText, Vector2 defaultPosition)
{
if (!Settings.ShowCustomFilterWindow) return null;
Settings.SavedFilters ??= [];
ImGui.SetNextWindowPos(defaultPosition, ImGuiCond.FirstUseEver);
if (ImGui.Begin(windowTitle, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.AlwaysAutoResize))
{
ImGui.InputTextWithHint("##input", "Filter using IFL syntax", ref filterText, 2000);
Predicate<Entity> returnValue = null;
if (!string.IsNullOrWhiteSpace(filterText))
{
ImGui.SameLine();
if (ImGui.Button("Clear"))
{
filterText = "";
return null;
}
if (!Settings.SavedFilters.Contains(filterText))
{
ImGui.SameLine();
if (ImGui.Button("Save"))
{
Settings.SavedFilters.Add(filterText);
}
}
var (query, exception) = _queries.GetValue(filterText, s =>
{
try
{
var itemQuery = ItemQuery.Load(s);
if (itemQuery.FailedToCompile)
{
return new QueryOrException(null, new Exception(itemQuery.Error));
}
return new QueryOrException(itemQuery, null);
}
catch (Exception ex)
{
return new QueryOrException(null, ex);
}
})!;
if (exception != null)
{
ImGui.TextUnformatted($"{exception.Message}");
}
else
{
returnValue = s =>
{
try
{
return query.CompiledQuery(new ItemData(s, GameController));
}
catch (Exception ex)
{
DebugWindow.LogError($"Failed to match item: {ex}");
return false;
}
};
}
}
// ReSharper disable once AssignmentInConditionalExpression
if (Settings.SavedFilters.Any() && Settings.UsePopupForFilterSelector
? Settings.OpenSavedFilterList = ImGui.BeginPopupContextItem("saved_filter_popup")
: Settings.OpenSavedFilterList = ImGui.TreeNodeEx("Saved filters",
Settings.OpenSavedFilterList
? ImGuiTreeNodeFlags.DefaultOpen | ImGuiTreeNodeFlags.NoTreePushOnOpen
: ImGuiTreeNodeFlags.NoTreePushOnOpen))
{
foreach (var (savedFilter, index) in Settings.SavedFilters.Select((x, i) => (x, i)).ToList())
{
ImGui.PushID($"saved{index}");
if (ImGui.Button("Load"))
{
filterText = savedFilter;
}
ImGui.SameLine();
if (ImGui.Button("Delete"))
{
if (ImGui.IsKeyDown(ImGuiKey.ModShift))
{
Settings.SavedFilters.Remove(savedFilter);
}
}
else if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("Hold Shift");
}
ImGui.SameLine();
ImGui.TextUnformatted(savedFilter);
ImGui.PopID();
}
if (Settings.UsePopupForFilterSelector)
{
ImGui.EndPopup();
}
else
{
ImGui.TreePop();
}
}
if (Settings.UsePopupForFilterSelector)
{
if (ImGui.Button("Open Saved Filters"))
{
ImGui.OpenPopup("saved_filter_popup");
}
}
ImGui.End();
return returnValue;
}
return null;
}
public override void Render()
{
if (_currentOperation != null)
{
DebugWindow.LogMsg("Running the inventory dump procedure...");
TaskUtils.RunOrRestart(ref _currentOperation, () => null);
if (_itemsToMove is { Count: > 0 } itemsToMove)
{
foreach (var (rect, color) in itemsToMove.Skip(1).Select(x => (x, Settings.CustomFilterFrameColor)).Prepend((itemsToMove[0], Color.Green)))
{
Graphics.DrawFrame(rect.TopLeft.ToVector2Num(), rect.BottomRight.ToVector2Num(), color, Settings.CustomFilterFrameThickness);
}
}
return;
}
if (!Settings.Enable)
return;
var (inventory, rectElement) = (InGameState.IngameUi.StashElement, InGameState.IngameUi.GuildStashElement) switch
{
({ IsVisible: true, VisibleStash: { InventoryUIElement: { } invRect } visibleStash }, _) => (visibleStash, invRect),
(_, { IsVisible: true, VisibleStash: { InventoryUIElement: { } invRect } visibleStash }) => (visibleStash, invRect),
_ => (null, null)
};
const float buttonSize = 37;
var highlightedItemsFound = false;
if (inventory != null)
{
var stashRect = rectElement.GetClientRectCache;
var (itemFilter, isCustomFilter) = GetPredicate("Custom stash filter", ref _customStashFilter, stashRect.BottomLeft.ToVector2Num()) is { } customPredicate
? ((Predicate<NormalInventoryItem>)(s => customPredicate(s.Item)), true)
: (s => s.isHighlighted != Settings.InvertSelection.Value, false);
//Determine Stash Pickup Button position and draw
var buttonPos = Settings.UseCustomMoveToInventoryButtonPosition
? Settings.CustomMoveToInventoryButtonPosition
: stashRect.BottomRight.ToVector2Num() + new Vector2(-43, 10);
var buttonRect = new SharpDX.RectangleF(buttonPos.X, buttonPos.Y, buttonSize, buttonSize);
Graphics.DrawImage("pick.png", buttonRect);
var highlightedItems = GetHighlightedItems(inventory, itemFilter);
highlightedItemsFound = highlightedItems.Any();
int? stackSizes = 0;
foreach (var item in highlightedItems)
{
stackSizes += item.Item?.GetComponent<Stack>()?.Size;
if (isCustomFilter)
{
var rect = item.GetClientRectCache;
var deflateFactor = Settings.CustomFilterBorderDeflation / 200.0;
var deflateWidth = (int)(rect.Width * deflateFactor + Settings.CustomFilterFrameThickness / 2);
var deflateHeight = (int)(rect.Height * deflateFactor + Settings.CustomFilterFrameThickness / 2);
rect.Inflate(-deflateWidth, -deflateHeight);
var topLeft = rect.TopLeft.ToVector2Num();
var bottomRight = rect.BottomRight.ToVector2Num();
Graphics.DrawFrame(topLeft, bottomRight, Settings.CustomFilterFrameColor, Settings.CustomFilterBorderRounding, Settings.CustomFilterFrameThickness, 0);
}
}
var countText = Settings.ShowStackSizes && highlightedItems.Count != stackSizes && stackSizes != null
? Settings.ShowStackCountWithSize
? $"{stackSizes} / {highlightedItems.Count}"
: $"{stackSizes}"
: $"{highlightedItems.Count}";
var countPos = new Vector2(buttonRect.Left - 2, buttonRect.Center.Y - 11);
Graphics.DrawText($"{countText}", countPos with { Y = countPos.Y + 2 }, SharpDX.Color.Black, FontAlign.Right);
Graphics.DrawText($"{countText}", countPos with { X = countPos.X - 2 }, SharpDX.Color.White, FontAlign.Right);
if (IsButtonPressed(buttonRect) ||
Input.IsKeyDown(Settings.MoveToInventoryHotkey.Value))
{
var orderedItems = highlightedItems
.OrderBy(stashItem => stashItem.GetClientRectCache.X)
.ThenBy(stashItem => stashItem.GetClientRectCache.Y)
.ToList();
_currentOperation = MoveItemsToInventory(orderedItems);
}
}
else
{
if (Settings.ResetCustomFilterOnPanelClose)
{
_customStashFilter = "";
}
}
var inventoryPanel = InGameState.IngameUi.InventoryPanel;
if (inventoryPanel.IsVisible)
{
var inventoryRect = inventoryPanel[2].GetClientRectCache;
var (itemFilter, isCustomFilter) = GetPredicate("Custom inventory filter", ref _customInventoryFilter, inventoryRect.BottomLeft.ToVector2Num()) is { } customPredicate
? (customPredicate, true)
: (_ => true, false);
if (Settings.DumpButtonEnable && IsStashTargetOpened)
{
//Determine Inventory Pickup Button position and draw
var buttonPos = Settings.UseCustomMoveToStashButtonPosition
? Settings.CustomMoveToStashButtonPosition
: inventoryRect.TopLeft.ToVector2Num() + new Vector2(buttonSize / 2, -buttonSize);
var buttonRect = new SharpDX.RectangleF(buttonPos.X, buttonPos.Y, buttonSize, buttonSize);
if (isCustomFilter)
{
foreach (var item in GameController.IngameState.ServerData.PlayerInventories[0].Inventory.InventorySlotItems.Where(x => itemFilter(x.Item)))
{
var rect = item.GetClientRect();
var deflateFactor = Settings.CustomFilterBorderDeflation / 200.0;
var deflateWidth = (int)(rect.Width * deflateFactor + Settings.CustomFilterFrameThickness / 2);
var deflateHeight = (int)(rect.Height * deflateFactor + Settings.CustomFilterFrameThickness / 2);
rect.Inflate(-deflateWidth, -deflateHeight);
var topLeft = rect.TopLeft.ToVector2Num();
var bottomRight = rect.BottomRight.ToVector2Num();
Graphics.DrawFrame(topLeft, bottomRight, Settings.CustomFilterFrameColor, Settings.CustomFilterBorderRounding, Settings.CustomFilterFrameThickness, 0);
}
}
Graphics.DrawImage("pickL.png", buttonRect);
if (IsButtonPressed(buttonRect) ||
Input.IsKeyDown(Settings.MoveToStashHotkey.Value) ||
Settings.UseMoveToInventoryAsMoveToStashWhenNoHighlights &&
!highlightedItemsFound &&
Input.IsKeyDown(Settings.MoveToInventoryHotkey.Value))
{
var inventoryItems = GameController.IngameState.ServerData.PlayerInventories[0].Inventory.InventorySlotItems
.Where(x => !IsInIgnoreCell(x))
.Where(x => itemFilter(x.Item))
.OrderBy(x => x.PosX)
.ThenBy(x => x.PosY)
.ToList();
_currentOperation = MoveItemsToStash(inventoryItems);
}
}
}
else
{
if (Settings.ResetCustomFilterOnPanelClose)
{
_customInventoryFilter = "";
}
}
}
private async SyncTask<bool> MoveItemsCommonPreamble()
{
while (Control.MouseButtons == MouseButtons.Left || MoveCancellationRequested)
{
if (MoveCancellationRequested)
{
return false;
}
await TaskUtils.NextFrame();
}
if (Settings.IdleMouseDelay.Value == 0)
{
return true;
}
var mousePos = Mouse.GetCursorPosition();
var sw = Stopwatch.StartNew();
await TaskUtils.NextFrame();
while (true)
{
if (MoveCancellationRequested)
{
return false;
}
var newPos = Mouse.GetCursorPosition();
if (mousePos != newPos)
{
mousePos = newPos;
sw.Restart();
}
else if (sw.ElapsedMilliseconds >= Settings.IdleMouseDelay.Value)
{
return true;
}
else
{
await TaskUtils.NextFrame();
}
}
}
private async SyncTask<bool> MoveItemsToStash(List<ServerInventory.InventSlotItem> items)
{
if (!await MoveItemsCommonPreamble())
{
return false;
}
_prevMousePos = Mouse.GetCursorPosition();
Keyboard.KeyDown(Keys.LControlKey);
await Wait(KeyDelay, true);
for (var i = 0; i < items.Count; i++)
{
var item = items[i];
_itemsToMove = items[i..].Select(x => x.GetClientRect()).ToList();
if (MoveCancellationRequested)
{
await StopMovingItems();
return false;
}
if (!InGameState.IngameUi.InventoryPanel.IsVisible)
{
DebugWindow.LogMsg("HighlightedItems: Inventory Panel closed, aborting loop");
break;
}
if (!IsStashTargetOpened)
{
DebugWindow.LogMsg("HighlightedItems: Target inventory closed, aborting loop");
break;
}
await MoveItem(item.GetClientRect().Center);
}
await StopMovingItems();
return true;
}
private bool IsStashTargetOpened =>
!Settings.VerifyTargetInventoryIsOpened
|| InGameState.IngameUi.StashElement.IsVisible
|| InGameState.IngameUi.SellWindow.IsVisible
|| InGameState.IngameUi.TradeWindow.IsVisible
|| InGameState.IngameUi.GuildStashElement.IsVisible;
private bool IsStashSourceOpened =>
!Settings.VerifyTargetInventoryIsOpened
|| InGameState.IngameUi.StashElement.IsVisible
|| InGameState.IngameUi.GuildStashElement.IsVisible;
private List<RectangleF> _itemsToMove = null;
private Point _prevMousePos = Point.Zero;
private async SyncTask<bool> MoveItemsToInventory(List<NormalInventoryItem> items)
{
if (!await MoveItemsCommonPreamble())
{
return false;
}
_prevMousePos = Mouse.GetCursorPosition();
Keyboard.KeyDown(Keys.LControlKey);
await Wait(KeyDelay, true);
for (var i = 0; i < items.Count; i++)
{
var item = items[i];
_itemsToMove = items[i..].Select(x => x.GetClientRectCache).ToList();
if (MoveCancellationRequested)
{
await StopMovingItems();
return false;
}
if (!IsStashSourceOpened)
{
DebugWindow.LogMsg("HighlightedItems: Stash Panel closed, aborting loop");
break;
}
if (!InGameState.IngameUi.InventoryPanel.IsVisible)
{
DebugWindow.LogMsg("HighlightedItems: Inventory Panel closed, aborting loop");
break;
}
if (IsInventoryFull())
{
DebugWindow.LogMsg("HighlightedItems: Inventory full, aborting loop");
break;
}
await MoveItem(item.GetClientRect().Center);
}
await StopMovingItems();
return true;
}
private async SyncTask<bool> StopMovingItems() {
Keyboard.KeyUp(Keys.LControlKey);
await Wait(KeyDelay, false);
Mouse.moveMouse(_prevMousePos);
_prevMousePos = Point.Zero;
_itemsToMove = null;
DebugWindow.LogMsg("HighlightedItems: Stopped moving items");
return true;
}
private List<NormalInventoryItem> GetHighlightedItems(Inventory stash, Predicate<NormalInventoryItem> filter)
{
try
{
var stashItems = stash.VisibleInventoryItems;
var highlightedItems = stashItems
.Where(stashItem => filter(stashItem))
.ToList();
return highlightedItems;
}
catch
{
return [];
}
}
private bool IsInventoryFull()
{
var inventoryItems = GameController.IngameState.ServerData.PlayerInventories[0].Inventory.InventorySlotItems;
// quick sanity check
if (inventoryItems.Count < 12)
{
return false;
}
// track each inventory slot
bool[,] inventorySlot = new bool[12, 5];
// iterate through each item in the inventory and mark used slots
foreach (var inventoryItem in inventoryItems)
{
int x = inventoryItem.PosX;
int y = inventoryItem.PosY;
int height = inventoryItem.SizeY;
int width = inventoryItem.SizeX;
for (int row = x; row < x + width; row++)
{
for (int col = y; col < y + height; col++)
{
inventorySlot[row, col] = true;
}
}
}
// check for any empty slots
for (int x = 0; x < 12; x++)
{
for (int y = 0; y < 5; y++)
{
if (inventorySlot[x, y] == false)
{
return false;
}
}
}
// no empty slots, so inventory is full
return true;
}
private static readonly TimeSpan KeyDelay = TimeSpan.FromMilliseconds(10);
private static readonly TimeSpan MouseMoveDelay = TimeSpan.FromMilliseconds(20);
private TimeSpan MouseDownDelay => TimeSpan.FromMilliseconds(25 + Settings.ExtraDelay.Value);
private static readonly TimeSpan MouseUpDelay = TimeSpan.FromMilliseconds(5);
private async SyncTask<bool> MoveItem(SharpDX.Vector2 itemPosition)
{
itemPosition += WindowOffset;
Mouse.moveMouse(itemPosition);
await Wait(MouseMoveDelay, true);
Mouse.LeftDown();
await Wait(MouseDownDelay, true);
Mouse.LeftUp();
await Wait(MouseUpDelay, true);
return true;
}
private async SyncTask<bool> Wait(TimeSpan period, bool canUseThreadSleep)
{
if (canUseThreadSleep && Settings.UseThreadSleep)
{
Thread.Sleep(period);
return true;
}
var sw = Stopwatch.StartNew();
while (sw.Elapsed < period)
{
await TaskUtils.NextFrame();
}
return true;
}
private readonly ConcurrentDictionary<RectangleF, bool?> _mouseStateForRect = [];
private bool IsButtonPressed(RectangleF buttonRect)
{
var prevState = _mouseStateForRect.GetValueOrDefault(buttonRect);
var isHovered = buttonRect.Contains(Mouse.GetCursorPosition() - WindowOffset);
if (!isHovered)
{
_mouseStateForRect[buttonRect] = null;
return false;
}
var isPressed = Control.MouseButtons == MouseButtons.Left && CanClickButtons;
_mouseStateForRect[buttonRect] = isPressed;
return isPressed &&
prevState == false;
}
private bool CanClickButtons => !Settings.VerifyButtonIsNotObstructed || !ImGui.GetIO().WantCaptureMouse;
private bool IsInIgnoreCell(ServerInventory.InventSlotItem inventItem)
{
var inventPosX = inventItem.PosX;
var inventPosY = inventItem.PosY;
if (inventPosX < 0 || inventPosX >= 12)
return true;
if (inventPosY < 0 || inventPosY >= 5)
return true;
return Settings.IgnoredCells[inventPosY, inventPosX]; //No need to check all item size
}
private void DrawIgnoredCellsSettings()
{
ImGui.BeginChild("##IgnoredCellsMain", new Vector2(ImGui.GetContentRegionAvail().X, 204f), ImGuiChildFlags.Border,
ImGuiWindowFlags.NoScrollWithMouse);
ImGui.Text("Ignored Inventory Slots (checked = ignored)");
var contentRegionAvail = ImGui.GetContentRegionAvail();
ImGui.BeginChild("##IgnoredCellsCels", new Vector2(contentRegionAvail.X, contentRegionAvail.Y), ImGuiChildFlags.Border,
ImGuiWindowFlags.NoScrollWithMouse);
for (int y = 0; y < 5; ++y)
{
for (int x = 0; x < 12; ++x)
{
bool isCellIgnored = Settings.IgnoredCells[y, x];
if (ImGui.Checkbox($"##{y}_{x}IgnoredCells", ref isCellIgnored))
Settings.IgnoredCells[y, x] = isCellIgnored;
if (x < 11)
ImGui.SameLine();
}
}
ImGui.EndChild();
ImGui.EndChild();
}
}