-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathAllClass.lua
5618 lines (5181 loc) · 243 KB
/
AllClass.lua
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
LIB_PATH = package.path:gsub("?.lua", "")
SCRIPT_PATH = LIB_PATH:gsub("Common\\", "")
SPRITE_PATH = SCRIPT_PATH:gsub("Scripts", "Sprites"):gsub("/", "\\")
BOL_PATH = SCRIPT_PATH:gsub("Scripts\\", "")
GAME_PATH = package.cpath:sub(1, math.max(package.cpath:find("?.") - 1, 1))
VIP_USER = CLoLPacket and true or false
--Faster for comparison of distances, returns the distance^2
function GetDistanceSqr(p1, p2)
p2 = p2 or player
return (p1.x - p2.x) ^ 2 + ((p1.z or p1.y) - (p2.z or p2.y)) ^ 2
end
function GetDistance(p1, p2)
return math.sqrt(GetDistanceSqr(p1, p2))
end
--p1 should be the BBoxed object
function GetDistanceBBox(p1, p2)
if p2 == nil then p2 = player end
assert(p1 and p1.minBBox and p2 and p2.minBBox, "GetDistanceBBox: wrong argument types (<object><object> expected for p1, p2)")
local bbox1 = GetDistance(p1, p1.minBBox)
return GetDistance(p1, p2) - (bbox1)
end
function ctype(t)
local _type = type(t)
if _type == "userdata" then
local metatable = getmetatable(t)
if not metatable or not metatable.__index then
t, _type = "userdata", "string"
end
end
if _type == "userdata" or _type == "table" then
local _getType = t.type or t.Type or t.__type
_type = type(_getType)=="function" and _getType(t) or type(_getType)=="string" and _getType or _type
end
return _type
end
function ctostring(t)
local _type = type(t)
if _type == "userdata" then
local metatable = getmetatable(t)
if not metatable or not metatable.__index then
t, _type = "userdata", "string"
end
end
if _type == "userdata" or _type == "table" then
local _tostring = t.tostring or t.toString or t.__tostring
if type(_tostring)=="function" then
local tstring = _tostring(t)
t = _tostring(t)
else
local _ctype = ctype(t) or "Unknown"
if _type == "table" then
t = tostring(t):gsub(_type,_ctype) or tostring(t)
else
t = _ctype
end
end
end
return tostring(t)
end
function print(...)
local t, len = {}, select("#",...)
for i=1, len do
local v = select(i,...)
local _type = type(v)
if _type == "string" then t[i] = v
elseif _type == "number" then t[i] = tostring(v)
elseif _type == "table" then t[i] = table.serialize(v)
elseif _type == "boolean" then t[i] = v and "true" or "false"
elseif _type == "userdata" then t[i] = ctostring(v)
else t[i] = _type
end
end
if len>0 then PrintChat(table.concat(t)) end
end
function DumpPacketData(p,s,e)
s, e = math.max(1,s or 1), math.min(p.size-1,e and e-1 or p.size-1)
local pos, data = p.pos, ""
p.pos = s
for i=p.pos, e do
data = data .. string.format("%02X ",p:Decode1())
end
p.pos = pos
return data
end
function DumpPacket(p)
local packet = {}
packet.time = GetInGameTimer()
packet.dwArg1 = p.dwArg1
packet.dwArg2 = p.dwArg2
packet.header = string.format("%02X",p.header)
packet.data = DumpPacketData(p)
return packet
end
function ValidTarget(object, distance, enemyTeam)
local enemyTeam = (enemyTeam ~= false)
return object ~= nil and object.valid and (object.team ~= player.team) == enemyTeam and object.visible and not object.dead and object.bTargetable and (enemyTeam == false or object.bInvulnerable == 0) and (distance == nil or GetDistanceSqr(object) <= distance * distance)
end
function ValidBBoxTarget(object, distance, enemyTeam)
local enemyTeam = (enemyTeam ~= false)
return object ~= nil and object.valid and (object.team ~= player.team) == enemyTeam and object.visible and not object.dead and object.bTargetable and (enemyTeam == false or object.bInvulnerable == 0) and (distance == nil or GetDistanceBBox(object) <= distance)
end
function ValidTargetNear(object, distance, target)
return object ~= nil and object.valid and object.team == target.team and object.networkID ~= target.networkID and object.visible and not object.dead and object.bTargetable and GetDistanceSqr(target, object) <= distance * distance
end
function GetDistanceFromMouse(object)
if object ~= nil and VectorType(object) then return GetDistance(object, mousePos) end
return math.huge
end
local _enemyHeroes
function GetEnemyHeroes()
if _enemyHeroes then return _enemyHeroes end
_enemyHeroes = {}
for i = 1, heroManager.iCount do
local hero = heroManager:GetHero(i)
if hero.team ~= player.team then
table.insert(_enemyHeroes, hero)
end
end
return setmetatable(_enemyHeroes,{
__newindex = function(self, key, value)
error("Adding to EnemyHeroes is not granted. Use table.copy.")
end,
})
end
local _allyHeroes
function GetAllyHeroes()
if _allyHeroes then return _allyHeroes end
_allyHeroes = {}
for i = 1, heroManager.iCount do
local hero = heroManager:GetHero(i)
if hero.team == player.team and hero.networkID ~= player.networkID then
table.insert(_allyHeroes, hero)
end
end
return setmetatable(_allyHeroes,{
__newindex = function(self, key, value)
error("Adding to AllyHeroes is not granted. Use table.copy.")
end,
})
end
--[[
Returns a number that is needed for Animation Drawing Functions.
@param number A time in seconds in which the output goes from 0 to 1
@param number An offset in seconds which will be added to the time to calculate the output
@returns number A number that goes from 0 to 1 in a time interval you've set (0 .. 0,1 ... 0,9 .. 1,0 .. 0 .. 0,1 ...)
]]
function GetDrawClock(time, offset)
time, offset = time or 1, offset or 0
return (os.clock() + offset) % time / time
end
function table.clear(t)
for i, v in pairs(t) do
t[i] = nil
end
end
function table.copy(from, deepCopy)
if type(from) == "table" then
local to = {}
for k, v in pairs(from) do
if deepCopy and type(v) == "table" then to[k] = table.copy(v)
else to[k] = v
end
end
return to
end
end
function table.contains(t, what, member) --member is optional
assert(type(t) == "table", "table.contains: wrong argument types (<table> expected for t)")
for i, v in pairs(t) do
if member and v[member] == what or v == what then return i, v end
end
end
function table.serialize(t, tab, functions)
assert(type(t) == "table", "table.serialize: Wrong Argument, table expected")
local s, len = {"{\n"}, 1
for i, v in pairs(t) do
local iType, vType = type(i), type(v)
if vType~="userdata" and (functions or vType~="function") then
if tab then
s[len+1] = tab
len = len + 1
end
s[len+1] = "\t"
if iType == "number" then
s[len+2], s[len+3], s[len+4] = "[", i, "]"
elseif iType == "string" then
s[len+2], s[len+3], s[len+4] = '["', i, '"]'
end
s[len+5] = " = "
if vType == "number" then
s[len+6], s[len+7], len = v, ",\n", len + 7
elseif vType == "string" then
s[len+6], s[len+7], s[len+8], len = '"', v:unescape(), '",\n', len + 8
elseif vType == "table" then
s[len+6], s[len+7], len = table.serialize(v, (tab or "") .. "\t", functions), ",\n", len + 7
elseif vType == "boolean" then
s[len+6], s[len+7], len = tostring(v), ",\n", len + 7
elseif vType == "function" and functions then
local dump = string.dump(v)
s[len+6], s[len+7], s[len+8], len = "load(Base64Decode(\"", Base64Encode(dump, #dump), "\")),\n", len + 8
end
end
end
if tab then
s[len+1] = tab
len = len + 1
end
s[len+1] = "}"
return table.concat(s)
end
function table.merge(base, t, deepMerge)
for i, v in pairs(t) do
if deepMerge and type(v) == "table" and type(base[i]) == "table" then
base[i] = table.merge(base[i], v)
else base[i] = v
end
end
return base
end
--from http://lua-users.org/wiki/SplitJoin
function string.split(str, delim, maxNb)
-- Eliminate bad cases...
if not delim or delim == "" or string.find(str, delim) == nil then
return { str }
end
maxNb = (maxNb and maxNb >= 1) and maxNb or 0
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gmatch(str, pat) do
nb = nb + 1
if nb == maxNb then
result[nb] = lastPos and string.sub(str, lastPos, #str) or str
break
end
result[nb] = part
lastPos = pos
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
function string.join(arg, del)
return table.concat(arg, del)
end
function string.trim(s)
return s:match'^%s*(.*%S)' or ''
end
function string.unescape(s)
return s:gsub(".",{
["\a"] = [[\a]],
["\b"] = [[\b]],
["\f"] = [[\f]],
["\n"] = [[\n]],
["\r"] = [[\r]],
["\t"] = [[\t]],
["\v"] = [[\v]],
["\\"] = [[\\]],
['"'] = [[\"]],
["'"] = [[\']],
["["] = "\\[",
["]"] = "\\]",
})
end
function math.isNaN(num)
return num ~= num
end
-- Round half away from zero
function math.round(num, idp)
assert(type(num) == "number", "math.round: wrong argument types (<number> expected for num)")
assert(type(idp) == "number" or idp == nil, "math.round: wrong argument types (<integer> expected for idp)")
local mult = 10 ^ (idp or 0)
if num >= 0 then return math.floor(num * mult + 0.5) / mult
else return math.ceil(num * mult - 0.5) / mult
end
end
function math.close(a, b, eps)
assert(type(a) == "number" and type(b) == "number", "math.close: wrong argument types (at least 2 <number> expected)")
eps = eps or 1e-9
return math.abs(a - b) <= eps
end
function math.limit(val, min, max)
assert(type(val) == "number" and type(min) == "number" and type(max) == "number", "math.limit: wrong argument types (3 <number> expected)")
return math.min(max, math.max(min, val))
end
local fps, avgFps, frameCount, fFrame, lastFrame, updateFPS = 0, 0, 0, -math.huge, -math.huge, nil
local function startFPSCounter()
if not updateFPS then
function updateFPS()
fps = 1 / (os.clock() - lastFrame)
lastFrame, frameCount = os.clock(), frameCount + 1
if os.clock() < 0.5 + fFrame then return end
avgFps = math.floor(frameCount / (os.clock() - fFrame))
fFrame, frameCount = os.clock(), 0
end
AddDrawCallback(updateFPS)
end
end
function GetExactFPS()
startFPSCounter()
return fps
end
function GetFPS()
startFPSCounter()
return avgFps
end
--[[
function GetSave
used to save data between matches. It can save all data except userdata, even functions!
what you save in GetSave(name) in one match, you can access next time with the same function call
Example:
GetSave("mySave").print = print
--> nextGame (Or reload)
GetSave("mySave").print("Hello")
]]
local _saves, _initSave = {}, true
function GetSave(name)
local save
if not _saves[name] then
if FileExist(LIB_PATH .. "Saves\\" .. name .. ".save") then
local f = loadfile(LIB_PATH .. "Saves\\" .. name .. ".save")
if type(f) == "function" then
_saves[name] = f()
end
else
_saves[name] = {}
MakeSurePathExists(LIB_PATH .. "Saves\\" .. name .. ".save")
end
end
save = _saves[name]
if not save then
print("SaveFile: " .. name .. " is broken. Reset.")
_saves[name] = {}
save = _saves[name]
end
function save:Save()
local _save, _reload, _clear, _isempty, _remove = self.Save, self.Reload, self.Clear, self.IsEmpty, self.Remove
self.Save, self.Reload, self.Clear, self.IsEmpty, self.Remove = nil, nil, nil, nil, nil
WriteFile(table.concat({"return ",table.serialize(self, nil, true)}), LIB_PATH .. "Saves\\" .. name .. ".save")
self.Save, self.Reload, self.Clear, self.IsEmpty, self.Remove = _save, _reload, _clear, _isempty, _remove
end
function save:Reload()
_saves[name] = loadfile(LIB_PATH .. "Saves\\" .. name .. ".save")()
save = _saves[name]
end
function save:Clear()
for i, v in pairs(self) do
if type(v) ~= "function" or (i ~= "Save" and i ~= "Reload" and i ~= "Clear" and i ~= "IsEmpty" and i ~= "Remove") then
self[i] = nil
end
end
end
function save:IsEmpty()
for i, v in pairs(self) do
if type(v) ~= "function" or (i ~= "Save" and i ~= "Reload" and i ~= "Clear" and i ~= "IsEmpty" and i ~= "Remove") then
return false
end
end
return true
end
function save:Remove()
for i, v in pairs(_saves) do
if v == self then
_saves[i] = nil
end
if FileExist(LIB_PATH .. "Saves\\" .. name .. ".save") then
DeleteFile(LIB_PATH .. "Saves\\" .. name .. ".save")
end
end
end
if _initSave then
_initSave = nil
local function saveAll()
for i, v in pairs(_saves) do
if v and v.Save then
if v:IsEmpty() then
v:Remove()
else
v:Save()
end
end
end
end
AddBugsplatCallback(saveAll)
AddUnloadCallback(saveAll)
AddExitCallback(saveAll)
end
return save
end
--[[
Executes a Powershell script
e.g: successful, output = os.executePowerShell("Write-Host \"PowerShell Executed\"")
]]
function os.executePowerShell(script, argument)
local cmd = ""
script:gsub(".", function(c) cmd = cmd .. c .. "\0" end)
return PopenHidden("powershell " .. (argument or "") .. " -encoded \"" .. Base64Encode(cmd, #cmd) .. "\"")
end
function os.executePowerShellAsync(script, argument)
local cmd = ""
script:gsub(".", function(c) cmd = cmd .. c .. "\0" end)
RunAsyncCmdCommand("powershell -windowstyle hidden " .. (argument or "") .. " -encoded \"" .. Base64Encode(cmd, #cmd) .. "\"")
end
--[[
Brings the League of Legends Window in Foreground. Needed after os.execute or other function that minimize the client.
]]
function SetForeground()
--Written By gReY
local script = [[
Add-Type(@"
using System;
using System.Runtime.InteropServices;
public class User32 {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);}
"@)
$h = (ps "League of Legends").MainWindowHandle;
[User32]::ShowWindowAsync($h,9);
[User32]::SetForegroundWindow($h);]]
os.executePowerShellAsync(script)
end
function PlaySoundPS(path, duration)
os.executePowerShellAsync('(new-object Media.SoundPlayer "' .. path .. '").play();\nfor ($i=1; $i -le ' .. (duration or 1000) .. '; $i++) {Start-Sleep -seconds 1}')
end
function PlayMediaPS(path, duration)
local script = [[$si = new-object System.Diagnostics.ProcessStartInfo;
$si.fileName = "]] .. path .. [[" ;
$si.windowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden;
$process = New-Object System.Diagnostics.Process;
$process.startInfo=$si;
$process.start();
]] .. (duration and ([[start-sleep -seconds ]] .. duration .. [[;
$process.CloseMainWindow();]]) or "")
return os.executePowerShellAsync(script)
end
-- Example: foldernames, filenames = ScanDirectory([[C:\]])
function ScanDirectory(path)
assert(type(path) == "string" and #path > 0, "ScanDirectory: wrong argument types (<string> expected for path)")
path = path and path:gsub([[/]], [[\]]) or BOL_PATH:gsub([[/]], [[\]])
local dirCmd, fileCmd = 'dir /b /a:d-s "' .. path .. '"', 'dir /b /a:-d-s "' .. path .. '"'
local dirs, files = {}, {}
if RunCmdCommand(dirCmd) == 0 then dirs = PopenHidden(dirCmd):trim():split("\n") end
if RunCmdCommand(fileCmd) == 0 then files = PopenHidden(fileCmd):trim():split("\n") end
return dirs, files
end
-- Example: exist = ProcessExist("League of Legends")
--[[function ProcessExist(name)
assert(type(name) == "string" and #name > 0, "ProcessExist: wrong argument types (<string> expected for path)")
name = name:gsub(".exe", "", 1):trim()
return RunCmdCommand('tasklist /FI "IMAGENAME eq ' .. name .. '.exe" 2>NUL | find /I /N "' .. name .. '.exe">NUL') == 0
end]]
--Return text of a file (you can also insert the filename)
function ReadFile(path)
assert(type(path) == "string", "ReadFile: wrong argument types (<string> expected for path)")
local file = io.open(path, "r")
if not file then
file = io.open(SCRIPT_PATH .. path, "r")
if not file then
file = io.open(LIB_PATH .. path, "r")
if not file then return end
end
end
local text = file:read("*all")
file:close()
return text
end
--Return true if could write to file; mode optional
function WriteFile(text, path, mode)
assert(type(text) == "string" and type(path) == "string" and (not mode or type(mode) == "string"), "WriteFile: wrong argument types (<string> expected for text, path and mode)")
local file = io.open(path, mode or "w+")
if not file then
if not MakeSurePathExists(path) then return false end
file = io.open(path, mode or "w+")
if not file then
return false
end
end
file:write(text)
file:close()
return true
end
--Return true if file exists
function FileExist(path)
assert(type(path) == "string", "FileExist: wrong argument types (<string> expected for path)")
local file = io.open(path, "r")
if file then file:close() return true else return false end
end
--takes a path and creates all necessary folders.
function MakeSurePathExists(path)
path = path:gsub("/", "\\"):reverse()
path = path:sub(path:find("\\"), #path)
if not DirectoryExist(path:reverse()) then
path = path:sub(2, #path):split("\\", 2)
if #path == 2 then
if not MakeSurePathExists(path[2]:reverse() .. "\\") or not CreateDirectory(("\\" .. path[1] .. "\\" .. path[2]):reverse()) then
return false
end
else
return DirectoryExist(path[1]:reverse() .. "\\")
end
end
return true
end
function DeleteFile(path)
assert(type(path) == "string", "DeleteFile: wrong argument types (<string> expected for path)")
return os.remove(path) == true
end
function GetFileSize(path)
assert(type(path) == "string", "GetFileSize: wrong argument types (<string> expected for path)")
local file = io.open(path, "r")
if not file then
file = io.open(SCRIPT_PATH .. path, "r")
if not file then
file = io.open(LIB_PATH .. path, "r")
if not file then return end
end
end
local size = file:seek("end")
file:close()
return size
end
function ReadIni(path)
local raw = ReadFile(path)
if not raw then return {} end
local t, section = {}, nil
for _, s in ipairs(raw:split("\n")) do
local v = s:trim()
local commentBegin = v:find(";") or v:find("#")
if commentBegin then v = v:sub(1, commentBegin) end
if v:sub(1, 3) == "tr " then v = v:sub(4, #v) end --ignore
if v:sub(1, 1) == "[" and v:sub(#v, #v) == "]" then --Section
section = v:sub(2, #v - 1):trim()
t[section] = {}
elseif section and v:find("=") then --Key = Value
local kv = v:split("=", 2)
if #kv == 2 then
local key, value = kv[1]:trim(), kv[2]:trim()
if value:lower() == "true" then value = true
elseif value:lower() == "false" then value = false
elseif tonumber(value) then value = tonumber(value)
elseif (value:sub(1, 1) == "\"" and value:sub(#value, #value) == "\"") or
(value:sub(1, 1) == "'" and value:sub(#value, #value) == "'") then
value = value:sub(2, #value - 1):trim()
end
if key ~= "" and value ~= "" then
if section then t[section][key] = value else t[key] = value end
end
end
end
end
return t
end
--[[
Function
GetItem(what)
returns an item.
You can use the English name, the id (recommended) or the Itemslot to get the Item
Example : GetItem(3070), GetItem(ITEM_1), GetItem("Healing Potion")
GetItemDB([callback])
returns a list with all the Items ingame
You can also insert a callback, since it might happen that it has no Items at all,
the first time you start it, since it has to extract all necessary data
Items:
They have the following Properties (and more)
GetName([localization]),GetDescription([localization]),Buy(),Sell(),GetCount(),GetInventorySlot(),GetSprite(),Cast([x,z])
id, icon, gold (total, sell, base), from, into, stats, tags ...
For a more detailed content, look in the items.json in the RAF Archives (Data\Items\items.json), which will be also extracted to BoL\Sprites, if you use this function the first time
You can get your current Localization with the function GetLocalization()
Example:
function OnLoad()
for i, item in pairs(GetItemDB) do
print(item:GetName(GetLocalization()),"\n")
for i, ingredient in pairs(item.from or {}) do
print("\t-> ",ingredient:GetName(GetLocalization()),"\n")
end
end
end
]]
local _items, _itemsLoaded, _onItemsLoaded, _onRafLoaded = {}, false, {}, nil
function GetItem(i)
local item
if type(i) == "number" then
if i >= ITEM_1 and i <= ITEM_7 then
local cItem = player:getItem(i)
item = GetItem(cItem and cItem.id)
else
item = GetItemDB()[i]
end
elseif type(i) == "string" then
for _, v in pairs(GetItemDB()) do
if v:GetName():trim():lower() == i:trim():lower() then item = v break end
end
end
return item, _itemsLoaded
end
function GetItemDB(OnLoaded)
local function ParseItems(RAF)
if _itemsLoaded and not RAF then return end
_itemsLoaded = true
local itemsJSON = RAF and RAF:find("DATA\\Items\\items.json").content or ReadFile(SPRITE_PATH .. "Items\\items.json")
assert(itemsJSON, "GetItemDB: items.json not found. Items couldn't get parsed. "..(RAF and "(Direct)" or "(Cached)"))
itemsJSON = JSON:decode(itemsJSON)
if not RAF and not itemsJSON then
print("GetItemDB: items.json not decoded. Items couldn't get parsed.")
print(DeleteFile(SPRITE_PATH:gsub("/", "\\") .. "Items\\items.json") and "Corrupted File Items\\items.json removed." or "Please remove the file 'items.json' in the folder 'Sprites\\Items\\'")
return
else
assert(itemsJSON, "GetItemDB: items.json not decoded. Items couldn't get parsed. "..(RAF and "(Direct)" or "(Cached)"))
end
local basicItem = itemsJSON.basicitem
for i, itemJSON in pairs(itemsJSON.items) do
if not _items[tonumber(itemJSON.id)] then _items[tonumber(itemJSON.id)] = table.copy(basicItem) end
local item = _items[tonumber(itemJSON.id)]
for j, p in pairs(itemJSON) do
if j == "id" then item[j] = tonumber(p)
elseif j == "into" or j == "from" then
item[j] = {}
for k, id in pairs(itemJSON[j]) do
if not _items[tonumber(id)] then _items[tonumber(id)] = table.copy(basicItem) end
item[j][k] = _items[tonumber(id)]
end
elseif j == "itemgroup" then
local index, content = table.contains(itemsJSON.itemgroups, p, "groupid")
item[j] = { [p] = content }
elseif j == "icon" and RAF then
if not FileExist(SPRITE_PATH .. "Items\\" .. p) then
local file = RAF:find("DATA\\Items\\Icons2D\\" .. p)
if not file or not file.name or file.name == "" then file = RAF:find("DATA\\Items\\Icons2D\\" .. p:gsub(" ", "_")) end
if file and file.name and file.name ~= "" then file:extract(SPRITE_PATH .. "Items\\" .. p)
else OutputDebugString("Item Icon: " .. p .. " hasnt been found")
end
end
item[j] = p
elseif j == "name" or j == "description" then
else
item[j] = p
end
end
end
for i, v in pairs(_items) do
function v:GetName(localization)
localization = localization or "en_US"
local name = self["name_" .. localization]
if not name or name == "" then
self["name_" .. localization] = GetDictionaryString("game_item_displayname_" .. self.id, localization)
return self["name_" .. localization]
else return name
end
end
function v:GetDescription(localization)
localization = localization or "en_US"
local desc = self["desc_" .. localization]
if not desc or desc == "" then
self["desc_" .. localization] = GetDictionaryString("game_item_description_" .. self.id, localization)
return self["desc_" .. localization]
else return desc
end
end
function v:Sell()
local slot = self:GetInventorySlot()
if slot then return SellItem(slot) end
end
function v:Buy()
return BuyItem(self.id)
end
function v:GetCount(object)
local count, ItemSlot = 0, { ITEM_1, ITEM_2, ITEM_3, ITEM_4, ITEM_5, ITEM_6, ITEM_7 }
for i = 1, 7, 1 do
local item = (object or player):getItem(ItemSlot[i])
if item and item.id == self.id then
count = count + math.max(item.stacks or 1, 1)
end
end
return count
end
function v:GetInventorySlot(object)
local ItemSlot = { ITEM_1, ITEM_2, ITEM_3, ITEM_4, ITEM_5, ITEM_6, ITEM_7 }
for i = 1, 7, 1 do
local item = (object or player):getItem(ItemSlot[i])
if item and item.id == self.id then return ItemSlot[i] end
end
end
function v:GetSprite()
if not self.sprite then
self.sprite = self:CreateSprite()
end
return self.sprite
end
function v:CreateSprite()
if self.icon and FileExist(SPRITE_PATH .. "Items\\" .. self.icon) then
return createSprite("Items\\" .. self.icon)
end
end
function v:Cast(x, z)
local slot = self:GetInventorySlot()
if not slot then return end
if x and z then CastSpell(slot, x, z)
elseif x then CastSpell(slot, x)
else CastSpell(slot)
end
end
end
for i, f in pairs(_onItemsLoaded) do
if type(f)=="function" then f(_items) end
_onItemsLoaded[i] = nil
end
end
if not _onRafLoaded then
function _onRafLoaded(RAF)
RAF:find("DATA\\Items\\items.json"):extract(SPRITE_PATH .. "Items\\items.json")
ParseItems(RAF)
end
GetRafFiles(_onRafLoaded)
end
if OnLoaded then
if not _itemsLoaded then table.insert(_onItemsLoaded, OnLoaded)
else OnLoaded(_items, _itemsLoaded) return _items, _itemsLoaded
end
end
if not _itemsLoaded and FileExist(SPRITE_PATH .. "Items\\items.json") then
ParseItems()
end
return _items, _itemsLoaded
end
--[[
Function GetDictionaryString(t,localization)
returns the string of the ingame Dictionary
It might happen that the Dictionary isnt already extracted,
in this case, the second return value is false, and you have to try again later
(This means the Raf Archives haven't already loaded)
You can get your current Localization with the function GetLocalization()
Example: myTranslation = GetDictionaryString("data_dragon_category_rune","de_DE")
The Dictionary Files can be found in the RAF Archives in e.g DATA\Menu\fontconfig_en_US.txt
]]
local _dictionaries = {}
function GetDictionaryString(key, localization)
localization = localization or "en_US"
local _result = ""
local function UpdateLibrary(localization)
local function _onRafLoadedDic(RAF)
local file = RAF:find("DATA\\Menu\\fontconfig_" .. localization .. ".txt")
if file and file.name and file.name ~= "" then
file:extract(LIB_PATH:gsub("/", "\\") .. "Saves\\" .. localization .. ".dic")
_dictionaries[localization] = ReadFile(LIB_PATH .. "Saves\\" .. localization .. ".dic")
end
end
GetRafFiles(_onRafLoadedDic)
end
if not _dictionaries[localization] then
local content = ""
if FileExist(LIB_PATH .. "Saves\\" .. localization .. ".dic") then
content = ReadFile(LIB_PATH .. "Saves\\" .. localization .. ".dic")
end
_dictionaries[localization] = content
UpdateLibrary(localization)
end
local s = _dictionaries[localization]
if s then
local A, B = s:find('\ntr "' .. key .. '" = "', 1, true)
local C, D = s:find('"\n', B, true)
_result = B and C and s:sub(B + 1, C - 1)
end
return _result, (s and true or false)
end
--[[
Returns the Raf-Archive Version
]]
local _rafVersion
function GetRafVersion()
if _rafVersion then return _rafVersion end
local maxVal = 0
for i, v in pairs(ScanDirectory(GAME_PATH:sub(1, GAME_PATH:find("\\RADS")) .. "\\RADS\\projects\\lol_game_client\\filearchives\\")) do
local val = 0
for i, v in pairs(v:split("[.]")) do
val = val + (tonumber(v) or 0) * 1000 ^ i
end
if val > maxVal then
_rafVersion = v:trim()
maxVal = val
end
end
return _rafVersion
end
--[[
Gets the Gamesettings (path: League of Legends\Config\game.cfg
example:
local gameSettings = GetGameSettings()
Width, Height = gameSettings.General.Width, gameSettings.General.Height
]]
function GetGameSettings()
local path = GAME_PATH:sub(1, GAME_PATH:find("\\RADS")) .. "Config\\game.cfg"
return ReadIni(path)
end
--[[
Gets the Localization of your Game. "en_EN", "de_DE" and so on
]]
local _localization
function GetLocalization()
if not _localization then
_localization = FileExist(GAME_PATH .. "DATA\\cfg\\defaults\\locale.cfg") and ReadIni(GAME_PATH .. "DATA\\cfg\\defaults\\locale.cfg").General.LanguageLocaleRegion or "en_EN"
end
return _localization
end
--[[
Delays a function call
example: DelayAction(myFunc, 5)
Note: Due to limitations to BoL
]]
local delayedActions, delayedActionsExecuter = {}, nil
function DelayAction(func, delay, args) --delay in seconds
if not delayedActionsExecuter then
function delayedActionsExecuter()
for t, funcs in pairs(delayedActions) do
if t <= os.clock() then
for _, f in ipairs(funcs) do f.func(table.unpack(f.args or {})) end
delayedActions[t] = nil
end
end
end
AddTickCallback(delayedActionsExecuter)
end
local t = os.clock() + (delay or 0)
if delayedActions[t] then table.insert(delayedActions[t], { func = func, args = args })
else delayedActions[t] = { { func = func, args = args } }
end
end
local _intervalFunction
function SetInterval(userFunction, timeout, count, params)
if not _intervalFunction then
function _intervalFunction(userFunction, startTime, timeout, count, params)
if userFunction(table.unpack(params or {})) ~= false and (not count or count > 1) then
DelayAction(_intervalFunction, (timeout - (os.clock() - startTime - timeout)), { userFunction, startTime + timeout, timeout, count and (count - 1), params })
end
end
end
DelayAction(_intervalFunction, timeout, { userFunction, os.clock(), timeout or 0, count, params })
end
local _DrawText, _PrintChat, _PrintFloatText, _DrawLine, _DrawArrow, _DrawCircle, _DrawRectangle, _DrawLines, _DrawLines2 = DrawText, PrintChat, PrintFloatText, DrawLine, DrawArrow, DrawCircle, DrawRectangle, DrawLines, DrawLines2
function EnableOverlay()
_G.DrawText, _G.PrintChat, _G.PrintFloatText, _G.DrawLine, _G.DrawArrow, _G.DrawCircle, _G.DrawRectangle, _G.DrawLines, _G.DrawLines2 = _DrawText, _PrintChat, _PrintFloatText, _DrawLine, _DrawArrow, _DrawCircle, _DrawRectangle, _DrawLines, _DrawLines2
end
function DisableOverlay()
_G.DrawText, _G.PrintChat, _G.PrintFloatText, _G.DrawLine, _G.DrawArrow, _G.DrawCircle, _G.DrawRectangle, _G.DrawLines, _G.DrawLines2 = function() end, function() end, function() end, function() end, function() end, function() end, function() end, function() end, function() end
end
function QuitGame(timeout)
RunAsyncCmdCommand("cmd /c" .. (timeout and (" ping -n " .. math.floor(timeout) .. " 127.0.0.1>nul &&") or "") .. ' taskkill /im "League of Legends.exe"')
DelayAction(os.exit, (timeout or 0) + 5, { 0 }) --ForceQuit
end
-- return if cursor is under a rectangle
function CursorIsUnder(x, y, sizeX, sizeY)
assert(type(x) == "number" and type(y) == "number" and type(sizeX) == "number", "CursorIsUnder: wrong argument types (at least 3 <number> expected)")
local posX, posY = GetCursorPos().x, GetCursorPos().y
if sizeY == nil then sizeY = sizeX end
if sizeX < 0 then
x = x + sizeX
sizeX = -sizeX
end
if sizeY < 0 then
y = y + sizeY
sizeY = -sizeY
end
return (posX >= x and posX <= x + sizeX and posY >= y and posY <= y + sizeY)
end
--[[
return texted version of a timer(minutes and seconds)
if you want the full time string, use os.date("%H:%M:%S",seconds+82800)
]]
function TimerText(seconds)
seconds = seconds or GetInGameTimer()
if type(seconds) ~= "number" or seconds > 100000 or seconds < 0 then return " ? " end
return string.format("%i:%02i", seconds / 60, seconds % 60)
end
-- return sprite
function GetSprite(file, altFile)
assert(type(file) == "string", "GetSprite: wrong argument types (<string> expected for file)")
if FileExist(SPRITE_PATH .. file) == true then
return createSprite(file)
else
if altFile ~= nil and FileExist(SPRITE_PATH .. altFile) == true then
return createSprite(altFile)
else
PrintChat(file .. " not found (sprites installed ?)")
return createSprite("empty.dds")
end
end
end
--[=[
GetWebSprite(url, [callback, [path]])
returns a sprite from a given website
if no callback is given, it returns it result immediately, if a callback is given, it downloads the sprite asynchrony and returns the sprite in the callback (recommended).
]=]
function GetWebSprite(url, callback, path)
local urlr, sprite = url:reverse(), nil
local filename, env = urlr:sub(1, urlr:find("/") - 1):reverse(), GetCurrentEnv() and GetCurrentEnv().FILE_NAME and GetCurrentEnv().FILE_NAME:gsub(".lua", "") or "WebSprites"
if env and env:lower():sub(1, #("protected")) == "protected" then env = "Protected" end
local filepath = type(path)=="string" and path or (SPRITE_PATH .. env .. "\\" .. filename)
if FileExist(filepath) then
sprite = createSprite(filepath)
if type(callback) == "function" then callback(sprite) end
else
if type(callback) == "function" then
MakeSurePathExists(filepath)