forked from 26F-Studio/Zenitha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
1427 lines (1270 loc) · 45.7 KB
/
init.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
-- # _____ _ _ _ #
-- # / _ / ___ _ __ (_) |_| |__ __ _ #
-- # \// / / _ \ '_ \| | __| '_ \ / _` | #
-- # / //\ __/ | | | | |_| | | | (_| | #
-- # /____/\___|_| |_|_|\__|_| |_|\__,_| #
-- # #
-- > An awesome, deluxe Pure-Lua game/app framework using Love2D, with modules listed below:
--
-- `SCN` (Scene), allow you custom all callback functions for each scene and easily travel between them.
-- ```
-- SCN.add("menu",scene)
-- SCN.go("menu")
-- SCN.go("setting","fastFade")
-- SCN.back()
-- ```
-- `BGM`/`SFX`/`VOC` (Effect/Music/Voice), allow you play audio events simpler.
-- ```
-- BGM.play("bgm1") -- with smooth fade-in/out
-- SFX.play("click")
-- SFX.play("click",0.8,-1,24) -- 80% Vol, left-sided, +2 Oct effect
-- -- Module will automatically create/unload idle resources.
-- ```
-- `BG` (Background), a customizable layer under the scene.
-- ```
-- BG.add("space",bg)
-- BG.setDefault("space")
-- BG.set("galaxy")
-- ```
-- `WIDGET`, interactive widgets layer above the scene, has the highest priority.
--
-- `MSG` (Message), an on-screen print, can be used to show notifications or warnings.
-- ```
-- MSG.new('info',"Techmino is fun!")
-- ```
-- `GC`, extended lib of love.graphics.
-- ```
-- GC.mDraw(); GC.regPolygon();
-- GC.newCamera(); GC.newBezier();
-- GC.stc_setComp('equal',1); GC.stc_rect(0,0,800,600); ...; GC.stc_stop()
-- GC.DO{{'setCL',COLOR.R},{'fRect',0,0,800,600},...}
-- ```
-- `FONT`, set font style & size easily as `GC.setColor`.
-- ```
-- FONT.load{
-- consolas="consola.ttf",
-- pixel="codePixel-Regular.ttf"
-- }
-- FONT.set(20,'consolas')
-- FONT.setDefaultFont('pixel') -- My monospaced coding font: github.com/MrZ626/codePixel
-- FONT.set(26)
-- FONT.setFallback('pixel','consolas')
-- ```
-- `IMG` (Image), allow images to be lazy-loaded after first used.
-- ```
-- IMG.init{
-- bg={"back/1.png","back/2.png","back/3.png"},
-- ...
-- }
-- GC.draw(IMG.bg[1])
-- ```
-- `FILE`, save/load a lua table with one function call like `FILE.save(config,'conf.json')`.
-- ```
-- FILE.save(config,'conf.json') -- Default to json
-- config=FILE.load('conf.json')
-- FILE.save(data,'data.lua','-luaon') -- Support "Luaon" format similar to Json
-- data=FILE.load('data.lua')
-- texts=FILE.load('log.txt','-string')
-- ```
-- `LANG` (Language), an i18n module allow you manage all strings which displayed to players/users.
-- ```
-- LANG.add{en='lang/en.lua',zh='lang/zh.lua'}
-- LANG.setDefault('en')
-- Text=LANG.set('zh')
-- print(Text.hello=="你好")
-- ```
-- `MATH`/`STRING`/`TABLE`, extended libs of standard Lua libs.
-- ```
-- chebyshevDist=MATH.mDist2(0,x1,y1,x2,y2)
-- list=STRING.split("Welcome;to;Zenitha",";") -- {"Welcome","to","Zenitha"}
-- t2=TABLE.copyAll(t1)
-- ```
-- `TASK`, a pseudo-async module allow you run a function asynchronously (as coroutine which must yield itself periodically, be continued once per main loop cycle).
-- ```
-- TASK.lock("signal",2.56)
-- TASK.new(function()
-- repeat yield() until not TASK.getLock("signal")
-- print("Echo from Moon")
-- end)
--
-- function scene.keyDown(k)
-- if k~='escape' then return end
-- if TASK.lock('sureQuit',1) then MSG.new('info',Text.pressAgainToQuit) return end
-- love.event.quit()
-- end
-- ```
-- `TCP`, allow you exchange data much easier then using LuaSocket. (Yet designed for data exchanging with TCP module itself, and using pure json only)
-- ```
-- TASK.new(function() -- Simulate Server
-- TCP.S_start(10026)
-- DEBUG.yieldT(0.26) -- Wait a bit, or getting a nil from TCP:S_receive()
-- print(TCP.S_receive()) -- "Hello server!"
-- end)
-- TASK.new(function() -- Simulate Client
-- TCP.C_connect("127.0.0.1", 10026)
-- TCP.C_send("Hello server!")
-- end)
-- ```
-- `TWEEN`, a simple tweening module allow you making smooth animation with several lines of codes
-- ```
-- TWEEN.new(function(v) Pos=200+100*v end) -- update Pos with v which goes from 0 to 1
-- :setEase('InOutSin') -- with a sine curve
-- :setDuration(2.6) -- in 2.6 seconds
-- :setOnFinish(function() print("FIN") end) -- and print "FIN" when finished
-- :run() -- confirm start
-- ```
-- `PROFILE`, a simple debug tool allow you start/stop profiling anytime, the result will be placed into the clipboard.
--
-- `COLOR`, a set of common color tables which can be used with `COLOR.R` (red), `COLOR.dG` (dark green).
--
-- And some useful utility functions like `ZENITHA.setMaxFPS` `ZENITHA.setDebugInfo` `ZENITHA.setVersionText`.
--
-- Experimental modules:
-- `WAIT`, `DEBUG`, `LOG`, `SYSFX`, `TEXT`, `VIB`, `WHEELMOV`, `REQUIRE`, `HTTP`, `MIDI`
--
-- Exterior modules:
-- `JSON`, json.lua by rxi;
-- `HASH`, sha2.lua by Egor Skriptunoff;
--
-- All ZENITHA module VARs are named in all UPPERCASE.
---@class Zenitha.Main
ZENITHA={}
--------------------------------------------------------------
-- typedef (you need Emmylua to make these things work) (Recommend extension: "Lua" by sumneko)
---@class Set<T>: { [T]:any }
---@class Map<T>: { [any]:T }
---@class Zenitha.Click
---@field x number
---@field y number
---@class Zenitha.Exception
---@field msg table
---@field scene string
---@field shot? love.ImageData
---@class Zenitha.JoystickState
---@field _id number
---@field _jsObj love.Joystick
---@field leftx number
---@field lefty number
---@field rightx number
---@field righty number
---@field triggerleft number
---@field triggerright number
--------------------------------------------------------------
-- #define
local ms,kb=love.mouse,love.keyboard
local MSisDown,KBisDown=ms.isDown,kb.isDown
local gc=love.graphics
local gc_replaceTransform,gc_translate,gc_present=gc.replaceTransform,gc.translate,gc.present
local gc_setColor,gc_circle=gc.setColor,gc.circle
local gc_print,gc_printf=gc.print,gc.printf
local max,min=math.max,math.min
local floor,abs=math.floor,math.abs
math.randomseed(os.time()*2600)
kb.setKeyRepeat(true)
--------------------------------------------------------------
-- Useful global values/variables
---@type table Empty table used as placeholder
NONE=setmetatable({},{__newindex=function() error("NONE: Attempt to modify constant table") end,__metatable=true})
---@type function Empty function used as placeholder
NULL=function(...) end
---@type love.Canvas Empty canvas used as placeholder
PAPER=love.graphics.newCanvas(1,1)
---@type 'macOS'|'Windows'|'Linux'|'Android'|'iOS'
SYSTEM=love.system.getOS():gsub('OS X','macOS')
---@type boolean (NOT RELIABLE) true if the system is Android or iOS
MOBILE=SYSTEM=='Android' or SYSTEM=='iOS'
---@type string Editting text, used by inputBox widget
EDITING=""
---print with formatted string
---@param str string
---@diagnostic disable-next-line
function printf(str,...) print(str:format(...)) end
---error with formatted string
---@param str string
---@diagnostic disable-next-line
function errorf(str,...) error(str:format(...)) end
---assert with formatted string
---@param v any
---@param str string
---@return any
---@diagnostic disable-next-line
function assertf(v,str,...) return v or error(str:format(...)) end
---Use `local require=requirePath(...)` to require modules in simpler way
---@overload fun(loader:function):unknown
---@param path string
function simpRequire(path)
return type(path)=='function' and
function(module) return path(module) end or
function(module) return require(path..module) end
end
-- Inside values
local mainLoopStarted=false
local devMode=false ---@type false|1|2|3|4
local mx,my,mouseShow,cursorSpd=640,360,false,0
local lastClicks={} ---@type Zenitha.Click[]
local jsState={} ---@type Zenitha.JoystickState[]
local errData={} ---@type Zenitha.Exception[]
local bigCanvases=setmetatable({},{
__index=function(self,k)
self[k]=gc.newCanvas(nil,nil,{msaa=select(3,love.window.getMode()).msaa})
return self[k]
end,
})
-- User-changeable values
local appName='Zenitha'
local versionText='V0.1'
local firstScene='_zenitha'
local clickFX=function(x,y) SYSFX.tap(.3,x,y) end
local discardCanvas=false
local showFPS=true
local updateFreq=100
local drawFreq=100
local sleepInterval=1/60
local clickDist2=62
local maxErrorCount=3
local globalEvent={
mouseDown=NULL, -- Able to interrupt scene event
mouseMove=NULL, -- Able to interrupt scene event and widget interaction
mouseUp=NULL, -- Able to interrupt scene event
mouseClick=NULL, -- Able to interrupt scene event
wheelMove=NULL, -- Able to interrupt scene event and widget interaction
touchDown=NULL, -- Able to interrupt scene event
touchUp=NULL, -- Able to interrupt scene event
touchMove=NULL, -- Able to interrupt scene event
touchClick=NULL, -- Able to interrupt scene event
-- Able to interrupt scene event and widget interaction
--
-- Default to a debugging tool, switch on/off with F8, then use it with F1~F12
keyDown=function(key,isRep)
if isRep then return end
if devMode then
if key=='f1' then -- Show system info
local info=("System:%s[%s]\nLuaVer:%s\nJitVer:%s\nJitVerNum:%s"):format(SYSTEM,jit.arch,_VERSION,jit.version,jit.version_num)
print(info); MSG.new('info',info); return true
elseif key=='f2' then -- Quick profiling
local info=PROFILE.switch() and "Profile start!" or "Profile report copied!"
print(info); MSG.new('info',info); return true
elseif key=='f3' then -- Show screen info
local info=table.concat(SCR.info(),"\n")
print(info); MSG.new('info',info); return true
elseif key=='f4' then -- Show everything in _G
for k,v in next,_G do print(k,v) end
MSG.new('info',"_G listed in console")
elseif key=='f5' then -- Show selected widget info
local info=WIDGET.sel and WIDGET.sel:getInfo() or "No widget selected"
print(info); MSG.new('info',info); return true
elseif key=='f6' then -- Show scene stack
local info="Scene stack:"..table.concat(SCN.stack,"->")
print(info); MSG.new('info',info); return true
elseif key=='f7' then -- Open console
if love['_openConsole'] then love['_openConsole']() end
MSG.new('info',"Console opened")
elseif key=='f8' then devMode=false MSG.new('info',"DEBUG OFF",.2); return true
elseif key=='f9' then devMode=1 MSG.new('info',"DEBUG 1 (Basic)"); return true
elseif key=='f10' then devMode=2 MSG.new('info',"DEBUG 2 (Widget)"); return true
elseif key=='f11' then devMode=3 MSG.new('info',"DEBUG 3 (Slow)"); return true
elseif key=='f12' then devMode=4 MSG.new('info',"DEBUG 4 (Sloooow)"); return true
elseif devMode==2 then -- Adjust Widget
local W=WIDGET.sel ---@type table
if not W then return end
local editted
if key=='left' then W.x=W.x-10; editted=true
elseif key=='right' then W.x=W.x+10; editted=true
elseif key=='up' then W.y=W.y-10; editted=true
elseif key=='down' then W.y=W.y+10; editted=true
elseif key==',' then W.w=W.w-10; editted=true
elseif key=='.' then W.w=W.w+10; editted=true
elseif key=='/' then W.h=W.h-10; editted=true
elseif key=="'" then W.h=W.h+10; editted=true
elseif key=='[' then W.fontSize=W.fontSize-5; editted=true
elseif key==']' then W.fontSize=W.fontSize+5; editted=true
end
if editted then
W:reset()
return true
end
end
elseif key=='f8' then
devMode=1
MSG.new('info',"DEBUG 1 (Basic)",.2)
return true
end
end,
keyUp=NULL, -- Able to interrupt scene event
textInput=NULL, -- Able to interrupt scene event and widget interaction
imeChange=NULL, -- Able to interrupt scene event and var `EDIT` updating
gamepadAdd=NULL, -- Able to interrupt gamepad managing
gamepadRemove=NULL, -- Able to interrupt gamepad managing
gamepadAxis=NULL, -- Able to interrupt gamepad managing
gamepadDown=NULL, -- Able to interrupt scene event and widget interaction
gamepadUp=NULL, -- Able to interrupt scene event
fileDrop=NULL, -- Able to interrupt scene event
folderDrop=NULL, -- Able to interrupt scene event
lowMemory=NULL, -- Able to interrupt scene event
resize=NULL, -- Able to interrupt scene event
focus=NULL, -- Able to interrupt scene event
-- System info function (like time and battery power) drawing function (default transform is SCR.xOy_ul)
drawSysInfo=NULL,
-- Cursor drawing function (pass time,x,y as arguments) (Color and line width is uncertain)
drawCursor=function(_,x,y)
gc_setColor(1,1,1)
gc.setLineWidth(2)
gc_circle(MSisDown(1) and 'fill' or 'line',x,y,6)
end,
-- Called when request quiting with ZENITHA._quit()
requestQuit=NULL,
-- Called when exactly before quiting
quit=NULL,
-- When exist, called when love.errorhandler is called. Normally you should handle error with scene named 'error'.
error=false,
}
--------------------------------------------------------------
-- Extended lua basic libraries
MATH= require'Zenitha.mathExtend'
STRING= require'Zenitha.stringExtend'
TABLE= require'Zenitha.tableExtend'
-- Pure lua modules (simple)
COLOR= require'Zenitha.color'
DEBUG= require'Zenitha.debug'
LOG= require'Zenitha.log'
JSON= require'Zenitha.json'
-- Pure lua modules (complex, with update/draw)
LANG= require'Zenitha.languages'
REQUIRE= require'Zenitha.require'
PROFILE= require'Zenitha.profile'
TASK= require'Zenitha.task'
HASH= require'Zenitha.sha2'
-- Love-based modules (simple)
VIB= require'Zenitha.vibrate'
WHEELMOV= require'Zenitha.wheelToArrow'
FONT= require'Zenitha.font'
IMG= require'Zenitha.image'
FILE= require'Zenitha.file'
SCR= require'Zenitha.screen'
GC= require'Zenitha.gcExtend'
TCP= require'Zenitha.tcp'
MIDI= require'Zenitha.midi'
-- Love-based modules (complex, with update/draw)
HTTP= require'Zenitha.http'
SCN= require'Zenitha.scene'
TEXT= require'Zenitha.text'
SYSFX= require'Zenitha.sysFX'
TWEEN= require'Zenitha.tween'
WAIT= require'Zenitha.wait'
MSG= require'Zenitha.message'
BG= require'Zenitha.background'
WIDGET= require'Zenitha.widget'
SFX= require'Zenitha.sfx'
BGM= require'Zenitha.bgm'
VOC= require'Zenitha.voice'
--------------------------------------------------------------
local TASK,HTTP,SCN,SCR,TEXT,SYSFX,TWEEN,WAIT,MSG,BG,WIDGET,VOC=TASK,HTTP,SCN,SCR,TEXT,SYSFX,TWEEN,WAIT,MSG,BG,WIDGET,VOC
local xOy=SCR.xOy
local ITP=xOy.inverseTransformPoint
local setFont=FONT.set
-- Set default font
FONT.load({
_norm='Zenitha/norm.ttf',
_mono='Zenitha/mono.ttf',
})
FONT.setDefaultFont('_norm')
FONT.setDefaultFallback('_norm')
--------------------------------------------------------------
local function _updateMousePos(x,y,dx,dy)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Interrupt by global event
if globalEvent.mouseMove(mx,my,dx,dy)==true then return end
if SCN.mouseMove then SCN.mouseMove(x,y,dx,dy) end
if MSisDown(1) then
WIDGET._drag(x,y,dx,dy)
else
WIDGET._cursorMove(x,y,'move')
end
end
local function _triggerMouseDown(x,y,k,presses)
-- Debug info
if devMode==1 then
if not lastClicks[k] then lastClicks[k]={x=0,y=0} end
print(("(%d,%d)<-%d,%d ~~(%d,%d)<-%d,%d"):format(
x,y,
x-lastClicks[k].x,y-lastClicks[k].y,
floor(x/10)*10,floor(y/10)*10,
floor((x-lastClicks[k].x)/10)*10,floor((y-lastClicks[k].y)/10)*10
))
end
-- Interrupt by scene swapping
if SCN.swapping then return end
WIDGET._cursorMove(x,y,'press')
if WIDGET.sel then
WIDGET._press(x,y,k)
else
-- Skip scene event by global event
if globalEvent.mouseDown(mx,my,k,presses)~=true then
if SCN.mouseDown then SCN.mouseDown(x,y,k,presses) end
end
lastClicks[k]={x=x,y=y}
end
clickFX(x,y)
end
local function mouse_update(dt)
if not KBisDown('lctrl','rctrl') and KBisDown('up','down','left','right') then
local dx,dy=0,0
if KBisDown('up') then dy=dy-cursorSpd end
if KBisDown('down') then dy=dy+cursorSpd end
if KBisDown('left') then dx=dx-cursorSpd end
if KBisDown('right') then dx=dx+cursorSpd end
if dx==0 and dy==0 then return end
mx=max(min(mx+dx,SCR.w0),0)
my=max(min(my+dy,SCR.h0),0)
if my==0 or my==SCR.h0 and dy~=0 then
WIDGET.sel=false
WIDGET._drag(0,0,0,-dy)
end
_updateMousePos(mx,my,dx,dy)
cursorSpd=min(cursorSpd+dt*26,12.6)
else
cursorSpd=6
end
end
local function gp_update(js,dt)
local sx,sy=js._jsObj:getGamepadAxis('leftx'),js._jsObj:getGamepadAxis('lefty')
if abs(sx)>.1 or abs(sy)>.1 then
local dx,dy=0,0
if abs(sy)>.1 then dy=dy+2*sy*cursorSpd end
if abs(sx)>.1 then dx=dx+2*sx*cursorSpd end
if dx==0 and dy==0 then return end
mx=max(min(mx+dx,SCR.w0),0)
my=max(min(my+dy,SCR.h0),0)
if my==0 or my==SCR.h0 then
WIDGET.sel=false
WIDGET._drag(0,0,0,-dy)
end
_updateMousePos(mx,my,dx,dy)
cursorSpd=min(cursorSpd+dt*26,12.6)
else
cursorSpd=6
end
end
---@type love.mousepressed
---@param x number
---@param y number
---@param k? number
---@param touch? boolean
---@param presses? number
function love.mousepressed(x,y,k,touch,presses)
if touch or WAIT.state then return end
mouseShow=true
mx,my=ITP(xOy,x,y)
_triggerMouseDown(mx,my,k,presses)
end
---@type love.mousemoved
---@param x number
---@param y number
---@param dx number
---@param dy number
---@param touch? boolean
function love.mousemoved(x,y,dx,dy,touch)
if touch then return end
mouseShow=true
mx,my=ITP(xOy,x,y)
dx,dy=dx/SCR.k,dy/SCR.k
for k,last in next,lastClicks do
if type(k)=='number' and (x-last.x)^2+(y-last.y)^2>clickDist2 then
lastClicks[k]=nil
end
end
_updateMousePos(mx,my,dx,dy)
end
---@type love.mousereleased
---@param x number
---@param y number
---@param k? number
---@param touch? boolean
---@param presses? number
function love.mousereleased(x,y,k,touch,presses)
if touch or WAIT.state or SCN.swapping then return end
mx,my=ITP(xOy,x,y)
local widgetSel=not not WIDGET.sel
if widgetSel then
WIDGET._release(mx,my,k)
end
-- Skip scene event by global event
if globalEvent.mouseUp(mx,my,k,presses)~=true then
if SCN.mouseUp then SCN.mouseUp(mx,my,k,presses) end
end
if not widgetSel and lastClicks[k] then
local dist=((x-lastClicks[k].x)^2+(y-lastClicks[k].y)^2)^.5
-- Skip scene event by global event
if globalEvent.mouseClick(mx,my,k,dist,presses)~=true then
if SCN.mouseClick then
SCN.mouseClick(mx,my,k,dist,presses)
end
end
end
WIDGET._cursorMove(mx,my,'release')
end
---@type love.wheelmoved
---@param dx number ±1 for each wheel movement
---@param dy number ±1 for each wheel movement
function love.wheelmoved(dx,dy)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Interrupt by global event
if globalEvent.wheelMove(dx,dy)==true then return end
-- Interrupt by scene event
if SCN.wheelMove and SCN.wheelMove(dx,dy)==true then return end
WIDGET._scroll(dx,dy)
end
---@type love.touchpressed
---@param id lightuserdata
---@param x number
---@param y number
---@param _? number dx and dy, ignored because always 0
---@param pressure? number
function love.touchpressed(id,x,y,_,_,pressure)
-- Hide cursor when key pressed
mouseShow=false
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Update mainTouchID
if not SCN.mainTouchID then
SCN.mainTouchID=id
WIDGET.unFocus(true)
love.touchmoved(id,x,y,0,0,pressure)
end
-- Transform to designing coord
x,y=ITP(xOy,x,y)
lastClicks[id]={x=x,y=y}
if WIDGET.sel and WIDGET.sel.type=='inputBox' and not WIDGET.sel:isAbove(x,y) then
WIDGET.unFocus(true)
kb.setTextInput(false)
end
WIDGET._cursorMove(x,y,'press')
WIDGET._press(x,y,1)
-- Skip scene event by global event
if globalEvent.touchDown(x,y,id,pressure)~=true then
if not WIDGET.sel and SCN.touchDown then SCN.touchDown(x,y,id,pressure) end
end
end
---@type love.touchmoved
---@param id lightuserdata
---@param x number
---@param y number
---@param dx number
---@param dy number
---@param pressure? number
function love.touchmoved(id,x,y,dx,dy,pressure)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Transform to designing coord
x,y=ITP(xOy,x,y)
dx,dy=dx/SCR.k,dy/SCR.k
if lastClicks[id] and (x-lastClicks[id].x)^2+(y-lastClicks[id].y)^2>clickDist2 then
lastClicks[id]=nil
end
WIDGET._drag(x,y,dx,dy)
-- Skip scene event by global event
if globalEvent.touchMove(x,y,id,pressure)~=true then
if not WIDGET.sel and SCN.touchMove then SCN.touchMove(x,y,dx,dy,id,pressure) end
end
end
---@type love.touchreleased
---@param id lightuserdata
---@param x number
---@param y number
---@param _? number dx and dy, ignored because always 0
---@param pressure? number
function love.touchreleased(id,x,y,_,_,pressure)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Transform to designing coord
x,y=ITP(xOy,x,y)
if id==SCN.mainTouchID then
WIDGET._release(x,y,id)
WIDGET._cursorMove(x,y,'release')
WIDGET.unFocus()
SCN.mainTouchID=false
end
-- Skip scene event by global event
if globalEvent.touchUp(x,y,id,pressure)~=true then
if SCN.touchUp then SCN.touchUp(x,y,id,pressure) end
end
if lastClicks[id] then
local dist=((x-lastClicks[id].x)^2+(y-lastClicks[id].y)^2)^.5
-- Skip scene event by global event
if globalEvent.touchClick(x,y,id,dist)~=true then
if SCN.touchClick then SCN.touchClick(x,y,id,dist) end
end
clickFX(x,y)
end
end
-- Touch control test
-- function love.mousepressed(x,y,k) if k==1 then love.touchpressed(1,x,y) end end
-- function love.mousereleased(x,y,k) if k==1 then love.touchreleased(1,x,y) end end
-- function love.mousemoved(x,y,dx,dy) if isMsDown(1) then love.touchmoved(1,x,y,dx,dy) end end
---@type love.keypressed
---@param key string
---@param scancode? string
---@param isRep? boolean
function love.keypressed(key,scancode,isRep)
-- Hide cursor when key pressed
if not isRep then mouseShow=false end
-- Interrupt by scene swapping
if SCN.swapping then return end
-- Interrupt by WAIT module
if WAIT.state then
if key=='escape' and WAIT.arg.escapable then WAIT.interrupt() end
return
end
-- Interrupt when typing text
if EDITING~="" then return end
-- Interrupt by global event
if globalEvent.keyDown(key,isRep,scancode)==true then return end
-- Interrupt by scene event
if SCN.keyDown and SCN.keyDown(key,isRep,scancode)==true then return end
-- Widget interaction
local W=WIDGET.sel
if key=='escape' and not isRep then
SCN.back()
elseif key=='up' or key=='down' or key=='left' or key=='right' then
if KBisDown('lctrl','rctrl') then
if W and W.arrowKey then W:arrowKey(key) end
else
mouseShow=true
end
elseif W and W.keypress then
W:keypress(key)
elseif key=='space' or key=='return' then
mouseShow=true
if not isRep then
clickFX(mx,my)
_triggerMouseDown(mx,my,1)
WIDGET._release(mx,my,1)
end
end
end
---@type love.keyreleased
---@param key string
function love.keyreleased(key)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Skip scene event by global event
if globalEvent.keyUp(key)~=true then
if SCN.keyUp then SCN.keyUp(key) end
end
end
---@type love.textinput
---@param texts string
function love.textinput(texts)
-- Interrupt by global event
if globalEvent.textInput(texts)==true then return end
-- Interrupt by scene event
if SCN.textInput and SCN.textInput(texts)==true then return end
WIDGET._textinput(texts)
end
---@type love.textedited
---@param texts string
function love.textedited(texts)
-- Interrupt by global event
if globalEvent.imeChange(texts)==true then return end
-- Interrupt by scene event
if SCN.imeChange and SCN.imeChange(texts)==true then return end
EDITING=texts
end
-- analog sticks: -1, 0, 1 for neg, neutral, pos
-- triggers: 0 for released, 1 for pressed
local jsAxisEventName={
leftx={'leftstick_left','leftstick_right'},
lefty={'leftstick_up','leftstick_down'},
rightx={'rightstick_left','rightstick_right'},
righty={'rightstick_up','rightstick_down'},
triggerleft='triggerleft',
triggerright='triggerright',
}
local gamePadKeys={'a','b','x','y','back','guide','start','leftstick','rightstick','leftshoulder','rightshoulder','dpup','dpdown','dpleft','dpright'}
local dPadToKey={
dpup='up',
dpdown='down',
dpleft='left',
dpright='right',
start='return',
back='escape',
}
---@type love.joystickadded
---@param JS love.Joystick
function love.joystickadded(JS)
-- Interrupt by global event
if globalEvent.gamepadAdd(JS)==true then return end
table.insert(jsState,{
_id=JS:getID(),
_jsObj=JS,
leftx=0,
lefty=0,
rightx=0,
righty=0,
triggerleft=0,
triggerright=0,
})
MSG.new('info',"Joystick added")
end
---@type love.joystickremoved
---@param JS love.Joystick
function love.joystickremoved(JS)
-- Interrupt by global event
if globalEvent.gamepadRemove(JS)==true then return end
for i=1,#jsState do
if jsState[i]._jsObj==JS then
for j=1,#gamePadKeys do
if JS:isGamepadDown(gamePadKeys[j]) then
love.gamepadreleased(JS,gamePadKeys[j])
end
end
love.gamepadaxis(JS,'leftx',0)
love.gamepadaxis(JS,'lefty',0)
love.gamepadaxis(JS,'rightx',0)
love.gamepadaxis(JS,'righty',0)
love.gamepadaxis(JS,'triggerleft',-1)
love.gamepadaxis(JS,'triggerright',-1)
MSG.new('info',"Joystick removed")
table.remove(jsState,i)
break
end
end
end
---@type love.gamepadaxis
---@param JS love.Joystick
---@param axis string
---@param val number
function love.gamepadaxis(JS,axis,val)
-- Interrupt by global event
if globalEvent.gamepadAxis(JS,axis,val)==true then return end
local js
for i=1,#jsState do
if jsState[i]._jsObj==JS then
js=jsState[i]
break
end
end
assert(js,"WTF why js not found")
if axis=='leftx' or axis=='lefty' or axis=='rightx' or axis=='righty' then
local newVal= -- range: [0,1]
val>.4 and 1 or
val<-.4 and -1 or
0
if newVal~=js[axis] then
if js[axis]==-1 then
love.gamepadreleased(JS,jsAxisEventName[axis][1])
elseif js[axis]~=0 then
love.gamepadreleased(JS,jsAxisEventName[axis][2])
end
if newVal==-1 then
love.gamepadpressed(JS,jsAxisEventName[axis][1])
elseif newVal==1 then
love.gamepadpressed(JS,jsAxisEventName[axis][2])
end
js[axis]=newVal
end
elseif axis=='triggerleft' or axis=='triggerright' then
local newVal=val>.3 and 1 or 0 -- range: [0,1]
if newVal~=js[axis] then
if newVal==1 then
love.gamepadpressed(JS,jsAxisEventName[axis])
else
love.gamepadreleased(JS,jsAxisEventName[axis])
end
js[axis]=newVal
end
end
end
---@type love.gamepadpressed
---@param JS love.Joystick
---@param key string
function love.gamepadpressed(JS,key)
-- Hide cursor when gamepad pressed
mouseShow=false
-- Interrupt by scene swapping
if SCN.swapping then return end
-- Interrupt by global event
if globalEvent.gamepadDown(JS,key)==true then return end
local interruptCursor
if SCN.gamepadDown then
interruptCursor=SCN.gamepadDown(key)
elseif SCN.keyDown then
interruptCursor=SCN.keyDown(dPadToKey[key] or key)
end
if not interruptCursor then
key=dPadToKey[key] or key
mouseShow=true
local W=WIDGET.sel
if key=='back' then
SCN.back()
elseif key=='up' or key=='down' or key=='left' or key=='right' then
mouseShow=true
if W and W.arrowKey then W:arrowKey(key) end
elseif key=='return' then
mouseShow=true
clickFX(mx,my)
_triggerMouseDown(mx,my,1)
WIDGET._release(mx,my,1)
else
if W and W.keypress then
W:keypress(key)
end
end
end
end
---@type love.gamepadreleased
---@param JS love.Joystick
---@param key string
function love.gamepadreleased(JS,key)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Skip scene event by global event
if globalEvent.gamepadUp(JS,key)~=true then
if SCN.gamepadUp then
SCN.gamepadUp(key)
elseif SCN.keyUp then
SCN.keyUp(dPadToKey[key] or key)
end
end
end
---@type love.filedropped
---@param file love.DroppedFile
function love.filedropped(file)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Skip scene event by global event
if globalEvent.fileDrop(file)~=true then
if SCN.fileDrop then SCN.fileDrop(file) end
end
end
---@type love.directorydropped
---@param path string
function love.directorydropped(path)
-- Interrupt by scene swapping & WAIT module
if SCN.swapping or WAIT.state then return end
-- Skip scene event by global event
if globalEvent.folderDrop(path)~=true then
if SCN.folderDrop then SCN.folderDrop(path) end
end
end
---@type love.lowmemory
function love.lowmemory()
collectgarbage()
-- Skip scene event by global event
if globalEvent.lowMemory()~=true then
if SCN.lowMemory then SCN.lowMemory() end
end
end
---@type love.resize
---@param w number
---@param h number
function love.resize(w,h)
if SCR.w==w and SCR.h==h then return end
SCR._resize(w,h)
for k in next,bigCanvases do
bigCanvases[k]:release()
bigCanvases[k]=gc.newCanvas()
end
BG._resize(w,h)
-- Skip scene event by global event
if globalEvent.resize(w,h)~=true then
if SCN.resize then SCN.resize(w,h) end
end
WIDGET._reset()
end
---@type love.focus
---@param f boolean
function love.focus(f)
-- Skip scene event by global event
if globalEvent.focus(f)~=true then
if SCN.focus then SCN.focus(f) end
end
end
---@type love.errorhandler
---@param msg string
---@return function #The main loop function
function love.errorhandler(msg)
-- Call global event if exist
if globalEvent.error then return globalEvent.error(msg) end
if type(msg)~='string' then
msg="Unknown error"
elseif msg:find("Invalid UTF-8") then
msg="[Invalid UTF-8] If you are on Windows, try downloading win32 or win64\n(different from what you are using now)."
end
-- Generate error message