-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
4180 lines (3818 loc) · 163 KB
/
Copy pathmain.lua
File metadata and controls
4180 lines (3818 loc) · 163 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
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
-- zip test2
return function(mod)
print("[Gen2Online] Initializing online MMO (Gen1Online port for Gen2Recomp)...")
local function loadLocal(mod, relative)
local source = assert(mod:read(relative), "missing " .. relative)
local chunk, err = load(source, "@" .. (mod.path or "mod") .. "/" .. relative)
assert(chunk, err)
return chunk()
end
-- Must load before any SaveData/Overworld hooks (boot calls newGame during Game:load)
local Gen2Compat = loadLocal(mod, "gen2_compat.lua")
local Quests = loadLocal(mod, "quests/init.lua")(loadLocal, mod)
local NPCs = loadLocal(mod, "npcs/init.lua")(loadLocal, mod)
-- Register quest item defs into game data when available (Gen1 + Gen2 relics)
local function ensureQuestItems()
local ok, G = pcall(require, "src.core.Game")
if ok and G and Quests and Quests.registerItems then
pcall(Quests.registerItems, G)
end
end
ensureQuestItems()
local Game = require("src.core.Game")
local Input = require("src.core.Input")
local OverworldState = require("src.world.OverworldController")
-- Gen2Recomp Phase 2B still defaults new games to REDS_HOUSE_2F / Pallet.
local origOwEnter = OverworldState.enter
if origOwEnter then
OverworldState.enter = function(self, mapId, x, y, facing)
local GC = Gen2Compat
if not GC then
local ok, mod = pcall(require, "src.core.GameVersion")
-- Gen2Compat always provided by this mod; skip if missing
end
if GC and GC.isGen2 and GC.isGen2() then
local sp = GC.defaultSpawn()
local mid = tostring(mapId or "")
if mid == "" or (GC.isKantoBootMap and GC.isKantoBootMap(mid)) then
mapId, x, y, facing = sp.map, sp.x, sp.y, sp.facing or "down"
end
if Game and Game.save then
GC.ensureGen2Start(Game.save, nil, { force = (GC.isKantoBootMap and GC.isKantoBootMap(mid)), data = Game.data })
end
end
return origOwEnter(self, mapId, x, y, facing)
end
end
pcall(function()
local SaveData = require("src.core.SaveData")
if SaveData and SaveData.newGame and not SaveData._gen2onlineStartHooked then
local origNewGame = SaveData.newGame
SaveData.newGame = function(boot)
local save = origNewGame(boot)
local GC = Gen2Compat
if GC and GC.isGen2 and GC.isGen2() and save then
GC.ensureGen2Start(save, nil, { force = true, data = (Game and Game.data) })
end
return save
end
SaveData._gen2onlineStartHooked = true
end
end)
local BattleState = require("src.battle.BattleState")
local LinkBattle = require("src.link.LinkBattle")
local Protocol = require("src.link.Protocol")
local Party = require("src.pokemon.Party")
local Boxes = require("src.pokemon.Boxes")
local Collision = require("src.world.Collision")
local Font = require("src.render.Font")
local Menu = require("src.ui.Menu")
local TextBox = require("src.render.TextBox")
local Net = require("src.link.Net")
local CodeEntry = require("src.link.CodeEntry")
local NPC = require("src.world.NPC")
local SpriteRenderer = require("src.render.SpriteRenderer")
local Pokemon = require("src.pokemon.Pokemon")
local Json = require("src.link.Json")
-- Gen2 DayCare: award a little online XP when withdrawing a raised mon / egg path
pcall(function()
local DayCare = require("src.pokemon.DayCare")
if DayCare and DayCare.withdraw and not DayCare._gen2onlineHooked then
local origWithdraw = DayCare.withdraw
DayCare.withdraw = function(save, which)
local mon = origWithdraw(save, which)
if mon and isGtsServerConnected and addMmoXp then
pcall(addMmoXp, Game, "breeding", 40)
end
return mon
end
DayCare._gen2onlineHooked = true
end
end)
local Strings = pcall(require, "src.core.Strings") and require("src.core.Strings") or function(s) return s end
-- Socket HTTP/HTTPS modules for 24/7 GTS REST Server & Cloudflare Tunnel
local hasSocketHttp, http = pcall(require, "socket.http")
if not hasSocketHttp then http = nil end
local hasHttps, https = pcall(require, "ssl.https")
if not hasHttps then https = nil end
local hasLtn12, ltn12 = pcall(require, "ltn12")
if not hasLtn12 then ltn12 = nil end
-- Direct Cloudflare Tunnel URL
local GTS_SERVER_URL = "https://gts.cedricslabs.com"
_G.GTS_SERVER_URL = GTS_SERVER_URL
local isGtsServerConnected = false -- Explicit manual connection required via menu
-- Lock Game Speed strictly to 1X whenever online and connected to the server to prevent desyncs
local origLogicSpeed = Game.logicSpeed
Game.logicSpeed = function(self)
if isGtsServerConnected then
return 1
end
if origLogicSpeed then return origLogicSpeed(self) end
return 1
end
-- Networking State
local netSession = nil
local isHost = false
local roomCode = nil
local lastSendTime = 0
local lastPlayerX = nil
local lastPlayerY = nil
local lastPlayerMap = nil
local activeBattleAdapter = nil
local activeParty = nil
local pendingPartyInvite = nil
local lastPartySyncTime = 0
local openPartyMainMenu = nil
-- Active GtsNetAdapter instance
local isWaitingForChallenge = false -- Locks player movement while waiting for challenge response
local challengeWaitTimer = 0
local lastBattleEndTime = -999 -- Cooldown: ignore challenges for 5s after battle ends
local inBattle = false -- Guard: prevents double-starting a battle from duplicate messages
local clientSessionId = string.format("%08x%08x", love.math.random(10000000, 99999999), os.time())
-- MMO Multi-Player NPC Registry (trainerId -> NPC object)
local netNpcs = {} -- trainerId -> human NPC object
local netFollowers = {} -- trainerId -> follower NPC object
local netPlayerMap = {} -- trainerId -> player raw position data
-- Custom Trainer Profile State & MMO Leveling Engine (1 to 100)
local localTrainerTitle = "ACE TRAINER"
local localFavoriteMon = Gen2Compat.defaultFavorite and Gen2Compat.defaultFavorite() or "CHARIZARD"
local mmoLevel = 1
local mmoXp = 0
local mmoToken = nil
-- Resolved to a *loadable* sheet on first Player.new / applyPlayerSprite
local localSelectedSprite = nil
-- Leveling Curve Calculation: starts fast, slows down gradually
local function calculateXpForLevel(lvl)
if lvl <= 1 then return 0 end
return math.floor(50 * ((lvl - 1) ^ 1.8))
end
local function calculateLevelFromXp(xp)
if xp <= 0 then return 1 end
for lvl = 100, 1, -1 do
if xp >= calculateXpForLevel(lvl) then
return lvl
end
end
return 1
end
local AVAILABLE_AVATARS = Gen2Compat.avatarList()
-- Global Trade Station (GTS) Database
_G.GEN1ONLINE_GTS = _G.GEN1ONLINE_GTS or {
listings = {}, -- listingId -> listing object
user_counts = {}, -- trainerId -> active deposit count
history = {}, -- array of last 50 trade receipts
claim_boxes = {}, -- trainerId -> list of completed traded mons
next_id = 1001,
}
local gtsDb = _G.GEN1ONLINE_GTS
-- TRUE ASYNCHRONOUS BACKGROUND THREADING ENGINE (love.thread)
-- Pos-sync channel: flush-all, keep newest (stale positions discarded)
local netOutChannel = _G.love and _G.love.thread and _G.love.thread.getChannel("gen1mmo_out")
local netInChannel = _G.love and _G.love.thread and _G.love.thread.getChannel("gen1mmo_in")
-- Battle channel: FIFO, every message delivered (moves cannot be dropped)
local battleOutChannel = _G.love and _G.love.thread and _G.love.thread.getChannel("gen1mmo_battle_out")
local battleInChannel = _G.love and _G.love.thread and _G.love.thread.getChannel("gen1mmo_battle_in")
-- Debug channel for thread errors
local debugChannel = _G.love and _G.love.thread and _G.love.thread.getChannel("gen1mmo_debug")
local bgThread = nil
-- Capture package paths for the thread
local threadPackagePath = package.path
local threadPackageCpath = package.cpath
-- Escape backslashes to avoid invalid escape sequences in the thread code string literal
local escapedPath = string.gsub(threadPackagePath, "\\", "\\\\")
local escapedCpath = string.gsub(threadPackageCpath, "\\", "\\\\")
-- Remote NPC count logging timer
local remoteCountLogTime = 0
local threadCode = [[
-- Inject main thread's package paths (backslashes escaped)
package.path = "]] .. escapedPath .. [["
package.cpath = "]] .. escapedCpath .. [["
require("love.timer")
local http = pcall(require, "socket.http") and require("socket.http") or nil
local https = pcall(require, "ssl.https") and require("ssl.https") or nil
local ltn12 = pcall(require, "ltn12") and require("ltn12") or nil
local socket = pcall(require, "socket") and require("socket") or nil
local outChan = love.thread.getChannel("gen1mmo_out")
local inChan = love.thread.getChannel("gen1mmo_in")
local battleOutChan = love.thread.getChannel("gen1mmo_battle_out")
local battleInChan = love.thread.getChannel("gen1mmo_battle_in")
local debugChan = love.thread.getChannel("gen1mmo_debug")
local function doPost(url, body)
local resp_body = {}
local fn = (url:sub(1,5)=="https" and https) and https.request or (http and http.request)
-- Ensure every background POST body carries modVersion (avoids false VERSION_MISMATCH)
if body and type(body) == "string" and #body > 2 and not body:find('"modVersion"') then
if body:sub(-1) == "}" then
body = body:sub(1, -2) .. ',"modVersion":"0.7.0-gen2","version":"0.7.0-gen2"}'
end
end
-- Gold/Silver clients must advertise generation=2 or they vanish from Gen2 player lists
if body and type(body) == "string" and body:find('"sync_pos"') and not body:find('"generation"') then
if body:sub(-1) == "}" then
body = body:sub(1, -2) .. ',"generation":2}'
end
end
if fn and ltn12 then
local ok, err = pcall(fn, {
url = url, method = "POST",
headers = { ["Content-Type"]="application/json",
["Content-Length"]=tostring(#body),
["X-Mod-Version"]="0.7.0-gen2" },
source = ltn12.source.string(body),
sink = ltn12.sink.table(resp_body),
timeout = 3.5
})
if not ok then
debugChan:push("HTTP POST error: " .. tostring(err))
return ""
end
else
debugChan:push("HTTP libraries not loaded (http=" .. tostring(http) .. ", https=" .. tostring(https) .. ", ltn12=" .. tostring(ltn12) .. ")")
return ""
end
return table.concat(resp_body)
end
while true do
-- 1. BATTLE channel:
-- send_battle_msg: FIFO — every send must be delivered
-- poll_battle_msgs: keep-newest — old polls are stale, discard them
local fifoSends = {}
local newestPoll = nil
local bReq = battleOutChan:pop()
while bReq do
if bReq.keepNewest then
newestPoll = bReq -- discard older polls, keep only latest
else
table.insert(fifoSends, bReq) -- must deliver every send
end
bReq = battleOutChan:pop()
end
-- Process sends first (order matters)
for _, req in ipairs(fifoSends) do
local resp = doPost(req.url, req.body)
if #resp > 0 then battleInChan:push(resp) end
end
-- Then process newest poll only (after all sends are done)
if newestPoll then
local resp = doPost(newestPoll.url, newestPoll.body)
if #resp > 0 then battleInChan:push(resp) end
end
-- 2. POSITION-SYNC channel: flush all, keep only the newest
local req = nil
local nxt = outChan:pop()
while nxt do req = nxt; nxt = outChan:pop() end
if req then
local resp = doPost(req.url, req.body)
if #resp > 0 then inChan:push(resp) end
end
if socket and socket.sleep then
socket.sleep(0.008)
elseif love and love.timer and love.timer.sleep then
love.timer.sleep(0.008)
end
end
]]
if _G.love and _G.love.thread then
pcall(function()
bgThread = _G.love.thread.newThread(threadCode)
bgThread:start()
end)
end
-- Optional: print debug messages from thread (call occasionally in love.update)
local function printThreadDebug()
if debugChannel then
local msg = debugChannel:pop()
while msg do
print("[Thread Debug] " .. tostring(msg))
msg = debugChannel:pop()
end
end
end
-- Universal Transport Helper
local function makeHttpRequest(reqTable)
reqTable.timeout = reqTable.timeout or 0.5
if reqTable.url:sub(1, 5) == "https" and https then
local ok, res, code, headers, status = pcall(https.request, reqTable)
if ok and code then return ok, res, code, headers, status end
end
if http then
return pcall(http.request, reqTable)
end
return false, nil, nil, nil, nil
end
local MOD_VERSION = "0.7.0-gen2"
-- Client Game Version (Red/Blue/Yellow) & Recomp Engine Version Detector
local function getClientVersionInfo()
local gameName = "Pokemon Red"
local okGv, GvMod = pcall(require, "src.core.GameVersion")
if okGv and GvMod and GvMod.get then
local vid = GvMod.get()
gameName = (GvMod.VERSIONS and GvMod.VERSIONS[vid] and GvMod.VERSIONS[vid].displayName) or (tostring(vid):sub(1,1):upper() .. tostring(vid):sub(2))
end
local recompVer = "0.0.0-dev"
local okVer, VerMod = pcall(require, "src.core.Version")
if okVer and VerMod and VerMod.engine then
recompVer = "v" .. tostring(VerMod.engine)
end
return gameName, recompVer
end
-- Profanity Filter Module Loader
local Profanity = nil
local okProf, profMod = pcall(require, "mods.gen2online.other.profanity")
if okProf and profMod then
Profanity = profMod
else
local okProf2, profMod2 = pcall(require, "other.profanity")
if okProf2 and profMod2 then Profanity = profMod2 end
end
local function gtsApiGet(path, timeout)
if not ltn12 then return nil end
local response_body = {}
local separator = path:find("?") and "&" or "?"
local fullPath = path .. separator .. "version=" .. MOD_VERSION .. "&modVersion=" .. MOD_VERSION
local ok, res, code, headers, status = makeHttpRequest({
url = GTS_SERVER_URL .. fullPath,
method = "GET",
headers = {
["X-Mod-Version"] = MOD_VERSION
},
sink = ltn12.sink.table(response_body),
timeout = timeout or 0.5
})
if ok and code == 200 and #response_body > 0 then
local str = table.concat(response_body)
local data = Json.decode(str)
return data
end
return nil
end
local function gtsApiPost(payload, timeout)
if not ltn12 then return nil end
payload = payload or {}
local gName, rVer = getClientVersionInfo()
payload.modVersion = MOD_VERSION
payload.version = MOD_VERSION
payload.gameVersion = gName
payload.recompVersion = rVer
local jsonStr = Json.encode(payload)
local response_body = {}
local ok, res, code, headers, status = makeHttpRequest({
url = GTS_SERVER_URL .. "/gts",
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = tostring(#jsonStr),
["X-Mod-Version"] = MOD_VERSION
},
source = ltn12.source.string(jsonStr),
sink = ltn12.sink.table(response_body),
timeout = timeout or 0.5
})
if ok and #response_body > 0 then
local str = table.concat(response_body)
local okJson, data = pcall(Json.decode, str)
if okJson and data then return data end
end
return nil
end -- Text Auto-Wrapping & 2-Line Dialogue Page Break Formatter
local function wrapText(str, maxLen)
maxLen = maxLen or 17
if not str or #str == 0 then return "" end
local rawLines = {}
for paragraph in tostring(str):gmatch("[^\r\n\f]+") do
local currentLine = ""
for word in paragraph:gmatch("%S+") do
if #currentLine == 0 then
currentLine = word
elseif #currentLine + 1 + #word <= maxLen then
currentLine = currentLine .. " " .. word
else
table.insert(rawLines, currentLine)
currentLine = word
end
end
if #currentLine > 0 then
table.insert(rawLines, currentLine)
end
end
-- Group every 2 lines into a dialog page separated by \f
local pages = {}
for i = 1, #rawLines, 2 do
local l1 = rawLines[i]
local l2 = rawLines[i + 1]
if l2 then
table.insert(pages, l1 .. "\n" .. l2)
else
table.insert(pages, l1)
end
end
return table.concat(pages, "\f")
end
-- Helper to list all Gen 1 Pokémon species sorted alphabetically
local function getAllGen1Species(data)
return Gen2Compat.allSpecies(data)
end
-- Fully Asynchronous 100% Non-Blocking Network Adapter for LinkBattle
--
-- CRITICAL CONTRACT (matches Net.lua API used by LinkBattle.lua):
-- LinkBattle calls update() then IMMEDIATELY poll() on the same frame.
-- update() MUST drain any available battle responses into self.inbox
-- synchronously, before poll() is called. Pushing to a background thread
-- and reading back later means poll() will always see an empty inbox.
--
-- Solution: update() does TWO things:
-- 1. Drain battleInChannel (background thread responses) -> self.inbox
-- 2. Push a fresh poll_battle_msgs request for NEXT frame's responses
local GtsNetAdapter = {}
GtsNetAdapter.__index = GtsNetAdapter
function GtsNetAdapter.new(myId, targetId, roomId)
local self = setmetatable({}, GtsNetAdapter)
self.myId = tostring(myId)
self.targetId = tostring(targetId)
self.roomId = roomId or ("ROOM_" .. self.myId .. "_" .. self.targetId)
self.inbox = {}
self.closed = false
self.paired = true -- already paired when battle starts
activeBattleAdapter = self
return self
end
function GtsNetAdapter:send(msg)
-- IMPORTANT: Suppress 'bye' messages from reaching the server room.
-- LinkBattle.lua calls net:send({type="bye"}) in origFinish, AFTER our
-- battle.finish wrapper has already called clear_battle_room. If 'bye'
-- is forwarded, it arrives in the room queue AFTER the clear and poisons
-- the opponent's next battle, causing an instant "other player left" loop.
-- Room cleanup is handled server-side by clear_battle_room, so bye is
-- unnecessary and actively harmful here.
if msg and msg.type == "bye" then return end
-- FIFO battle channel: send_battle_msg must NEVER be dropped
if battleOutChannel then
battleOutChannel:push({
url = GTS_SERVER_URL .. "/gts",
body = Json.encode({
action = "send_battle_msg",
modVersion = MOD_VERSION,
version = MOD_VERSION,
roomId = self.roomId,
targetId = self.targetId,
msg = msg
})
})
end
end
function GtsNetAdapter:update()
-- STEP 1: Drain any battle responses that the background thread has
-- already fetched into self.inbox NOW so poll() sees them this frame.
if battleInChannel then
local bStr = battleInChannel:pop()
while bStr do
local ok, bRes = pcall(Json.decode, bStr)
if ok and bRes and bRes.msgs then
for _, m in ipairs(bRes.msgs) do
table.insert(self.inbox, m)
end
end
bStr = battleInChannel:pop()
end
end
-- STEP 2: Push a fresh poll request every frame (keepNewest=true so
-- the background thread discards stale polls if they pile up).
-- No rate limit needed — the background thread coalesces them.
if not self.closed and battleOutChannel then
battleOutChannel:push({
keepNewest = true, -- ← tells background thread to discard older polls
url = GTS_SERVER_URL .. "/gts",
body = Json.encode({
action = "poll_battle_msgs",
modVersion = MOD_VERSION,
version = MOD_VERSION,
roomId = self.roomId,
myId = self.myId
})
})
end
end
function GtsNetAdapter:poll()
local out = self.inbox
self.inbox = {}
return out
end
function GtsNetAdapter:close()
-- Mark closed and clear the global reference.
-- We do NOT send a "bye" via the room queue here — the room is
-- cleared server-side by clear_battle_room in battle.finish, so
-- sending a bye would only poison the NEXT battle's fresh room
-- if clear_battle_room races with the new poll.
self.closed = true
if activeBattleAdapter == self then
activeBattleAdapter = nil
end
end
local syncMultiNetPlayers = nil
local getTrainerInfo = nil
local startPvpBattle = nil
local startLinkTrade = nil
local saveOnlineAccount = nil
local loadOnlineAccount = nil
local syncLocalProfile = nil
local performForcedSave = nil
local writeOnlineSave = nil
local loadOnlineSave = nil
local addMmoXp = nil
local openOnlineOptionsMenu = nil
local openFreshOnlinePlayerMenu = nil
local openRedeemTokenMenu = nil
local openMyProfileMenu = nil
local openTrainerCardScreen = nil
local openMmoLevelInfoScreen = nil
local openMmoChatMenu = nil
local handleDisconnect = nil
local handleConnectToServer = nil
local applyPlayerSprite = nil
-- NOTE: Battle responses are drained by GtsNetAdapter:update() directly, not here.
-- This function only handles position-sync and challenge/trade signals.
local function processGlobalThreadMessages(game)
-- Drain ALL queued position-sync responses (drain-all prevents stale challenge
-- data from sitting in netInChannel across multiple frames and firing after the
-- battle ends when the inBattle / cooldown guards are no longer active).
if not netInChannel then return end
local respStr = netInChannel:pop()
while respStr do
local ok, res = pcall(Json.decode, respStr)
if ok and res then
if res.error == "VERSION_MISMATCH" then
handleDisconnect(game, string.format("VERSION MISMATCH!\nSERVER IS ON V%s\nCLIENT SENT V%s\nLOCAL MOD V%s", res.serverVersion or "NEW", tostring(res.clientVersion or "EMPTY"), MOD_VERSION))
return
elseif res.error == "ALREADY_LOGGED_IN" or res.error == "BANNED" then
handleDisconnect(game, (res.message or "ACCOUNT ALREADY ACTIVE ON ANOTHER DEVICE!\nDISCONNECTED FOR SAFETY."))
return
end
if res.success then
-- Party invite receiver
if res.partyInvite and not pendingPartyInvite and not activeParty then
pendingPartyInvite = res.partyInvite
local inv = res.partyInvite
local tid, tName = getTrainerInfo(game.save)
local pMenu = {
{
label = "ACCEPT INVITE",
onSelect = function()
local aRes = gtsApiPost({
action = "party_accept",
trainerId = tid,
name = tName,
level = mmoLevel or 1,
map = (game.overworld and game.overworld.map and game.overworld.map.id) or Gen2Compat.defaultSpawn().map,
x = (game.overworld and game.overworld.player and game.overworld.player.cellX) or 5,
y = (game.overworld and game.overworld.player and game.overworld.player.cellY) or 5,
spriteId = localSelectedSprite
}, 1.5)
if aRes and aRes.success then
activeParty = aRes.party
pendingPartyInvite = nil
game.stack:push(TextBox.new(game, wrapText("JOINED CO-OP PARTY!\nALL XP IS NOW SHARED WITH MEMBERS!")))
else
pendingPartyInvite = nil
game.stack:push(TextBox.new(game, wrapText("COULD NOT JOIN PARTY!")))
end
end
},
{
label = "DECLINE",
onSelect = function()
gtsApiPost({ action = "party_decline", trainerId = tid }, 1.0)
pendingPartyInvite = nil
end
}
}
local invMsg = string.format("%s INVITED YOU TO A CO-OP PARTY!\nACCEPT INVITE?", inv.fromName or "A TRAINER")
game.stack:push(TextBox.new(game, wrapText(invMsg), function()
game.stack:push(Menu.new(game, pMenu, { tx = 0, ty = 0, tw = 20, maxVisible = 6, startCloses = true }))
end))
end
-- Shared Party XP receiver
if res.partyXp and #res.partyXp > 0 then
for _, xev in ipairs(res.partyXp) do
addMmoXp(game, "party_share", xev.xp or 50)
game.stack:push(TextBox.new(game, wrapText(string.format("PARTY CO-OP BONUS!\n+%d XP FROM %s!", xev.xp or 50, xev.fromName or "TEAMMATE"))))
end
end
if res.party ~= nil then
activeParty = res.party
end
-- 1. Route multi-player positions if overworld active
if res.players and game.overworld then
syncMultiNetPlayers(game, game.overworld, res.players)
end
-- 2. Route pending battle messages directly to active GtsNetAdapter
if res.msgs and activeBattleAdapter then
for _, m in ipairs(res.msgs) do
table.insert(activeBattleAdapter.inbox, m)
end
end
-- 3. Live Network Challenge Receiver (PVP Battle or Trade Popup!)
if res.challenge then
local nowT = (_G.love and _G.love.timer and _G.love.timer.getTime) and _G.love.timer.getTime() or os.time()
local inCooldown = (nowT - lastBattleEndTime) < 5.0
if inCooldown then
-- Post-battle cooldown: silently wipe stale challenges from the server
-- so they stop appearing on every sync_pos response.
local myId = getTrainerInfo(game.save)
if myId then
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
end
else
local challengerName = res.challenge.fromName or "TRAINER"
local challengerId = res.challenge.fromId
local cType = res.challenge.type or "PVP"
local remotePartyPacked = res.challenge.party or {}
local sharedSeed = res.challenge.seed or 12345
local roomId = res.challenge.roomId
local remoteGen = tonumber(res.challenge.generation)
if remoteGen and remoteGen ~= Gen2Compat.generation() then
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
game.stack:push(TextBox.new(game, wrapText(string.format(
"PVP BLOCKED: GENERATION MISMATCH (YOU GEN %d / THEM GEN %d)",
Gen2Compat.generation(), remoteGen))))
-- skip handling this challenge
cType = "DECLINE"
end
if cType == "ACCEPT_PVP" then
-- Guard: never start a second battle if one is already running
if inBattle then
local myId = getTrainerInfo(game.save)
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
else
isWaitingForChallenge = false
local myId = getTrainerInfo(game.save)
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
if not game.save or not game.save.party or #game.save.party == 0 then
game.stack:push(TextBox.new(game, wrapText("YOU NEED AT LEAST 1 POKéMON IN YOUR PARTY TO BATTLE!")))
elseif not remotePartyPacked or #remotePartyPacked == 0 then
game.stack:push(TextBox.new(game, wrapText(string.format("%s HAS NO POKéMON IN THEIR PARTY!", challengerName or "FOE"))))
else
game.stack:push(TextBox.new(game, "CHALLENGE ACCEPTED!\nSTARTING PVP BATTLE!"))
startPvpBattle(game, challengerName, challengerId, remotePartyPacked, true, sharedSeed, roomId)
end
end
elseif cType == "ACCEPT_TRADE" then
isWaitingForChallenge = false
local myId = getTrainerInfo(game.save)
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
if not game.save or not game.save.party or #game.save.party == 0 then
game.stack:push(TextBox.new(game, wrapText("YOU NEED AT LEAST 1 POKéMON IN YOUR PARTY TO TRADE!")))
else
game.stack:push(TextBox.new(game, wrapText("OFFER ACCEPTED! STARTING LINK TRADE!")))
startLinkTrade(game, challengerName, challengerId, false, roomId)
end
elseif cType == "DECLINE" then
isWaitingForChallenge = false
local myId = getTrainerInfo(game.save)
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
game.stack:push(TextBox.new(game, wrapText("CHALLENGE DECLINED BY OPPONENT.")))
elseif cType == "PVP" or cType == "TRADE" then
local myId, myName = getTrainerInfo(game.save)
local promptItems = {
{
label = string.format("ACCEPT %s", cType),
onSelect = function()
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
local myPackedParty = Gen2Compat.packParty(Protocol, game.save and game.save.party or {})
if cType == "PVP" then
if not game.save or not game.save.party or #game.save.party == 0 then
game.stack:push(TextBox.new(game, wrapText("YOU NEED AT LEAST 1 POKéMON IN YOUR PARTY TO BATTLE!")))
return
end
if not remotePartyPacked or #remotePartyPacked == 0 then
game.stack:push(TextBox.new(game, wrapText(string.format("%s HAS NO POKéMON IN THEIR PARTY!", challengerName or "FOE"))))
return
end
gtsApiPost({
action = "send_challenge",
targetId = challengerId,
fromId = myId,
fromName = myName,
challengeType = "ACCEPT_PVP",
party = myPackedParty,
seed = sharedSeed,
roomId = roomId,
generation = Gen2Compat.generation()
}, 1.5)
startPvpBattle(game, challengerName, challengerId, remotePartyPacked, false, sharedSeed, roomId)
elseif cType == "TRADE" then
if not game.save or not game.save.party or #game.save.party == 0 then
game.stack:push(TextBox.new(game, wrapText("YOU NEED AT LEAST 1 POKéMON IN YOUR PARTY TO TRADE!")))
return
end
gtsApiPost({
action = "send_challenge",
targetId = challengerId,
fromId = myId,
fromName = myName,
challengeType = "ACCEPT_TRADE",
roomId = roomId
}, 1.5)
startLinkTrade(game, challengerName, challengerId, true, roomId)
end
end
},
{
label = "DECLINE",
onSelect = function()
gtsApiPost({ action = "clear_challenge", trainerId = myId }, 0.5)
gtsApiPost({
action = "send_challenge",
targetId = challengerId,
fromId = myId,
fromName = myName,
challengeType = "DECLINE"
}, 0.5)
end
}
}
game.stack:push(Menu.new(game, promptItems, { tx = 1, ty = 1, tw = 18, th = 6 }))
end
end -- end cooldown else
end -- end if res.challenge
end -- end if res.success
end -- end if ok and res
respStr = netInChannel:pop()
end
end
-- Sync GTS Database with 24/7 Server
local function fetchGtsServerSync(trainerId)
local data = gtsApiGet("/gts/browse", 1.5)
if data and data.success then
isGtsServerConnected = true
gtsDb.listings = data.listings or {}
gtsDb.history = data.history or {}
if trainerId then
local claimData = gtsApiGet("/gts/claims?trainerId=" .. tostring(trainerId), 1.5)
if claimData and claimData.success then
gtsDb.claim_boxes[tostring(trainerId)] = claimData.claims or {}
end
end
return true
end
return false
end
-- Patch SPRITE_RED with walker = true for 3D Voxel camera while preserving GBC color palette
pcall(function()
pcall(function()
local sid = Gen2Compat.defaultSprite()
if sid and sid ~= "SPRITE_RED" then
mod.content.sprites:patch(sid, { walker = true })
end
end)
mod.content.sprites:patch("SPRITE_RED", {
walker = true,
})
end)
local activeQuestsCache = {}
local function fetchPlayerQuests(game)
game = game or Game
local tid = getTrainerInfo and getTrainerInfo(game and game.save) or "100001"
local data = gtsApiPost({ action = "get_quests", trainerId = tid }, 1.5)
if data and data.success and data.quests then
activeQuestsCache = data.quests
return activeQuestsCache
end
return activeQuestsCache or {}
end
local function getTrainerId(save)
local tid, tName = getTrainerInfo(save)
return tid
end
-- Trainer ID & Name Helper
getTrainerInfo = function(save)
local p = save and save.player
if not p then return 12345, "TRAINER" end
if not p.id then
-- IMPORTANT: plain math.random() is NOT auto-seeded by Lua/LOVE, so two
-- players who each roll their very first trainer ID around the same
-- point in their own process's (identical, unseeded) random sequence
-- can end up with the SAME id. Since the server keys active_players by
-- trainerId, a collision means one player's sync_pos overwrites the
-- other's entry, and each of them filters out anything matching "self"
-- -- which now also matches the other player -- making them invisible
-- to each other. love.math's RNG is auto-seeded per-process (time+PID)
-- by LOVE itself, so it doesn't collide across separate machines.
if _G.love and _G.love.math and _G.love.math.random then
p.id = love.math.random(10000, 99999)
else
math.randomseed(os.time() + math.floor((os.clock() or 0) * 1000000))
p.id = math.random(10000, 99999)
end
end
return p.id, p.name or "TRAINER"
end
-- Calculate Total Owned Badges from Save
-- Calculate Total Owned Badges from Save
local function getBadgeCount(save)
if not save or not save.badges then return 0 end
local count = 0
for _, b in pairs(save.badges) do
if b then count = count + 1 end
end
return count
end
-- Calculate Total Pokédex Caught from Save
local function getPokedexCount(save)
if not save or not save.pokedex or not save.pokedex.owned then return 0 end
local count = 0
for _, owned in pairs(save.pokedex.owned) do
if owned then count = count + 1 end
end
return count
end
-- Dual Save State Storage: Dedicated Online MMO Save File (Independent of Local save.lua)
local function getOnlineSaveFiles()
local gv = "red"
local okGv, GvMod = pcall(require, "src.core.GameVersion")
if okGv and GvMod and GvMod.get then gv = GvMod.get() or "red" end
local suffix = Gen2Compat.onlineSaveSuffix()
return "save_online" .. suffix .. ".lua", "save_online" .. suffix .. ".lua.bak", "save_online" .. suffix .. ".lua.tmp"
end
local offlineSaveBackup = nil
loadOnlineSave = function()
local SaveSerializer = require("src.core.SaveSerializer")
local fs = love.filesystem
if not fs then return nil end
local saveFile, bakFile, tmpFile = getOnlineSaveFiles()
local content = fs.read(saveFile)
if not content then
content = fs.read(bakFile) or fs.read(tmpFile)
end
if not content then return nil end
local ok, data = pcall(SaveSerializer.decode, content)
if ok and data and type(data) == "table" then
return data
end
return nil
end
writeOnlineSave = function(saveTable)
if not saveTable or type(saveTable) ~= "table" then return false end
local SaveSerializer = require("src.core.SaveSerializer")
local fs = love.filesystem
if not fs then return false end
local saveFile, bakFile, tmpFile = getOnlineSaveFiles()
local encoded = SaveSerializer.encode(saveTable)
if fs.getInfo(saveFile) then
local prev = fs.read(saveFile)
if prev then fs.write(bakFile, prev) end
end
fs.write(tmpFile, encoded)
fs.remove(saveFile)
fs.write(saveFile, encoded)
fs.remove(tmpFile)
return true
end
-- Global SaveData.save Guard: Intercept all Start Menu and in-game saves while online
local SaveDataModule = pcall(require, "src.core.SaveData") and require("src.core.SaveData") or nil
if SaveDataModule and SaveDataModule.save then
local origSaveDataSave = SaveDataModule.save
SaveDataModule.save = function(data, mods)
-- Only route to online slot while connected. Token alone must not redirect offline saves.
if isGtsServerConnected then
saveOnlineAccount(data)
return writeOnlineSave(data)
end
return origSaveDataSave(data, mods)
end
end
-- Forced Game Save helper (Captures live overworld coordinates & routes to save_online.lua or save.lua)
performForcedSave = function(game)
if not game or not game.save then return end
if game.overworld and game.overworld.captureSave then
pcall(function() game.overworld:captureSave(game.save) end)
end
if isGtsServerConnected then
saveOnlineAccount(game.save)
writeOnlineSave(game.save)
elseif game.writeSave then
pcall(function() game:writeSave() end)
end
end
-- Sync Local Trainer Profile & Online Account to Server
loadOnlineAccount = function(save)
if not save then return end
save.onlineAccount = save.onlineAccount or {}
local acc = save.onlineAccount
if acc.name and save.player then save.player.name = acc.name end
if acc.trainerId and save.player then save.player.id = acc.trainerId end
mmoLevel = acc.level or 1
mmoXp = acc.xp or 0
mmoToken = acc.token or nil
localSelectedSprite = Gen2Compat.resolveSprite(game, acc.spriteId or Gen2Compat.defaultSprite())
if acc.title then localTrainerTitle = acc.title end
if acc.favoriteMon then localFavoriteMon = acc.favoriteMon end
if acc.blackouts then save.blackoutCount = acc.blackouts end
-- Sanitize pcItems: migrate any legacy array-of-objects format to { ITEM_ID = count }
-- (PlayerPC.lua and Bag.lua expect pairs() over string keys, not ipairs over arrays)
local function sanitizeItemMap(tbl)
if type(tbl) ~= "table" then return {} end
-- Check if it's already in the correct key-value format (string keys = item IDs)
for k, v in pairs(tbl) do
if type(k) == "string" and type(v) == "number" then
return tbl -- already correct format