forked from danielkrupinski/Osiris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InventoryChanger.cpp
1471 lines (1206 loc) · 60.8 KB
/
InventoryChanger.cpp
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <cassert>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include <range/v3/algorithm/search.hpp>
#include <range/v3/algorithm/sort.hpp>
#include <range/v3/view/split.hpp>
#include <range/v3/view/zip.hpp>
#define STBI_ONLY_PNG
#define STBI_NO_FAILURE_STRINGS
#define STBI_NO_STDIO
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <imgui/imgui.h>
#define IMGUI_DEFINE_MATH_OPERATORS
#include <imgui/imgui_internal.h>
#include <imgui/imgui_stdlib.h>
#include "InventoryChanger.h"
#include "../ProtobufReader.h"
#include "../Texture.h"
#include <nlohmann/json.hpp>
#include <CSGO/PODs/ConVar.h>
#include <CSGO/Constants/ClassId.h>
#include <CSGO/Client.h>
#include <CSGO/ClientClass.h>
#include <CSGO/ConVar.h>
#include <CSGO/Cvar.h>
#include <CSGO/EconItemView.h>
#include <CSGO/Entity.h>
#include <CSGO/EntityList.h>
#include <CSGO/FileSystem.h>
#include <CSGO/Constants/ConVarNames.h>
#include <CSGO/Constants/FrameStage.h>
#include <CSGO/GameEvent.h>
#include <CSGO/GlobalVars.h>
#include <CSGO/ItemSchema.h>
#include <CSGO/LocalPlayer.h>
#include <CSGO/MemAlloc.h>
#include <CSGO/ModelInfo.h>
#include <CSGO/Panorama.h>
#include <CSGO/PlayerResource.h>
#include <CSGO/WeaponId.h>
#include <CSGO/PanoramaMarshallHelper.h>
#include <CSGO/CSPlayerInventory.h>
#include "../Helpers.h"
#include "GameItems/Lookup.h"
#include "Inventory/Item.h"
#include "Inventory/Structs.h"
#include "Backend/Loadout.h"
#include "Backend/BackendSimulator.h"
#include "ItemGenerator/ItemGenerator.h"
#include "Backend/Response/ResponseHandler.h"
#include "Backend/Request/RequestBuilder.h"
#include "GameIntegration/CrateLoot.h"
#include "GameIntegration/Inventory.h"
#include "GameIntegration/Items.h"
#include "../Hooks.h"
#include "WeaponNames.h"
#include <SortFilter.h>
#if IS_WIN32()
#include "Platform/Windows/DynamicLibrarySection.h"
#elif IS_LINUX()
#include "Platform/Linux/DynamicLibrarySection.h"
#endif
#include <Interfaces/ClientInterfaces.h>
#include <Interfaces/OtherInterfaces.h>
#if IS_WIN32()
static csgo::EntityPOD* createGloves(const ClientInterfaces& clientInterfaces, csgo::MemAllocPOD* memAlloc) noexcept
{
static const auto createWearable = [&clientInterfaces] {
std::uintptr_t createWearableFn = 0;
for (auto clientClass = clientInterfaces.getClient().getAllClasses(); clientClass; clientClass = clientClass->next) {
if (clientClass->classId == ClassId::EconWearable) {
createWearableFn = std::uintptr_t(clientClass->createFunction);
break;
}
}
return createWearableFn;
}();
const auto sizeOfEconWearable = *reinterpret_cast<std::uint32_t*>(std::uintptr_t(createWearable) + 39);
const auto econWearable = csgo::MemAlloc::from(retSpoofGadgets->client, memAlloc).allocAligned(sizeOfEconWearable, 16);
if (!econWearable)
return nullptr;
std::memset(econWearable, 0, sizeOfEconWearable);
const auto econWearableConstructor = SafeAddress{ std::uintptr_t(createWearable) + 61 }.relativeToAbsolute().get();
retSpoofGadgets->client.invokeThiscall<void>(std::uintptr_t(econWearable), econWearableConstructor);
csgo::Entity::from(retSpoofGadgets->client, static_cast<csgo::EntityPOD*>(econWearable)).initializeAsClientEntity(nullptr, false);
return static_cast<csgo::EntityPOD*>(econWearable);
}
#else
static csgo::EntityPOD* createGlove(const ClientInterfaces& clientInterfaces, int entry, int serial) noexcept
{
static const auto createWearable = [&clientInterfaces]{
std::add_pointer_t<csgo::EntityPOD* CDECL_CONV(int, int)> createWearableFn = nullptr;
for (auto clientClass = clientInterfaces.getClient().getAllClasses(); clientClass; clientClass = clientClass->next) {
if (clientClass->classId == ClassId::EconWearable) {
createWearableFn = clientClass->createFunction;
break;
}
}
return createWearableFn;
}();
if (!createWearable)
return nullptr;
if (const auto wearable = createWearable(entry, serial))
return reinterpret_cast<csgo::EntityPOD*>(std::uintptr_t(wearable) - 2 * sizeof(std::uintptr_t));
return nullptr;
}
#endif
static std::optional<std::list<inventory_changer::inventory::Item>::const_iterator> getItemFromLoadout(const inventory_changer::backend::Loadout& loadout, csgo::Team team, std::uint8_t slot)
{
switch (team) {
case csgo::Team::None: return loadout.getItemInSlotNoTeam(slot);
case csgo::Team::CT: return loadout.getItemInSlotCT(slot);
case csgo::Team::TT: return loadout.getItemInSlotTT(slot);
default: return {};
}
}
static void applyGloves(const EngineInterfaces& engineInterfaces, const ClientInterfaces& clientInterfaces, const OtherInterfaces& interfaces, const Memory& memory, const inventory_changer::backend::BackendSimulator& backend, const csgo::CSPlayerInventory& localInventory, const csgo::Entity& local) noexcept
{
const auto optionalItem = getItemFromLoadout(backend.getLoadout(), local.getTeamNumber(), 41);
if (!optionalItem.has_value())
return;
const auto& item = *optionalItem;
const auto itemID = backend.getItemID(item);
if (!itemID.has_value())
return;
const auto wearables = local.wearables();
static int gloveHandle = 0;
auto glovePtr = clientInterfaces.getEntityList().getEntityFromHandle(wearables[0]);
if (!glovePtr)
glovePtr = clientInterfaces.getEntityList().getEntityFromHandle(gloveHandle);
if (!glovePtr) {
#if IS_WIN32()
glovePtr = createGloves(clientInterfaces, memory.memAlloc);
#else
constexpr auto NUM_ENT_ENTRIES = 8192;
glovePtr = createGlove(clientInterfaces, NUM_ENT_ENTRIES - 1, -1);
#endif
}
if (!glovePtr)
return;
const auto glove = csgo::Entity::from(retSpoofGadgets->client, glovePtr);
wearables[0] = gloveHandle = glove.handle();
glove.accountID() = localInventory.getAccountID();
glove.entityQuality() = 3;
local.body() = 1;
bool dataUpdated = false;
if (auto& definitionIndex = glove.itemDefinitionIndex(); definitionIndex != item->gameItem().getWeaponID()) {
definitionIndex = item->gameItem().getWeaponID();
if (const auto def = csgo::ItemSchema::from(retSpoofGadgets->client, memory.itemSystem().getItemSchema()).getItemDefinitionInterface(item->gameItem().getWeaponID()))
glove.setModelIndex(engineInterfaces.getModelInfo().getModelIndex(csgo::EconItemDefinition::from(retSpoofGadgets->client, def).getWorldDisplayModel()));
dataUpdated = true;
}
if (glove.itemID() != static_cast<csgo::ItemId>(*itemID)) {
glove.itemIDHigh() = std::uint32_t(static_cast<csgo::ItemId>(*itemID) >> 32);
glove.itemIDLow() = std::uint32_t(static_cast<csgo::ItemId>(*itemID) & 0xFFFFFFFF);
dataUpdated = true;
}
glove.initialized() = true;
memory.equipWearable(glove.getPOD(), local.getPOD());
if (dataUpdated) {
// FIXME: This leaks game memory
glove.econItemView().visualDataProcessors().size = 0;
glove.econItemView().customMaterials().size = 0;
//
glove.getNetworkable().postDataUpdate(0);
glove.getNetworkable().onDataChanged(0);
}
}
static void applyKnife(const EngineInterfaces& engineInterfaces, const ClientInterfaces& clientInterfaces, const OtherInterfaces& interfaces, const Memory& memory, const inventory_changer::backend::BackendSimulator& backend, const csgo::CSPlayerInventory& localInventory, const csgo::Entity& local) noexcept
{
const auto localXuid = local.getSteamId(engineInterfaces.getEngine());
const auto optionalItem = getItemFromLoadout(backend.getLoadout(), local.getTeamNumber(), 0);
if (!optionalItem.has_value())
return;
const auto& item = *optionalItem;
const auto itemID = backend.getItemID(item);
if (!itemID.has_value())
return;
for (auto& weapons = local.weapons(); auto weaponHandle : weapons) {
if (weaponHandle == -1)
break;
const auto weapon = csgo::Entity::from(retSpoofGadgets->client, clientInterfaces.getEntityList().getEntityFromHandle(weaponHandle));
if (weapon.getPOD() == nullptr)
continue;
auto& definitionIndex = weapon.itemDefinitionIndex();
if (!Helpers::isKnife(definitionIndex))
continue;
if (weapon.originalOwnerXuid() != localXuid)
continue;
weapon.accountID() = localInventory.getAccountID();
weapon.itemIDHigh() = std::uint32_t(static_cast<csgo::ItemId>(*itemID) >> 32);
weapon.itemIDLow() = std::uint32_t(static_cast<csgo::ItemId>(*itemID) & 0xFFFFFFFF);
weapon.entityQuality() = 3;
if (definitionIndex != item->gameItem().getWeaponID()) {
definitionIndex = item->gameItem().getWeaponID();
if (const auto def = csgo::ItemSchema::from(retSpoofGadgets->client, memory.itemSystem().getItemSchema()).getItemDefinitionInterface(item->gameItem().getWeaponID())) {
weapon.setModelIndex(engineInterfaces.getModelInfo().getModelIndex(csgo::EconItemDefinition::from(retSpoofGadgets->client, def).getPlayerDisplayModel()));
weapon.getNetworkable().preDataUpdate(0);
}
}
}
const auto viewModel = csgo::Entity::from(retSpoofGadgets->client, clientInterfaces.getEntityList().getEntityFromHandle(local.viewModel()));
if (viewModel.getPOD() == nullptr)
return;
const auto viewModelWeapon = csgo::Entity::from(retSpoofGadgets->client, clientInterfaces.getEntityList().getEntityFromHandle(viewModel.weapon()));
if (viewModelWeapon.getPOD() == nullptr)
return;
const auto def = csgo::ItemSchema::from(retSpoofGadgets->client, memory.itemSystem().getItemSchema()).getItemDefinitionInterface(viewModelWeapon.itemDefinitionIndex());
if (!def)
return;
viewModel.modelIndex() = engineInterfaces.getModelInfo().getModelIndex(csgo::EconItemDefinition::from(retSpoofGadgets->client, def).getPlayerDisplayModel());
const auto worldModel = csgo::Entity::from(retSpoofGadgets->client, clientInterfaces.getEntityList().getEntityFromHandle(viewModelWeapon.weaponWorldModel()));
if (worldModel.getPOD() == nullptr)
return;
worldModel.modelIndex() = engineInterfaces.getModelInfo().getModelIndex(csgo::EconItemDefinition::from(retSpoofGadgets->client, def).getWorldDisplayModel());
}
static void applyWeapons(const inventory_changer::InventoryChanger& inventoryChanger, const csgo::Engine& engine, const ClientInterfaces& clientInterfaces, const OtherInterfaces& interfaces, const Memory& memory, const csgo::CSPlayerInventory& localInventory, const csgo::Entity& local) noexcept
{
const auto localTeam = local.getTeamNumber();
const auto localXuid = local.getSteamId(engine);
const auto itemSchema = csgo::ItemSchema::from(retSpoofGadgets->client, memory.itemSystem().getItemSchema());
const auto highestEntityIndex = clientInterfaces.getEntityList().getHighestEntityIndex();
for (int i = memory.globalVars->maxClients + 1; i <= highestEntityIndex; ++i) {
const auto entity = csgo::Entity::from(retSpoofGadgets->client, clientInterfaces.getEntityList().getEntity(i));
if (entity.getPOD() == nullptr || !entity.isWeapon())
continue;
const auto weapon = entity;
if (weapon.originalOwnerXuid() != localXuid)
continue;
const auto& definitionIndex = weapon.itemDefinitionIndex();
if (Helpers::isKnife(definitionIndex))
continue;
const auto def = itemSchema.getItemDefinitionInterface(definitionIndex);
if (!def)
continue;
const auto loadoutSlot = csgo::EconItemDefinition::from(retSpoofGadgets->client, def).getLoadoutSlot(localTeam);
const auto optionalItem = getItemFromLoadout(inventoryChanger.getBackend().getLoadout(), localTeam, loadoutSlot);
if (!optionalItem.has_value())
continue;
const auto& item = *optionalItem;
if (definitionIndex != item->gameItem().getWeaponID())
continue;
const auto itemID = inventoryChanger.getBackend().getItemID(item);
if (!itemID.has_value())
continue;
weapon.accountID() = localInventory.getAccountID();
weapon.itemIDHigh() = std::uint32_t(static_cast<csgo::ItemId>(*itemID) >> 32);
weapon.itemIDLow() = std::uint32_t(static_cast<csgo::ItemId>(*itemID) & 0xFFFFFFFF);
}
}
static void onPostDataUpdateStart(const inventory_changer::InventoryChanger& inventoryChanger, const EngineInterfaces& engineInterfaces, const ClientInterfaces& clientInterfaces, const OtherInterfaces& interfaces, const Memory& memory, int localHandle) noexcept
{
const auto local = csgo::Entity::from(retSpoofGadgets->client, clientInterfaces.getEntityList().getEntityFromHandle(localHandle));
if (local.getPOD() == nullptr)
return;
const auto localInventory = csgo::CSPlayerInventory::from(retSpoofGadgets->client, memory.inventoryManager.getLocalInventory());
if (localInventory.getPOD() == nullptr)
return;
applyKnife(engineInterfaces, clientInterfaces, interfaces, memory, inventoryChanger.getBackend(), localInventory, local);
applyWeapons(inventoryChanger, engineInterfaces.getEngine(), clientInterfaces, interfaces, memory, localInventory, local);
}
static bool hudUpdateRequired{ false };
static void updateHud(const Memory& memory) noexcept
{
if (auto hud_weapons = memory.findHudElement(memory.hud, "CCSGO_HudWeaponSelection") - WIN32_LINUX(0x28, 62)) {
for (int i = 0; i < *(hud_weapons + WIN32_LINUX(32, 52)); i++)
i = memory.clearHudWeapon(hud_weapons, i);
}
hudUpdateRequired = false;
}
static void applyMusicKit(const Memory& memory, const inventory_changer::backend::BackendSimulator& backend) noexcept
{
if (!localPlayer)
return;
const auto pr = *memory.playerResource;
if (pr == nullptr)
return;
const auto optionalItem = backend.getLoadout().getItemInSlotNoTeam(54);
if (!optionalItem.has_value())
return;
const auto& item = *optionalItem;
if (!item->gameItem().isMusic())
return;
pr->musicID()[localPlayer.get().getNetworkable().index()] = backend.getGameItemLookup().getStorage().getMusicKit(item->gameItem()).id;
}
static void applyPlayerAgent(const inventory_changer::InventoryChanger& inventoryChanger, const csgo::ModelInfo& modelInfo, const ClientInterfaces& clientInterfaces, const OtherInterfaces& interfaces, const Memory& memory) noexcept
{
if (!localPlayer)
return;
const auto optionalItem = getItemFromLoadout(inventoryChanger.getBackend().getLoadout(), localPlayer.get().getTeamNumber(), 38);
if (!optionalItem.has_value())
return;
const auto item = *optionalItem;
if (!item->gameItem().isAgent())
return;
const auto def = csgo::ItemSchema::from(retSpoofGadgets->client, memory.itemSystem().getItemSchema()).getItemDefinitionInterface(item->gameItem().getWeaponID());
if (!def)
return;
const auto model = csgo::EconItemDefinition::from(retSpoofGadgets->client, def).getPlayerDisplayModel();
if (!model)
return;
if (const auto agent = get<inventory_changer::inventory::Agent>(*item)) {
for (std::size_t i = 0; i < agent->patches.size(); ++i) {
if (const auto& patch = agent->patches[i]; patch.patchID != 0)
localPlayer.get().playerPatchIndices()[i] = patch.patchID;
}
}
const auto idx = modelInfo.getModelIndex(model);
localPlayer.get().setModelIndex(idx);
if (const auto ragdoll = csgo::Entity::from(retSpoofGadgets->client, clientInterfaces.getEntityList().getEntityFromHandle(localPlayer.get().ragdoll())); ragdoll.getPOD() != nullptr)
ragdoll.setModelIndex(idx);
}
static void applyMedal(const Memory& memory, const inventory_changer::backend::Loadout& loadout) noexcept
{
if (!localPlayer)
return;
const auto pr = *memory.playerResource;
if (!pr)
return;
const auto optionalItem = loadout.getItemInSlotNoTeam(55);
if (!optionalItem.has_value())
return;
const auto& item = *optionalItem;
if (!item->gameItem().isCollectible() && !item->gameItem().isServiceMedal() && !item->gameItem().isTournamentCoin())
return;
pr->activeCoinRank()[localPlayer.get().getNetworkable().index()] = static_cast<int>(item->gameItem().getWeaponID());
}
struct EquipRequest {
std::chrono::steady_clock::time_point time;
std::uint64_t itemID;
WeaponId weaponID;
std::uint8_t counter = 0;
};
static std::vector<EquipRequest> equipRequests;
static void simulateItemUpdate(const Memory& memory, const EconItemViewFunctions& econItemViewFunctions, std::uint64_t itemID)
{
const auto localInventory = csgo::CSPlayerInventory::from(retSpoofGadgets->client, memory.inventoryManager.getLocalInventory());
if (localInventory.getPOD() == nullptr)
return;
if (const auto view = csgo::EconItemView::from(retSpoofGadgets->client, memory.findOrCreateEconItemViewForItemID(itemID), econItemViewFunctions); view.getPOD() != nullptr) {
if (const auto soc = view.getSOCData())
localInventory.soUpdated(localInventory.getSOID(), (csgo::SharedObjectPOD*)soc, 4);
}
}
static void processEquipRequests(const Memory& memory, const EconItemViewFunctions& econItemViewFunctions)
{
const auto now = std::chrono::steady_clock::now();
for (auto it = equipRequests.begin(); it != equipRequests.end();) {
if (now - it->time >= std::chrono::milliseconds{ 500 }) {
if (it->counter == 0)
simulateItemUpdate(memory, econItemViewFunctions, it->itemID);
it = equipRequests.erase(it);
} else {
++it;
}
}
}
[[nodiscard]] static bool isLocalPlayerMVP(const csgo::Engine& engine, const csgo::GameEvent& event)
{
return localPlayer && localPlayer.get().getUserId(engine) == event.getInt("userid");
}
static bool windowOpen = false;
void inventory_changer::InventoryChanger::menuBarItem() noexcept
{
if (ImGui::MenuItem("Inventory Changer")) {
windowOpen = true;
ImGui::SetWindowFocus("Inventory Changer");
ImGui::SetWindowPos("Inventory Changer", { 100.0f, 100.0f });
}
}
void inventory_changer::InventoryChanger::tabItem(const Memory& memory) noexcept
{
if (ImGui::BeginTabItem("Inventory Changer")) {
drawGUI(memory, true);
ImGui::EndTabItem();
}
}
static ImTextureID getItemIconTexture(const OtherInterfaces& interfaces, std::string_view iconpath) noexcept;
namespace ImGui
{
static bool SkinSelectable(const inventory_changer::InventoryChanger& inventoryChanger, const OtherInterfaces& interfaces, const Memory& memory, const inventory_changer::game_items::Item& item, const ImVec2& iconSizeSmall, const ImVec2& iconSizeLarge, ImU32 rarityColor, int* toAddCount = nullptr) noexcept
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const auto itemName = inventory_changer::WeaponNames::instance(interfaces, memory).getWeaponName(item.getWeaponID()).data();
const auto itemNameSize = CalcTextSize(itemName, nullptr);
const auto paintKitName = getItemName(inventoryChanger.getGameItemLookup().getStorage(), item).forDisplay.data();
const auto paintKitNameSize = CalcTextSize(paintKitName, nullptr);
PushID(itemName);
PushID(paintKitName);
const auto id = window->GetID(0);
PopID();
PopID();
const auto height = ImMax(paintKitNameSize.y, ImMax(itemNameSize.y, iconSizeSmall.y));
const auto rarityBulletRadius = IM_FLOOR(height * 0.2f);
const auto size = ImVec2{ iconSizeSmall.x + rarityBulletRadius * 2.0f + itemNameSize.x + paintKitNameSize.x, height };
ImVec2 pos = window->DC.CursorPos;
pos.y += window->DC.CurrLineTextBaseOffset;
ItemSize(size, 0.0f);
const auto smallIconMin = pos;
const auto smallIconMax = smallIconMin + iconSizeSmall;
const auto rarityBulletPos = ImVec2{ pos.x + iconSizeSmall.x + 5.0f + rarityBulletRadius, pos.y + IM_FLOOR(size.y * 0.5f) };
const auto itemNameMin = ImVec2{ rarityBulletPos.x + rarityBulletRadius + 5.0f, pos.y };
const auto itemNameMax = itemNameMin + ImVec2{ itemNameSize.x, size.y };
const auto separatorHeightInv = IM_FLOOR(height * 0.2f);
const auto separatorMin = ImVec2{ itemNameMax.x + 5.0f, pos.y + separatorHeightInv };
const auto separatorMax = separatorMin + ImVec2{ 1.0f, height - 2.0f * separatorHeightInv };
const auto paintKitNameMin = ImVec2{ separatorMax.x + 5.0f, pos.y };
const auto paintKitNameMax = paintKitNameMin + ImVec2{ paintKitNameSize.x, size.y };
// Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
ImRect bb(pos, pos + ImVec2{ ImMax(size.x, window->WorkRect.Max.x - pos.x), size.y });
const float spacingX = style.ItemSpacing.x;
const float spacingY = style.ItemSpacing.y;
const float spacingL = IM_FLOOR(spacingX * 0.50f);
const float spacingU = IM_FLOOR(spacingY * 0.50f);
bb.Min.x -= spacingL;
bb.Min.y -= spacingU;
bb.Max.x += (spacingX - spacingL);
bb.Max.y += (spacingY - spacingU);
if (!ItemAdd(bb, id))
return false;
const ImRect selectableBB{ bb.Min, ImVec2{ bb.Max.x - 130.0f, bb.Max.y} };
// We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
ImGuiButtonFlags buttonFlags = 0;
bool hovered, held;
bool pressed = false;
ButtonBehavior(selectableBB, id, &hovered, &held, buttonFlags);
// Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard
if (pressed) {
if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent) {
SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent, ImRect(bb.Min - window->Pos, bb.Max - window->Pos));
g.NavDisableHighlight = true;
}
MarkItemEdited(id);
}
if (hovered) {
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
}
if (const auto icon = getItemIconTexture(interfaces, item.getIconPath())) {
window->DrawList->AddImage(icon, smallIconMin, smallIconMax);
if (g.HoveredWindow == window && IsMouseHoveringRect(bb.Min, ImVec2{ bb.Min.x + iconSizeSmall.x, bb.Max.y })) {
BeginTooltip();
Image(icon, iconSizeLarge);
EndTooltip();
}
}
window->DrawList->AddCircleFilled(rarityBulletPos, rarityBulletRadius + 1.0f, IM_COL32(0, 0, 0, (std::min)(120u, (rarityColor & IM_COL32_A_MASK))), 12);
window->DrawList->AddCircleFilled(rarityBulletPos, rarityBulletRadius, rarityColor, 12);
RenderTextClipped(itemNameMin, itemNameMax, itemName, nullptr, &itemNameSize, { 0.0f, 0.5f }, &bb);
if (paintKitName[0] != '\0')
window->DrawList->AddRectFilled(separatorMin, separatorMax, GetColorU32(ImGuiCol_Text));
RenderTextClipped(paintKitNameMin, paintKitNameMax, paintKitName, nullptr, &paintKitNameSize, { 0.0f, 0.5f }, &bb);
if (toAddCount) {
const auto cursorPosNext = window->DC.CursorPos.y;
SameLine(window->WorkRect.Max.x - pos.x - 130.0f);
const auto cursorPosBackup = window->DC.CursorPos.y;
window->DC.CursorPos.y += (size.y - GetFrameHeight()) * 0.5f;
SetNextItemWidth(80.0f);
InputInt("", toAddCount);
*toAddCount = (std::max)(*toAddCount, 1);
window->DC.CursorPosPrevLine.y = cursorPosBackup;
window->DC.CursorPos.y = cursorPosNext;
}
{
const auto cursorPosNext = window->DC.CursorPos.y;
SameLine(window->WorkRect.Max.x - pos.x - 40.0f);
const auto cursorPosBackup = window->DC.CursorPos.y;
window->DC.CursorPos.y += (size.y - GetFrameHeight()) * 0.5f;
pressed = Button("Add");
window->DC.CursorPosPrevLine.y = cursorPosBackup;
window->DC.CursorPos.y = cursorPosNext;
}
if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
CloseCurrentPopup();
return pressed;
}
static void SkinItem(const inventory_changer::InventoryChanger& inventoryChanger, const OtherInterfaces& interfaces, const Memory& memory, const inventory_changer::game_items::Item& item, const ImVec2& iconSizeSmall, const ImVec2& iconSizeLarge, ImU32 rarityColor, bool& shouldDelete) noexcept
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
const ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const auto itemName = inventory_changer::WeaponNames::instance(interfaces, memory).getWeaponName(item.getWeaponID()).data();
const auto itemNameSize = CalcTextSize(itemName, nullptr);
const auto paintKitName = getItemName(inventoryChanger.getGameItemLookup().getStorage(), item).forDisplay.data();
const auto paintKitNameSize = CalcTextSize(paintKitName, nullptr);
PushID(itemName);
PushID(paintKitName);
const auto id = window->GetID(0);
PopID();
PopID();
const auto height = ImMax(paintKitNameSize.y, ImMax(itemNameSize.y, iconSizeSmall.y));
const auto rarityBulletRadius = IM_FLOOR(height * 0.2f);
const auto size = ImVec2{ iconSizeSmall.x + rarityBulletRadius * 2.0f + itemNameSize.x + paintKitNameSize.x, height };
ImVec2 pos = window->DC.CursorPos;
pos.y += window->DC.CurrLineTextBaseOffset;
ItemSize(size, 0.0f);
const auto smallIconMin = pos;
const auto smallIconMax = smallIconMin + iconSizeSmall;
const auto rarityBulletPos = ImVec2{ pos.x + iconSizeSmall.x + 5.0f + rarityBulletRadius, pos.y + IM_FLOOR(size.y * 0.5f) };
const auto itemNameMin = ImVec2{ rarityBulletPos.x + rarityBulletRadius + 5.0f, pos.y };
const auto itemNameMax = itemNameMin + ImVec2{ itemNameSize.x, size.y };
const auto separatorHeightInv = IM_FLOOR(height * 0.2f);
const auto separatorMin = ImVec2{ itemNameMax.x + 5.0f, pos.y + separatorHeightInv };
const auto separatorMax = separatorMin + ImVec2{ 1.0f, height - 2.0f * separatorHeightInv };
const auto paintKitNameMin = ImVec2{ separatorMax.x + 5.0f, pos.y };
const auto paintKitNameMax = paintKitNameMin + ImVec2{ paintKitNameSize.x, size.y };
// Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
ImRect bb(pos, pos + ImVec2{ ImMax(size.x, window->WorkRect.Max.x - pos.x), size.y });
const float spacingX = style.ItemSpacing.x;
const float spacingY = style.ItemSpacing.y;
const float spacingL = IM_FLOOR(spacingX * 0.50f);
const float spacingU = IM_FLOOR(spacingY * 0.50f);
bb.Min.x -= spacingL;
bb.Min.y -= spacingU;
bb.Max.x += (spacingX - spacingL);
bb.Max.y += (spacingY - spacingU);
if (!ItemAdd(bb, id))
return;
if (const bool hovered = (g.HoveredWindow == window && IsMouseHoveringRect(bb.Min, bb.Max))) {
const ImU32 col = GetColorU32(ImGuiCol_HeaderHovered);
RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
}
if (const auto icon = getItemIconTexture(interfaces, item.getIconPath())) {
window->DrawList->AddImage(icon, smallIconMin, smallIconMax);
if (g.HoveredWindow == window && IsMouseHoveringRect(bb.Min, ImVec2{ bb.Min.x + iconSizeSmall.x, bb.Max.y })) {
BeginTooltip();
Image(icon, iconSizeLarge);
EndTooltip();
}
}
window->DrawList->AddCircleFilled(rarityBulletPos, rarityBulletRadius + 1.0f, IM_COL32(0, 0, 0, (std::min)(120u, (rarityColor & IM_COL32_A_MASK))), 12);
window->DrawList->AddCircleFilled(rarityBulletPos, rarityBulletRadius, rarityColor, 12);
RenderTextClipped(itemNameMin, itemNameMax, itemName, nullptr, &itemNameSize, { 0.0f, 0.5f }, &bb);
if (paintKitName[0] != '\0')
window->DrawList->AddRectFilled(separatorMin, separatorMax, GetColorU32(ImGuiCol_Text));
RenderTextClipped(paintKitNameMin, paintKitNameMax, paintKitName, nullptr, &paintKitNameSize, { 0.0f, 0.5f }, &bb);
const auto removeButtonSize = CalcTextSize("Delete", nullptr) + style.FramePadding * 2.0f;
const auto cursorPosNext = window->DC.CursorPos.y;
SameLine(window->WorkRect.Max.x - pos.x - removeButtonSize.x - 7.0f);
const auto cursorPosBackup = window->DC.CursorPos.y;
window->DC.CursorPos.y += (size.y - GetFrameHeight()) * 0.5f;
if (Button("Delete"))
shouldDelete = true;
window->DC.CursorPosPrevLine.y = cursorPosBackup;
window->DC.CursorPos.y = cursorPosNext;
}
}
namespace inventory_changer
{
struct NameComparator {
NameComparator(const game_items::Storage& gameItemStorage, const WeaponNames& weaponNames)
: gameItemStorage{ gameItemStorage }, weaponNames{ weaponNames } {}
[[nodiscard]] bool operator()(const game_items::Item& a, const game_items::Item& b) const
{
if (a.getWeaponID() == b.getWeaponID())
return getItemName(gameItemStorage, a).forSearch < getItemName(gameItemStorage, b).forSearch;
const auto comp = weaponNames.getWeaponNameUpper(a.getWeaponID()).compare(weaponNames.getWeaponNameUpper(b.getWeaponID()));
if (comp == 0)
return a.getWeaponID() < b.getWeaponID();
return comp < 0;
}
private:
const game_items::Storage& gameItemStorage;
const WeaponNames& weaponNames;
};
void InventoryChanger::scheduleHudUpdate() noexcept
{
otherInterfaces.getCvar().findVar(csgo::cl_fullupdate)->changeCallback();
hudUpdateRequired = true;
}
void InventoryChanger::drawGUI(const Memory& memory, bool contentOnly)
{
if (!contentOnly) {
if (!windowOpen)
return;
ImGui::SetNextWindowSize({ 700.0f, 400.0f });
if (!ImGui::Begin("Inventory Changer", &windowOpen, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) {
ImGui::End();
return;
}
}
static std::string filter;
static bool isInAddMode = false;
if (!isInAddMode && ImGui::Button("Add items.."))
isInAddMode = true;
if (!isInAddMode) {
ImGui::SameLine();
if (ImGui::Button("Force Update"))
scheduleHudUpdate();
}
constexpr auto rarityColor = [](EconRarity rarity) noexcept {
constexpr auto rarityColors = std::to_array<ImU32>({
IM_COL32(106, 97, 85, 255),
IM_COL32(176, 195, 217, 255),
IM_COL32( 94, 152, 217, 255),
IM_COL32( 75, 105, 255, 255),
IM_COL32(136, 71, 255, 255),
IM_COL32(211, 44, 230, 255),
IM_COL32(235, 75, 75, 255),
IM_COL32(228, 174, 57, 255)
});
return rarityColors[static_cast<std::size_t>(rarity) < rarityColors.size() ? static_cast<std::size_t>(rarity) : 0];
};
if (isInAddMode) {
if (ImGui::Button("Back")) {
isInAddMode = false;
}
ImGui::SameLine();
ImGui::SetNextItemWidth(550.0f);
const bool filterChanged = ImGui::InputTextWithHint("##search", "Search weapon skins, stickers, knives, gloves, music kits..", &filter);
ImGui::SameLine();
const bool addingAll = ImGui::Button("Add all in list");
constexpr auto passesFilter = []<typename... Strings>(std::wstring_view filter, Strings&&... strings) {
for (const auto filterWord : ranges::views::split(filter, L' ')) {
if ((ranges::search(strings, filterWord).empty() && ...))
return false;
}
return true;
};
static SortFilter gameItemList{ getGameItemLookup().getStorage().getItems() };
if (filterChanged) {
const std::wstring filterWide{ Helpers::ToUpperConverter{}.toUpper(Helpers::toWideString(filter)) };
gameItemList.filter([&passesFilter, &filterWide, &weaponNames = inventory_changer::WeaponNames::instance(otherInterfaces, memory), &gameItemStorage = getGameItemLookup().getStorage()](const inventory_changer::game_items::Item& item) {
return filterWide.empty() || passesFilter(filterWide, weaponNames.getWeaponNameUpper(item.getWeaponID()), getItemName(gameItemStorage, item).forSearch);
});
}
if (ImGui::BeginChild("##scrollarea", ImVec2{ 0.0f, contentOnly ? 400.0f : 0.0f })) {
static std::vector<int> toAddCount(gameItemList.totalItemCount(), 1);
if (static bool sorted = false; !sorted) {
gameItemList.sort(inventory_changer::NameComparator{ getGameItemLookup().getStorage(), inventory_changer::WeaponNames::instance(otherInterfaces, memory) });
sorted = true;
}
for (const auto& [i, gameItem] : gameItemList.getItems()) {
if (addingAll) {
backend.getInventoryHandler().addItem(inventory::Item{ gameItem, backend.getItemGenerator().createDefaultItemProperties(gameItem) }, true);
}
ImGui::PushID(i);
if (ImGui::SkinSelectable(*this, otherInterfaces, memory, gameItem, { 37.0f, 28.0f }, { 200.0f, 150.0f }, rarityColor(gameItem.getRarity()), &toAddCount[i])) {
for (int j = 0; j < toAddCount[i]; ++j)
backend.getInventoryHandler().addItem(inventory::Item{ gameItem, backend.getItemGenerator().createDefaultItemProperties(gameItem) }, true);
toAddCount[i] = 1;
}
ImGui::PopID();
}
}
ImGui::EndChild();
} else {
if (ImGui::BeginChild("##scrollarea2", ImVec2{ 0.0f, contentOnly ? 400.0f : 0.0f })) {
const auto& inventory = backend.getInventory();
std::size_t i = 0;
for (auto it = inventory.rbegin(); it != inventory.rend();) {
if (it->getState() != inventory::Item::State::Default) {
++it;
continue;
}
ImGui::PushID(i);
bool shouldDelete = false;
ImGui::SkinItem(*this, otherInterfaces, memory, it->gameItem(), { 37.0f, 28.0f }, { 200.0f, 150.0f }, rarityColor(it->gameItem().getRarity()), shouldDelete);
if (shouldDelete) {
it = std::make_reverse_iterator(backend.getItemRemovalHandler()(std::next(it).base()));
} else {
++it;
}
ImGui::PopID();
++i;
}
}
ImGui::EndChild();
}
if (!contentOnly)
ImGui::End();
}
}
[[nodiscard]] static bool isDefaultKnifeNameLocalizationString(std::string_view string) noexcept
{
return string == "#SFUI_WPNHUD_Knife" || string == "#SFUI_WPNHUD_Knife_T";
}
static void appendProtobufString(std::string_view string, std::vector<char>& buffer) noexcept
{
assert(string.length() < 128);
buffer.push_back(0x1A);
buffer.push_back(static_cast<char>(string.length()));
std::ranges::copy(string, std::back_inserter(buffer));
}
[[nodiscard]] static std::vector<char> buildTextUserMessage(int destination, std::string_view string1, std::string_view string2, std::string_view string3 = {}) noexcept
{
std::vector<char> buffer{ 0x8, static_cast<char>(destination) };
appendProtobufString(string1, buffer);
appendProtobufString(string2, buffer);
appendProtobufString(string3, buffer);
// game client expects text protobuf to contain 5 strings
appendProtobufString("", buffer);
appendProtobufString("", buffer);
return buffer;
}
static std::uint64_t stringToUint64(std::string_view str) noexcept
{
std::uint64_t result = 0;
std::from_chars(str.data(), str.data() + str.size(), result);
return result;
}
struct Icon {
Texture texture;
int lastReferencedFrame = 0;
};
static std::unordered_map<std::string, Icon> iconTextures;
static ImTextureID getItemIconTexture(const OtherInterfaces& interfaces, std::string_view iconpath) noexcept
{
if (iconpath.empty())
return 0;
auto& icon = iconTextures[std::string{ iconpath }];
if (!icon.texture.get()) {
static int frameCount = 0;
static float timeSpentThisFrame = 0.0f;
static int loadedThisFrame = 0;
if (frameCount != ImGui::GetFrameCount()) {
frameCount = ImGui::GetFrameCount();
timeSpentThisFrame = 0.0f;
// memory->debugMsg("LOADED %d ICONS\n", loadedThisFrame);
loadedThisFrame = 0;
}
if (timeSpentThisFrame > 0.01f)
return 0;
++loadedThisFrame;
const auto start = std::chrono::steady_clock::now();
auto handle = interfaces.getBaseFileSystem().open(("resource/flash/" + std::string{ iconpath } + (iconpath.find("status_icons") != std::string_view::npos ? "" : "_large") + ".png").c_str(), "r", "GAME");
if (!handle)
handle = interfaces.getBaseFileSystem().open(("resource/flash/" + std::string{ iconpath } + ".png").c_str(), "r", "GAME");
assert(handle);
if (handle) {
if (const auto size = interfaces.getBaseFileSystem().size(handle); size > 0) {
const auto buffer = std::make_unique<std::uint8_t[]>(size);
if (interfaces.getBaseFileSystem().read(buffer.get(), size, handle) > 0) {
int width, height;
stbi_set_flip_vertically_on_load_thread(false);
if (const auto data = stbi_load_from_memory((const stbi_uc*)buffer.get(), size, &width, &height, nullptr, STBI_rgb_alpha)) {
icon.texture.init(width, height, data);
stbi_image_free(data);
} else {
assert(false);
}
}
}
interfaces.getBaseFileSystem().close(handle);
}
const auto end = std::chrono::steady_clock::now();
timeSpentThisFrame += std::chrono::duration<float>(end - start).count();
}
icon.lastReferencedFrame = ImGui::GetFrameCount();
return icon.texture.get();
}
void inventory_changer::InventoryChanger::clearItemIconTextures() noexcept
{
iconTextures.clear();
}
void inventory_changer::InventoryChanger::clearUnusedItemIconTextures() noexcept
{
constexpr auto maxIcons = 30;
const auto frameCount = ImGui::GetFrameCount();
while (iconTextures.size() > maxIcons) {
const auto oldestIcon = std::ranges::min_element(iconTextures, {}, [](const auto& icon) { return icon.second.lastReferencedFrame; });
if (oldestIcon->second.lastReferencedFrame == frameCount)
break;
iconTextures.erase(oldestIcon);
}
}
static int remapKnifeAnim(WeaponId weaponID, const int sequence, Helpers::RandomGenerator& randomGenerator) noexcept
{
enum Sequence
{
SEQUENCE_DEFAULT_DRAW = 0,
SEQUENCE_DEFAULT_IDLE1 = 1,
SEQUENCE_DEFAULT_IDLE2 = 2,
SEQUENCE_DEFAULT_LIGHT_MISS1 = 3,
SEQUENCE_DEFAULT_LIGHT_MISS2 = 4,
SEQUENCE_DEFAULT_HEAVY_MISS1 = 9,
SEQUENCE_DEFAULT_HEAVY_HIT1 = 10,
SEQUENCE_DEFAULT_HEAVY_BACKSTAB = 11,
SEQUENCE_DEFAULT_LOOKAT01 = 12,
SEQUENCE_BUTTERFLY_DRAW = 0,
SEQUENCE_BUTTERFLY_DRAW2 = 1,
SEQUENCE_BUTTERFLY_LOOKAT01 = 13,
SEQUENCE_BUTTERFLY_LOOKAT03 = 15,
SEQUENCE_FALCHION_IDLE1 = 1,
SEQUENCE_FALCHION_HEAVY_MISS1 = 8,
SEQUENCE_FALCHION_HEAVY_MISS1_NOFLIP = 9,
SEQUENCE_FALCHION_LOOKAT01 = 12,
SEQUENCE_FALCHION_LOOKAT02 = 13,
SEQUENCE_DAGGERS_IDLE1 = 1,
SEQUENCE_DAGGERS_LIGHT_MISS1 = 2,
SEQUENCE_DAGGERS_LIGHT_MISS5 = 6,
SEQUENCE_DAGGERS_HEAVY_MISS2 = 11,
SEQUENCE_DAGGERS_HEAVY_MISS1 = 12,