forked from thisdp/dgs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.lua
1525 lines (1435 loc) · 45.7 KB
/
utility.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
EnableDGSMemoryLog = false
if EnableDGSMemoryLog then
dgsStartUpMemoryMonitor = {}
function dgsLogLuaMemory()
collectgarbage()
local columns,rows = getPerformanceStats("Lua memory","",getResourceName(getThisResource()))
local debugInfo = debug.getinfo(2)
local src = debugInfo.short_src:gsub("%\\","/")
local res = src:find("/")
src = src:sub(res)
dgsStartUpMemoryMonitor[#dgsStartUpMemoryMonitor+1] = {src,rows[1][3]}
debugInfo = nil
columns = nil
rows = nil
collectgarbage()
end
setTimer(function()
dgsLogLuaMemory()
local last = 0
for i=1,#dgsStartUpMemoryMonitor do
local current = tonumber(dgsStartUpMemoryMonitor[i][2]:sub(1,-4))
print("+"..(current-last).." KB",dgsStartUpMemoryMonitor[i][2],dgsStartUpMemoryMonitor[i][1])
last = current
end
print("Logged "..#dgsStartUpMemoryMonitor.." Times")
end,1000,1)
else
function dgsLogLuaMemory() return end
end
dgsLogLuaMemory()
--------------------------------Events
events = {
"onDgsCursorTypeChange",
"onDgsMouseLeave",
"onDgsMouseEnter",
"onDgsMousePreClick",
"onDgsMouseWheel",
"onDgsMouseClick",
"onDgsMouseClickUp",
"onDgsMouseClickDown",
"onDgsMouseDoubleClick",
"onDgsMouseDoubleClickUp",
"onDgsMouseDoubleClickDown",
"onDgsMouseMultiClick",
"onDgsMouseStay",
"onDgsMouseDown",
"onDgsMouseUp",
"onDgsMouseDrag",
"onDgsMouseMove",
"onDgsWindowClose",
"onDgsPositionChange",
"onDgsSizeChange",
"onDgsTextChange",
"onDgsElementScroll",
"onDgsDestroy",
"onDgsSwitchButtonStateChange",
"onDgsSelectorSelect",
"onDgsGridListSelect",
"onDgsGridListHover",
"onDgsMouseHover",
"onDgsGridListItemDoubleClick",
"onDgsProgressBarChange",
"onDgsCreate",
"onDgsPluginCreate",
"onDgsPreRender",
"onDgsRender",
"onDgsElementRender",
"onDgsElementLeave",
"onDgsElementEnter",
"onDgsElementMove",
"onDgsElementSize",
"onDgsFocus",
"onDgsBlur",
"onDgsKey",
"onDgsTabSelect",
"onDgsTabPanelTabSelect",
"onDgsRadioButtonChange",
"onDgsCheckBoxChange",
"onDgsComboBoxSelect",
"onDgsComboBoxStateChange",
"onDgsEditPreSwitch",
"onDgsEditSwitched",
"onDgsEditAccepted",
"onDgsStopMoving",
"onDgsStopSizing",
"onDgsStopAlphaing",
"onDgsStopAniming",
"onDgsTranslationTableChange",
"onDgsDrop",
"onDgsDrag",
"onDgsStart",
"onDgsPaste", --DGS Paste Handler
"onDgsPropertyChange",
"onDgsFormSubmit",
-------Plugin events
"onDgsRemoteImageLoad",
"onDgsQRCodeLoad",
-------internal events
"DGSI_Paste",
"DGSI_ReceiveIP",
"DGSI_ReceiveQRCode",
"DGSI_ReceiveRemoteImage",
"DGSI_onDebug",
"DGSI_onDebugRequestContext",
"DGSI_onDebugSendContext",
"DGSI_onImport",
-------G2D Hooker events
"onDgsEditAccepted-C",
"onDgsTextChange-C",
"onDgsComboBoxSelect-C",
"onDgsTabSelect-C",
-------
}
local addEvent = addEvent
for i=1,#events do
addEvent(events[i],true)
end
events = nil
local cos,sin,rad,atan2,deg = math.cos,math.sin,math.rad,math.atan2,math.deg
local gsub,sub,len,find,format,byte,char = string.gsub,string.sub,string.len,string.find,string.format,string.byte,string.char
local utf8Len,utf8Byte,utf8Sub = utf8.len,utf8.byte,utf8.sub
local setmetatable,ipairs,pairs = setmetatable,ipairs,pairs
local tableInsert = table.insert
local tableRemove = table.remove
local pi180 = math.pi/180
sW,sH = guiGetScreenSize()
__createElement = createElement
__dxCreateShader = dxCreateShader
__dxCreateFont = dxCreateFont
__dxCreateTexture = dxCreateTexture
__dxDrawImageSection = dxDrawImageSection
__dxDrawImage = dxDrawImage
-------Built-in DX Fonts
fontBuiltIn = {
["default"]=true,
["default-bold"]=true,
["clear"]=true,
["arial"]=true,
["sans"]=true,
["pricedown"]=true,
["bankgothic"]=true,
["diploma"]=true,
["beckett"]=true,
}
-------Built-in Blend Modes
blendModeBuiltIn = {
blend = "blend",
add = "add",
modulate_add = "modulate_add",
overwrite = "overwrite",
}
------Built-in Layers
layerBuiltIn = {
top = true,
center = true,
bottom = true,
}
-------Built-in Easing Functions
easingBuiltIn = {
Linear = true,
InQuad = true,
OutQuad = true,
InOutQuad = true,
OutInQuad = true,
InElastic = true,
OutElastic = true,
InOutElastic = true,
OutInElastic = true,
InBack = true,
OutBack = true,
InOutBack = true,
OutInBack = true,
InBounce = true,
OutBounce = true,
InOutBounce = true,
OutInBounce = true,
SineCurve = true,
CosineCurve = true,
}
-------Built-in Cursor Types
cursorTypesBuiltIn = {
arrow = true,
sizing_ns = true,
sizing_ew = true,
sizing_nwse = true,
sizing_nesw = true,
text = true,
move = true,
pointer = true,
}
-------Can Be Blocked Default Value
g_canBeBlocked = {
checkBuildings = true,
checkVehicles = true,
checkPeds = true,
checkObjects = true,
checkDummies = true,
seeThroughStuff = false,
ignoreSomeObjectsForCamera = false,
}
-------DGS Built-in Texture
DGSBuiltInTex = {
transParent_1x1 = dxCreateTexture(1,1,"dxt5"),
}
-------DEBUG
addCommandHandler("debugdgs",function(command,arg)
local enableDebug = getElementData(resourceRoot,"DGS-enableDebug")
if not enableDebug then return outputChatBox("[DGS]Debug Mode is #FF0000not enabled #FFFFFFon this server",255,255,255,true) end
if not arg or arg == "1" then
debugMode = (not getElementData(localPlayer,"DGS-DEBUG") or arg == "1") and 1 or false
setElementData(localPlayer,"DGS-DEBUG",debugMode,false)
checkDisabledElement = false
outputChatBox("[DGS]Debug Mode "..(debugMode and "#00FF00Enabled" or "#FF0000Disabled"),255,255,255,true)
if not debugMode then
setElementData(localPlayer,"DGS-DEBUG-C",comp,false)
end
elseif arg == "2" then
debugMode = 2
setElementData(localPlayer,"DGS-DEBUG",2,false)
checkDisabledElement = false
outputChatBox("[DGS]Debug Mode "..(debugMode and "#00FF00Enabled ( Mode 2 )"),255,255,255,true)
elseif arg == "3" then
debugMode = 3
setElementData(localPlayer,"DGS-DEBUG",3,false)
setElementData(localPlayer,"DGS-DebugTracer",true,false)
checkDisabledElement = true
outputChatBox("[DGS]Debug Mode "..(debugMode and "#00FF00Enabled ( Mode 3 )"),255,255,255,true)
elseif arg == "c" then
local comp = not getElementData(localPlayer,"DGS-DEBUG-C")
outputChatBox("[DGS]Debug Mode For Compatibility Check "..(comp and "#00FF00Enabled" or "#FF0000Disabled"),255,255,255,true)
setElementData(localPlayer,"DGS-DEBUG-C",comp,false)
end
end)
debugMode = getElementData(localPlayer,"DGS-DEBUG")
checkDisabledElement = debugMode == 3
function dgsSetDebugTracerEnabled(state)
return setElementData(localPlayer,"DGS-DebugTracer",state,false)
end
--------------------------------Element Utility
--------Element Pool
externalElementPool = {}
function dgsPushElement(element,eleType,sRes)
eleType = eleType or dgsGetType(element)
local sourceRes = sRes or sourceResource or resource
externalElementPool[sourceRes] = externalElementPool[sourceRes] or {}
externalElementPool[sourceRes][eleType] = externalElementPool[sourceRes][eleType] or {}
local elePool = externalElementPool[sourceRes][eleType]
elePool[#elePool+1] = element
return true
end
function dgsPopElement(eleType,sRes)
eleType = eleType or dgsGetType(element)
local sourceRes = sRes or sourceResource or resource
externalElementPool[sourceRes] = externalElementPool[sourceRes] or {}
externalElementPool[sourceRes][eleType] = externalElementPool[sourceRes][eleType] or {}
local elePool = externalElementPool[sourceRes][eleType]
local ele = elePool[#elePool]
if not ele then return false end
elePool[#elePool] = nil
return ele
end
--Built in
dgsMaterialType = {
texture = "texture",
shader = "shader",
svg = "texture",
["dgs-dxcanvas"] = "texture",
["render-target-texture"] = "texture",
}
function DGSI_RegisterMaterialType(typeName,sort)
dgsMaterialType[typeName] = sort
end
function isMaterial(ele)
local eleType = dgsGetType(ele)
return dgsMaterialType[eleType] or false
end
dgsElementLogger = {} --0:Empty texture 1:texture; 2:shader
dgsElementKeeper = {}
function dxCreateEmptyTexture(width,height,sRes)
local texture
if sRes ~= false then --Read the data instead of create from path, and create remotely
sRes = sRes or sourceResource
if dgsElementKeeper[sRes] then
local sResRoot = getResourceRootElement(sRes)
dgsTriggerEvent("onDgsRequestCreateRemoteElement",sResRoot,"texture",width,height)
texture = dgsPopElement("texture",sRes)
end
end
if not texture then
texture = __dxCreateTexture(width,height)
dgsElementLogger[texture] = {0,false,texture} --Log internally created texture
addEventHandler("onClientElementDestroy",texture,function()
dgsElementLogger[texture] = nil --Clear logging
end,false)
return texture
else
return texture
end
end
function dxCreateTexture(pathOrData,sRes)
local texture
if sRes ~= false then --Read the data instead of create from path, and create remotely
sRes = sRes or sourceResource
if dgsElementKeeper[sRes] then
local textureData = fileGetContent(pathOrData) or pathOrData
local sResRoot = getResourceRootElement(sRes)
dgsTriggerEvent("onDgsRequestCreateRemoteElement",sResRoot,"texture",textureData)
texture = dgsPopElement("texture",sRes)
end
end
if not texture then
texture = __dxCreateTexture(pathOrData)
if not texture then return false end
dgsElementLogger[texture] = {1,pathOrData,texture} --Log internally created texture
addEventHandler("onClientElementDestroy",texture,function()
dgsElementLogger[texture] = nil --Clear logging
end,false)
return texture
else
return texture
end
end
function dxCreateShader(pathOrData,sRes)
local shader
if sRes ~= false then --Read the data instead of create from path, and create remotely
sRes = sRes or sourceResource
if dgsElementKeeper[sRes] then
local shaderData = fileGetContent(pathOrData) or pathOrData
local sResRoot = getResourceRootElement(sRes)
dgsTriggerEvent("onDgsRequestCreateRemoteElement",sResRoot,"shader",shaderData)
shader = dgsPopElement("shader",sRes)
end
end
if not shader then
shader = __dxCreateShader(pathOrData)
if not shader then return false end
dgsElementLogger[shader] = {2,pathOrData,shader} --Log internally created shader
addEventHandler("onClientElementDestroy",shader,function()
dgsElementLogger[shader] = nil --Clear logging
end,false)
return shader
else
return shader
end
end
--[[
creationInfo
1.path
2.raw data
3.{path/raw data,size,isBold,quality}
]]
function dxCreateFont(creationInfo,sRes)
local pathOrData,font,size,isbold,quality = creationInfo
if type(creationInfo) == "table" then
pathOrData,size,isbold,quality = creationInfo[1],creationInfo[2],creationInfo[3],creationInfo[4]
end
if sRes ~= false then --Read the data instead of create from path, and create remotely
sRes = sRes or sourceResource
if dgsElementKeeper[sRes] then
local sResRoot = getResourceRootElement(sRes)
dgsTriggerEvent("onDgsRequestCreateRemoteElement",sResRoot,"font",pathOrData,size,isbold,quality)
font = dgsPopElement("font",sRes)
end
end
if not font then
font = __dxCreateFont(pathOrData,size,isbold,quality)
if not font then return false end
dgsElementLogger[font] = {3,{pathOrData,size,isbold,quality},font} --Log internally created font
addEventHandler("onClientElementDestroy",font,function()
dgsElementLogger[font] = nil --Clear logging
end,false)
return font
else
return font
end
end
function dgsCreateRenderTarget(w,h,isTransparent,dgsElement,sRes)
local rt
if sRes ~= false then --Create remotely
sRes = sRes or sourceResource
if dgsElementKeeper[sRes] then
local sResRoot = getResourceRootElement(sRes)
dgsTriggerEvent("onDgsRequestCreateRemoteElement",sResRoot,"rendertarget",w,h,isTransparent)
rt = dgsPopElement("rendertarget",sRes)
end
end
local rendertarget = rt or dxCreateRenderTarget(w,h,isTransparent)
if not isElement(rendertarget) then
if w < 1 or h < 1 then return nil end --Pass
local videoMemory = dxGetStatus().VideoMemoryFreeForMTA
local reqSize,reqUnit = getProperUnit(0.0000076*w*h,"MB")
local freeSize,freeUnit = getProperUnit(videoMemory,"MB")
local forWhat = dgsElement and (" for "..dgsGetPluginType(dgsElement)) or ""
return false,"Failed to create render target"..forWhat.." ("..w.."x"..h..") [Expected:"..reqSize..reqUnit.."/Free:"..freeSize..freeUnit.."]"
end
return rendertarget
end
function createElement(eleType,sRes)
local ele
sRes = sRes or sourceResource
if sRes then --Create remotely
if dgsElementKeeper[sRes] then
local sResRoot = getResourceRootElement(sRes)
dgsTriggerEvent("onDgsRequestCreateRemoteElement",sResRoot,eleType)
ele = dgsPopElement(eleType,sRes)
end
end
local ele = ele or __createElement(eleType)
return ele
end
function removeElementData(element,key)
setElementData(element,key,nil)
end
DGSFastEvent = {}
function dgsRegisterFastEvent(eventName,fncName)
if not DGSFastEvent[eventName] then DGSFastEvent[eventName] = {} end
DGSFastEvent[eventName][#DGSFastEvent[eventName]+1] = fncName
return true
end
function dgsRemoveFastEvent(eventName,fncName)
if not DGSFastEvent[eventName] then return false end
return table.removeItemFromArray(DGSFastEvent[eventName],fncName)
end
function dgsTriggerFastEvent(eventName,...)
local eventFunctions = DGSFastEvent[eventName]
if eventFunctions then
for i=1,#eventFunctions do
_G[ eventFunctions[i] ](...)
end
end
end
function dgsAddEventHandler(eventName,element,fncName,...)
if addEventHandler(eventName,element,_G[fncName],...) then
if not dgsElementData[element] then dgsElementData[element] = {} end
local eleData = dgsElementData[element]
if not eleData.eventHandlers then eleData.eventHandlers = {} end
local eventHandlers = eleData.eventHandlers
eventHandlers[#eventHandlers+1] = {eventName,fncName,...} --Log event handler
return true
end
return false
end
function dgsRemoveEventHandler(eventName,element,fncName)
local eventHandlers = dgsElementData[element].eventHandlers
if not eventHandlers then return true end
for i=1,#eventHandlers do
if eventHandlers[i][1] == eventName and eventHandlers[i][2] == fncName then
table.remove(eventHandlers,i)
removeEventHandler(eventName,element,_G[fncName])
return
end
end
return false
end
function dgsTriggerEvent(eventName,element,...)
--Trigger event sometimes changes "sourceResource"
local sRes = sourceResource --Log
local sResRoot = sourceResourceRoot --Log
dgsTriggerFastEvent(eventName,element,...)
local result = true
if isElement(element) then
result = triggerEvent(eventName,element,...)
end
sourceResource = sRes
sourceResourceRoot = sResRoot
return result
end
--------------------------------Table Utility
function table.find(tab,ke,num)
if num then
for k,v in pairs(tab) do
if v[num] == ke then
return k
end
end
else
for k,v in pairs(tab) do
if v == ke then
return k
end
end
end
return false
end
function table.removeItemFromArray(tab,item)
local id
for i=1,#tab do
if tab[i] == item then
id = i
break
end
end
return id and tableRemove(tab,id) or false
end
function table.count(tabl)
local cnt = 0
for k,v in pairs(tabl) do
cnt = cnt + 1
end
return cnt
end
function table.deepcount(tabl)
local cnt = 0
for k,v in pairs(tabl) do
cnt = cnt+1
if type(v) == "table" then
cnt = cnt+table.deepcount(v)
end
end
return cnt
end
function table.merger(...)
local tab = {...}
if #tab > 1 then
local result = {}
for k,v in ipairs(tab) do
if type(v) ~= "table" then
assert(false,"Bad argument @table.merger at argument "..k..",expect table got "..type(v))
return false
end
for _k,_v in pairs(v) do
result[_k] = _v
end
end
return result
else
return tab[1] or false
end
end
function table.complement(theall,...)
assert(type(theall) == "table","Bad argument @table.complement at argument 1,expect table got "..type(theall))
local remove = table.merger(...)
local newtable = {}
for k,v in pairs(theall) do
if not table.find(remove) then
tableInsert(newtable,v)
end
end
return newtable
end
function table.deepcopy(obj)
local InTable = {}
local function Func(obj)
if type(obj) ~= "table" then
return obj
end
local NewTable = {}
InTable[obj] = NewTable
for k,v in pairs(obj) do
NewTable[Func(k)] = Func(v)
end
return setmetatable(NewTable,getmetatable(obj))
end
return Func(obj)
end
function table.shallowCopy(obj)
local InTable = {}
for k,v in pairs(obj) do
InTable[k] = v
end
return InTable
end
function table.getKeys(obj)
local newTable = {}
for k,v in pairs(obj) do
newTable[#newTable+1] = k
end
table.sort(newTable)
return newTable
end
--------------------------------File Utility
function hashFile(fName,exportContent)
local f = fileOpen(fName,true)
local fSize = fileGetSize(f)
local fContent = fileRead(f,fSize)
fileClose(f)
return hash("sha256",fContent),fSize,exportContent and fContent or nil
end
function fileGetContent(fName)
if not fileExists(fName) then return false end
local matched,fileInfo = verifyFile(fName)
if not matched then
triggerServerEvent("DGSI_AbnormalDetected",localPlayer,{[fName]=fileInfo})
return ""
end
local f = fileOpen(fName,true)
local str = fileRead(f,fileGetSize(f))
fileClose(f)
return str
end
--[[
streamer = setmetatable({
readPos = 0,
file = nil,
},{
__index = {
read = function(self,bits)
fileSetPos(self.file,self.readPos)
local str = fileRead(self.file,bits)
self.readPos = self.readPos+bits
return str
end,
getSize = function(self)
return fileGetSize(self.file)
end,
seek = function(self,op,bits)
if op == "set" then
fileSetPos(self.file,bits)
self.readPos = bits
elseif op == "cur" then
self.readPos = self.readPos+bits
fileSetPos(self.file,self.readPos)
elseif op == "end" then
self.readPos = fileGetSize(self.file)+bits
fileSetPos(self.file,self.readPos)
end
return true
end,
open = function(self,fName)
self.file = fileOpen(fName)
end,
close = function(self)
if self.file then fileClose(self.file) end
end,
}
})]]
--------------------------------String Utility
--[[
ASCIIBuffer = {}
for i=0,255 do
ASCIIBuffer[char(i)] = i
ASCIIBuffer[i] = char(i)
end]]
function string.split(s,delim)
local delimLen = len(delim)
if type(delim) ~= "string" or delimLen <= 0 then return false end
local start,index,t = 1,1,{}
while true do
local pos = find(s,delim,start,true)
if not pos then break end
t[index] = sub(s,start,pos-1)
start = pos+delimLen
index = index+1
end
t[index] = sub(s,start)
return t
end
function string.getPath(res,path)
if res and res ~= "global" and res ~= getThisResource() then
path = path:gsub("\\","/")
if not path:find(":") then
path = ":"..getResourceName(res).."/"..path
path = path:gsub("//","/") or path
end
end
return path
end
--[[
0: symbol
1: character
]]
function utf8.getCharType(c)
local cCode = utf8Byte(c)
local cType = 1
if cCode <= 47 then
cType = 0
elseif cCode <= 57 then
cType = 1
elseif cCode <= 64 then
cType = 0
elseif cCode <= 90 then
cType = 1
elseif cCode <= 96 then
cType = 0
elseif cCode <= 122 then
cType = 1
elseif cCode <= 127 then
cType = 0
end
return cType
end
local utf8GetCharType = utf8.getCharType
function dgsSearchFullWordType(text,index,side)
local textLen = utf8Len(text)
if side == 1 then index = index+1 end
local startStr = utf8Sub(text,index,index)
if not startStr or startStr == "" then return 0,textLen end
local startType = utf8GetCharType(startStr)
local frontPos = index
local backPos = index
while true do
frontPos = frontPos-1
if frontPos < 0 then break end
local searchChar = utf8Sub(text,frontPos,frontPos)
if not searchChar or searchChar == "" then break end
if utf8GetCharType(searchChar) ~= startType then break end
end
while true do
backPos = backPos+1
if backPos > textLen then break end
local searchChar = utf8Sub(text,backPos,backPos)
if not searchChar or searchChar == "" then break end
if utf8GetCharType(searchChar) ~= startType then break end
end
return frontPos,backPos-1,startType
end
--------------------------------Math Utility
function findRotation(x1,y1,x2,y2,offsetFix)
local t = -deg(atan2(x2-x1,y2-y1))+offsetFix
return t<0 and t+360 or t
end
function findRotation3D(x1,y1,z1,x2,y2,z2)
local dx = x1-x2
local dy = y1-y2
local rotx = atan2(z2-z1,(dx*dx+dy*dy)^0.5)/pi180
local rotz = -atan2(x2-x1,y2-y1)/pi180
rotz = rotz < 0 and rotz + 360 or rotz
return rotx, 0,rotz
end
function math.clamp(value,n_min,n_max)
--[[if type(value) ~= "number" then
local dbInfo = debug.getinfo(2)
outputDebugString("WARNING: "..dbInfo.short_src..":"..dbInfo.currentline..": Bad argument @math.clamp at argument 1, expect a number, got "..type(value),4,255,128,0)
return false
end
if type(n_min) ~= "number" then
local dbInfo = debug.getinfo(2)
outputDebugString("WARNING: "..dbInfo.short_src..":"..dbInfo.currentline..": Bad argument @math.clamp at argument 2, expect a number, got "..type(n_min),4,255,128,0)
return false
end
if type(n_max) ~= "number" then
local dbInfo = debug.getinfo(2)
outputDebugString("WARNING: "..dbInfo.short_src..":"..dbInfo.currentline..": Bad argument @math.clamp at argument 3, expect a number, got "..type(n_max),4,255,128,0)
return false
end]]
if value <= n_min then
return n_min
elseif value >= n_max then
return n_max
else
return value
end
end
function math.inRange(n_min,n_max,value)
return value >= n_min and value <= n_max
end
function math.lerp(s,a,b)
return a+s*(b-a)
end
function math.seekEmpty(list)
local cnt = 1
while(list[cnt]) do
cnt = cnt+1
end
return cnt
end
function math.c(n,r)
local up,down = 1,1
for i=n-r+1,n do up = up*i end
for i=1,r do down = down*i end
return up/down
end
function math.getBezierPoint(pos,t)
local retX,retY = 0,0
local n = #pos-1
for i=1,n+1 do
local index = i-1
local factor = (t)^index*(1-t)^(n-index)*math.c(n,index)
retX = retX+factor*pos[i][1]
retY = retY+factor*pos[i][2]
end
return retX,retY
end
function getPositionFromElementOffset(element,offX,offY,offZ)
local m = getElementMatrix(element)
return offX*m[1][1]+offY*m[2][1]+offZ*m[3][1]+m[4][1],offX*m[1][2]+offY*m[2][2]+offZ*m[3][2]+m[4][2],offX*m[1][3]+offY*m[2][3]+offZ*m[3][3]+m[4][3]
end
function getRotationMatrix(rx,ry,rz) --Super fast
local rx,ry,rz = rx*pi180,ry*pi180,rz*pi180
local rxCos,ryCos,rzCos,rxSin,rySin,rzSin = cos(rx),cos(ry),cos(rz),sin(rx),sin(ry),sin(rz)
--m11,m12,m13,m21,m22,m23,m31,m32,m33 For extreme performance, using upvalue instead of table
return rzCos*ryCos-rzSin*rxSin*rySin,ryCos*rzSin+rzCos*rxSin*rySin,-rxCos*rySin,-rxCos*rzSin,rzCos*rxCos,rxSin,rzCos*rySin+ryCos*rzSin*rxSin,rzSin*rySin-rzCos*ryCos*rxSin,rxCos*ryCos
end
function getPositionFromOffsetByRotMat(offx,offy,offz,x,y,z,m11,m12,m13,m21,m22,m23,m31,m32,m33)
return offx*m11+offy*m21+offz*m31+x,offx*m12+offy*m22+offz*m32+y,offx*m13+offy*m23+offz*m33+z
end
function dgsFindRotationByCenter(dgsEle,x,y,offsetFix)
local posX,posY = dgsGetElementPositionOnScreen(dgsEle)
local absSize = dgsElementData[dgsEle].absSize
local posX,posY = posX+absSize[1]/2,posY+absSize[2]/2
local rot = findRotation(posX,posY,x,y,offsetFix)
return rot,(x-posX)/absSize[1],(y-posY)/absSize[2]
end
--------------------------------Built-in Utility
HorizontalAlign = {
left = "left",
center = "center",
right = "right",
}
VerticalAlign = {
top = "top",
center = "center",
bottom = "bottom",
}
--------------------------------Color Utility
white = 0xFFFFFFFF
black = 0xFF000000
green = 0xFF00FF00
red = 0xFFFF0000
blue = 0xFF0000FF
yellow = 0xFFFFFF00
function fromcolor(color,relative)
local b = color%256
color = (color-b)/256
local g = color%256
color = (color-g)/256
local r = color%256
color = (color-r)/256
local a = color%256
if relative then
return r/255,g/255,b/255,a/255
end
return r,g,b,a
end
function getColorAlpha(color)
color = color%0x100000000
local a = (color-color%0x1000000)/0x1000000
return a-a%1
end
function setColorAlpha(color,alpha)
color = color%0x100000000
alpha = alpha-alpha%1
return color%0x1000000+alpha*0x1000000
end
function applyColorAlpha(color,alpha)
color = color%0x100000000
local rgb = color%0x1000000
local a = (color-rgb)/0x1000000*alpha
a = a-a%1
return rgb+a*0x1000000
end
function interpolateColor(colorA,colorB,s) --From, To, Percent
local cAr,cAg,cAb,cAa
local cBr,cBg,cBb,cBa
local r,g,b,a
cAb = colorA%256
colorA = (colorA-cAb)/256
cAg = colorA%256
colorA = (colorA-cAg)/256
cAr = colorA%256
colorA = (colorA-cAr)/256
cAa = colorA%256
cBb = colorB%256
colorB = (colorB-cBb)/256
cBg = colorB%256
colorB = (colorB-cBg)/256
cBr = colorB%256
colorB = (colorB-cBr)/256
cBa = colorB%256
a = cAa+(cBa-cAa)*s
r = cAr+(cBr-cAr)*s
g = cAg+(cBg-cAg)*s
b = cAb+(cBb-cAb)*s
a = a-a%1
r = r-r%1
g = g-g%1
b = b-b%1
return a*0x1000000+r*0x10000+g*0x100+b
end
--HSL and HSV are not the same thing, while HSB is the same as HSV...
function HSL2RGB(H,S,L)
local H,S,L = H/360,S/100,L/100
local R,G,B
if S == 0 then
R,G,B = L,L,L
else
local var2 = (L < 0.5) and L*(1+S) or L+S-S*L
local var1 = 2*L-var2
R = HUE2RGB(var1,var2,H+(1/3))
G = HUE2RGB(var1,var2,H)
B = HUE2RGB(var1,var2,H-(1/3))
end
return R*255,G*255,B*255
end
function HUE2RGB(v1,v2,vH)
if vH < 0 then
vH = vH+1
elseif vH > 1 then
vH = vH-1
end
if 6*vH < 1 then
return v1+(v2-v1)*6*vH
elseif 2*vH < 1 then
return v2
elseif 3*vH < 2 then
return v1+(v2-v1)*((2/3)-vH)*6
end
return v1
end
function RGB2HSL(R,G,B)
local R,G,B = R/255,G/255,B/255
local min,max = math.min(R,G,B),math.max(R,G,B)
local delta = max-min
local L,H,S = (max+min)/2,0,0
if delta ~= 0 then
S = L < 0.5 and delta/(max+min) or delta/(2-max-min)
local dR,dG,dB = ((max-R)/6+delta/2)/delta,((max-G)/6+delta/2)/delta,((max-B)/6+delta/2)/delta
if R == max then
H = dB-dG
elseif G == max then
H = (1/3)+dR-dB
else
H = (2/3)+dG-dR
end
if H < 0 then
H = H+1
elseif H > 1 then
H = H-1
end
end
return H*360,S*100,L*100 --{0~360,0~100,0~100} H,S,L
end
function RGB2HSV(R,G,B)
local R,G,B = R/255,G/255,B/255
local min,max = math.min(R,G,B),math.max(R,G,B)
local V,H,S,delta = max,0,0,max - min
S = max == 0 and 0 or delta / max
local dR = R/6
local dG = G/6
local dB = B/6
if R == max then
H = dB-dG
elseif G == max then
H = (1/3)+dR-dB
else
H = (2/3)+dG-dR
end
if H < 0 then
H = H+1
elseif H > 1 then