-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
788 lines (684 loc) · 23 KB
/
Copy pathmain.go
File metadata and controls
788 lines (684 loc) · 23 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
package main
import (
"bytes"
"embed"
"encoding/binary"
"encoding/json"
"fmt"
"io/fs"
"log"
"net"
"net/http"
"os"
"sort"
"strings"
"time"
)
// --- Configuration ---
type Config struct {
Port int `json:"port"`
TrackerIntervalSeconds int `json:"trackerIntervalSeconds"`
AutoTrackDefault bool `json:"autoTrackDefault"`
HostInNetwork bool `json:"hostInNetwork"`
}
// --- Embedding ---
//go:embed static/*
var staticEmbed embed.FS
//go:embed data/*
var dataEmbed embed.FS
// --- Data Structures ---
// ShineDefinition tracks the state and metadata of a specific shine.
type ShineDefinition struct {
ID string `json:"id"` // Unique ID used for tracking logic
Name string `json:"name"`
NumID int `json:"num_id"` // Numeric ID used for hook tracking (if applicable)
MemByte int `json:"mem_byte"`
MemBit int `json:"mem_bit"`
}
// Exit represents a loading zone or transition point within the game world.
type Exit struct {
ID string `json:"id"`
Name string `json:"name"`
}
// Zone represents a major level or area the player can warp to.
type Zone struct {
ID string `json:"id"`
Name string `json:"name"`
ShinesAvailable []ShineDefinition `json:"shines_available"`
Exits []Exit `json:"exits"`
BlueCoinIDs []string `json:"blue_coin_ids"`
}
type BlueCoinDefinition struct {
ID string `json:"id"`
Title string `json:"title"`
Episode []int `json:"episode"`
EpisodeString string `json:"episodeString"`
MarioPartyLegacyLink string `json:"mariopartylegacylink"`
Stage string `json:"stage"`
MemoryIndex int `json:"memory_index"`
}
type SkillMapping struct {
SkillName string `json:"skill_name"`
HasSkill bool `json:"has_skill"`
ShineID uint32 `json:"shine_id"`
ShineName string `json:"shine_name,omitempty"`
ZoneName string `json:"zone_name,omitempty"`
IsMapped bool `json:"is_mapped"`
OriginalIndex int `json:"-"` // Hidden from JSON, used for sorting
}
// Unlock represents a game capability, item, or nozzle.
type Unlock struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
}
// PlazaShines defines a specific entry point from the hub world (Plaza) to a level.
type PlazaShines struct {
ID string `json:"id"`
Name string `json:"name"`
GroupName string `json:"group_name"` // Used for grouping in the UI (e.g., "Bianco Hills")
Image string `json:"image"`
IsWarp bool `json:"is_warp"`
}
// WorldData serves as the root container for all static game configuration loaded from JSON.
type WorldData struct {
Zones map[string]Zone `json:"zones"`
Unlocks []Unlock `json:"unlocks"`
PlazaEntrances []PlazaShines `json:"plaza_entrances"`
BlueCoins []BlueCoinDefinition `json:"blue_coins"`
}
// MemoryState for API Output
type MemoryState struct {
IsHooked bool `json:"is_hooked"`
CurrentLevel string `json:"current_level"`
LevelAddress string `json:"level_address"`
CurrentEpisode string `json:"current_episode"`
EpisodeAddress string `json:"episode_address"`
EpisodeNumber int `json:"episode_number"`
Unlocks map[string]bool `json:"unlocks"`
// Collectibles read live from the save memory.
BlueCoins []string `json:"blue_coins"` // bcid list
Shines []string `json:"shines"` // shine id list
BlueCoinTrades int `json:"blue_coin_trades"` // count of trade-in shines collected
// Configvalues for Memory State
Interval int `json:"interval"`
AutoTrack bool `json:"auto_track"`
Seed string `json:"seed"`
}
// --- Dolphin Hook Logic ---
const (
PROCESS_VM_READ = 0x0010
PROCESS_QUERY_INFORMATION = 0x0400
// ADDR_SHINES_TOTAL is a vanilla game stat (total shines collected). It is
// NOT part of the randomizer's injected data block, so it stays put across
// randomizer updates and doubles as our "is the emulator still alive?" probe.
ADDR_SHINES_TOTAL = 0x8043A5A4
// The randomizer injects a data block (seed + skill unlocks + skill->shine
// map) whose BASE ADDRESS changes between randomizer versions. We therefore
// discover it at runtime (see LocateRandomizerBlock) and only rely on the
// block's fixed INTERNAL layout below.
OFF_SEED_TO_SKILLS = 0x1D // seed copy start -> skills array start (seed is 0x1D before skills)
OFF_SKILLS_TO_SHINES = 0x17 // skills array start -> shine-map start (map is right after the 23 skill bytes)
// Painting episode-select "last selected" values (menu struct; stable across
// reloads). Used to identify the SOURCE of a Plaza warp: which world painting
// and which episode you entered.
ADDR_SEL_COURSE = 0x80A01C9A // world/course id (see courseToPrefix)
ADDR_SEL_EPISODE = 0x80A01C9B // episode index, 0-based
)
// courseToPrefix maps the in-memory course id to the UI zone/entrance prefix.
var courseToPrefix = map[byte]string{
0: "corona", 2: "bianco", 3: "ricco", 4: "gelato",
5: "pinna", 6: "sirena", 8: "pianta", 9: "noki",
}
// Possible Levelnames the Hook can find
var levels = []string{
"BIANCO HILLS", "RICCO HARBOR", "GELATO BEACH", "PINNA PARK",
"SIRENA BEACH", "PIANTA VILLAGE", "NOKI BAY", "CORONA MOUNTAIN",
"DELFINO PLAZA", "AIRSTRIP",
}
// Skill names the hook can give to the tracker
var skillNames = []string{
"DOUBLE_JUMP", "TRIPLE_JUMP", "SIDEFLIP", "GRAB", "GROUND_SPIN",
"SPIN_JUMP", "DIVE", "WALL_KICKS", "GROUND_POUND", "Y_CAMERA",
"TALKING", "SHINE_SHIRT", "SUNGLASSES", "HELMET", "YOSHI",
"BLOOPER", "TOROCCO", "SPRAY", "SPAM_SPRAY", "HOVER",
"ROCKET", "TURBO", "CLIMBING",
}
// DolphinHookManager manages the connection and memory reading from the Dolphin emulator.
type DolphinHookManager struct {
PID uint32
Handle uintptr
BaseAddr uintptr
IsHooked bool
CurrentLevel string
CurrentEpisode string
LevelAddress uint32
EpisodeAddress uint32
EpisodeNumber int
LastSkills []byte
ShineIDs []uint32
Seed string
// Runtime-discovered addresses of the randomizer data block. Populated by
// LocateRandomizerBlock; only valid while BlockFound is true.
BlockFound bool
SeedAddr uint32
SkillsAddr uint32
ShinesAddr uint32
LastBlockScan time.Time
ModuleAnchor uint32 // cached address of a randomizer rodata string (0 = not found yet)
}
// SyncLocation scans the game's memory to determine the current level and episode.
func (d *DolphinHookManager) SyncLocation() {
blockSize := 0x400000
// Scan up to 0x81800000
for i := 0; i < 6; i++ {
offset := uint32(i) * uint32(blockSize)
data, err := d.Read(0x80000000+offset, blockSize)
if err != nil || data == nil {
continue
}
for _, name := range levels {
// We look for all occurrences in the block, not just the first one
idx := 0
for {
foundIdx := bytes.Index(data[idx:], []byte(name))
if foundIdx == -1 {
break
}
actualIdx := idx + foundIdx
absAddr := 0x80000000 + offset + uint32(actualIdx)
if absAddr >= 0x80960000 && absAddr <= 0x80970000 {
idx = actualIdx + 1
continue
}
if actualIdx > 0 && data[actualIdx-1] != 0x00 {
idx = actualIdx + 1
continue
}
// If we passed the filters, this is likely our real active level
d.CurrentLevel = name
d.LevelAddress = absAddr
// Grab the mission context
contextStart := max(0, actualIdx-1024)
d.CurrentEpisode, d.EpisodeAddress = findMostLikelyMission(data[contextStart:actualIdx])
return
}
}
}
}
func (d *DolphinHookManager) GetTotalShines() int {
data, err := d.Read(ADDR_SHINES_TOTAL, 4)
if err != nil || data == nil {
return 0
}
return int(binary.BigEndian.Uint32(data))
}
// --- Global State ---
var (
currentWorld WorldData
dm = &DolphinHookManager{CurrentLevel: "SEARCHING..."}
globalCfg Config
)
// --- Helper Functions ---
func findMostLikelyMission(data []byte) (string, uint32) {
parts := bytes.Split(data, []byte{0x00})
for i := len(parts) - 1; i >= 0; i-- {
p := bytes.TrimSpace(parts[i])
if len(p) > 4 && len(p) < 40 {
isASCII := true
for _, b := range p {
if b < 32 || b > 126 {
isASCII = false
break
}
}
if isASCII {
return string(p), binary.BigEndian.Uint32(data)
}
}
}
return "???", 0
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// isKnownLevel reports whether name is one of the game levels SyncLocation can
// detect. Used to confirm we are actually in-game before trusting/locating the
// randomizer block (its data is meaningless on the menus).
func isKnownLevel(name string) bool {
for _, l := range levels {
if l == name {
return true
}
}
return false
}
// --- Main Logic ---
// loadGameData parses JSON files and constructs the initial world state.
// This should only be called once during startup.
func loadGameData() {
// A. Load Zones
zoneFile, err := dataEmbed.ReadFile("data/zones.json")
if err != nil {
log.Fatalf("Error reading embedded zones.json: %v", err)
}
// Temporary wrapper to match the JSON structure structure
var zoneWrapper struct {
Zones map[string]Zone `json:"zones"`
}
if err := json.Unmarshal(zoneFile, &zoneWrapper); err != nil {
log.Fatalf("Error parsing zones.json: %v", err)
}
// The JSON uses the ID as the map key. We inject that key into the struct itself
// so the frontend receives a fully self-contained object.
for id, zone := range zoneWrapper.Zones {
zone.ID = id
zoneWrapper.Zones[id] = zone
}
// B. Load Unlocks
unlockFile, err := dataEmbed.ReadFile("data/unlocks.json")
if err != nil {
log.Fatalf("Error reading embedded unlocks.json: %v", err)
}
var unlockWrapper struct {
Unlocks []Unlock `json:"unlocks"`
}
if err := json.Unmarshal(unlockFile, &unlockWrapper); err != nil {
log.Fatalf("Error parsing unlocks.json: %v", err)
}
// C. Define Plaza Entrances programmatically
var entrances []PlazaShines
// 1. Plaza stuff
singles := []struct {
ID, Name, Image string
isWarp bool
}{
{"enter_corona", "Corona Mountain", "corona.png", true},
}
for _, s := range singles {
entrances = append(entrances, PlazaShines{
ID: s.ID,
Name: s.Name,
GroupName: "Plaza: Special & Secrets",
Image: s.Image,
IsWarp: s.isWarp,
})
}
// 2. Main Worlds (Generate entries for Episodes 1-8)
worlds := []struct {
ID, Name, Image string
}{
{"bianco", "Bianco Hills", "bianco_entry.png"},
{"ricco", "Ricco Harbor", "ricco_entry.png"},
{"gelato", "Gelato Beach", "gelato_entry.png"},
{"pinna", "Pinna Park", "pinna_entry.png"},
{"sirena", "Sirena Beach", "sirena_entry.png"},
{"noki", "Noki Bay", "noki_entry.png"},
{"pianta", "Pianta Village", "pianta_entry.png"},
}
for _, w := range worlds {
for ep := 1; ep <= 8; ep++ {
entrances = append(entrances, PlazaShines{
ID: fmt.Sprintf("enter_%s_ep%d", w.ID, ep),
Name: fmt.Sprintf("Episode %d", ep),
GroupName: w.Name,
Image: w.Image,
IsWarp: true,
})
}
}
// D. Load Blue Coins
bcFile, err := dataEmbed.ReadFile("data/blue_coin.json")
if err != nil {
log.Printf("Warning: Could not find blue_coin.json: %v", err)
}
var blueCoins []BlueCoinDefinition
if bcFile != nil {
if err := json.Unmarshal(bcFile, &blueCoins); err != nil {
log.Printf("Error parsing blue_coins.json: %v", err)
}
}
// Assign compiled data to global state
currentWorld = WorldData{
Zones: zoneWrapper.Zones,
Unlocks: unlockWrapper.Unlocks,
PlazaEntrances: entrances,
BlueCoins: blueCoins,
}
// --- NEW PROGRESS TRACKER LOGIC ---
// --- FILE-LEVEL PROGRESS TRACKER ---
totalShinesInFile := 0
missingMem := 0
placeholderIDs := 0
foundIDs := make(map[int]bool)
unmappedShines := []string{}
shinesWithNotKnownNumID := []string{}
for zoneID, zone := range currentWorld.Zones {
for _, shine := range zone.ShinesAvailable {
if !foundIDs[shine.NumID] {
foundIDs[shine.NumID] = true
totalShinesInFile++
} else if shine.NumID == 9999 {
shinesWithNotKnownNumID = append(shinesWithNotKnownNumID, fmt.Sprintf("%s - %s", zone.Name, shine.Name))
totalShinesInFile++
}
// Count every time 9999 appears in the file
if shine.NumID == 9999 {
placeholderIDs++
}
// Count every shine missing memory bits
// We skip bianco0 because 0,0 is its legitimate address
if shine.MemByte == 0 && shine.MemBit == 0 && zoneID != "bianco0" {
unmappedShines = append(unmappedShines, fmt.Sprintf("%s - %s", zone.Name, shine.Name))
missingMem++
}
}
}
debugf("\n=== FILE PROGRESS REPORT ===\n")
debugf("Total Shine Entries: %d\n", totalShinesInFile)
debugf("Remaining 9999 IDs: %d\n", placeholderIDs)
debugf("Remaining Mem Offsets: %d\n", missingMem)
debugf("Shines Missing Mem: \n")
for _, s := range unmappedShines {
debugf(" - %s\n", s)
}
debugf("Shines with NumID 9999: \n")
for _, s := range shinesWithNotKnownNumID {
if !strings.Contains(s, "100 Coin") {
debugf(" - %s\n", s)
}
}
debugf("============================\n\n")
debugf("Data loaded successfully: %d zones, %d entrances configured, %d unlocks, %d blue coins.\n",
len(currentWorld.Zones), len(currentWorld.PlazaEntrances), len(currentWorld.Unlocks), len(currentWorld.BlueCoins))
// Completion audit for debugging: List how many zones still have num_id: 9999 and how many are missing mem_byte and mem_bit entry
}
func containsOffset(offsets [][]int, target []int) bool {
for _, offset := range offsets {
if len(offset) == 2 && len(target) == 2 && offset[0] == target[0] && offset[1] == target[1] {
return true
}
}
return false
}
// --- Server API ---
func LoadConfig() Config {
defaultConfig := Config{Port: 8080, TrackerIntervalSeconds: 5, AutoTrackDefault: true, HostInNetwork: false}
file, err := os.ReadFile("config.json")
if err != nil {
// If file doesn't exist, write the file then load defaults
if os.IsNotExist(err) {
configData, _ := json.MarshalIndent(defaultConfig, "", " ")
writeErr := os.WriteFile("config.json", configData, 0644)
if writeErr != nil {
log.Fatalf("Error creating default config.json: %v", writeErr)
} else {
fmt.Println("Created default config.json")
}
} else {
log.Fatalf("Error reading config.json: %v", err)
}
return defaultConfig
}
var loadedConfig Config
if err := json.Unmarshal(file, &loadedConfig); err != nil {
fmt.Printf("Warning: Failed to parse config.json, using default port %d\n", defaultConfig.Port)
return defaultConfig
}
return loadedConfig
}
func runMemoryScanner() {
warnedNoDolphin := false
for {
if !dm.IsHooked {
if !dm.Hook() {
if !warnedNoDolphin {
debugf("Dolphin not found — waiting for it to start...\n")
warnedNoDolphin = true
}
time.Sleep(2 * time.Second)
continue
}
debugf("Successfully hooked to Dolphin!\n")
warnedNoDolphin = false
dm.BlockFound = false
dm.LastBlockScan = time.Time{}
dm.ModuleAnchor = 0
}
// Liveness probe against a vanilla address so we notice a closed emulator
// even before the randomizer block has been located.
if _, err := dm.Read(ADDR_SHINES_TOTAL, 4); err != nil {
debugf("Connection lost to Dolphin, cleaning up...\n")
dm.Close()
dm.IsHooked = false
dm.BlockFound = false
dm.ModuleAnchor = 0
time.Sleep(1 * time.Second)
continue
}
oldLocation := dm.CurrentLevel
oldEpisode := dm.CurrentEpisode
dm.SyncLocation()
// Find the randomizer data block (abilities + shine map). Only attempt
// this once we are actually inside a level: on the menus the real block
// isn't populated yet, so a scan there can lock onto stale/garbage data.
if !dm.BlockFound && isKnownLevel(dm.CurrentLevel) && time.Since(dm.LastBlockScan) > 3*time.Second {
dm.LastBlockScan = time.Now()
dm.LocateRandomizerBlock()
}
if dm.BlockFound {
oldSkills := dm.LastSkills
s, err := dm.Read(dm.SkillsAddr, 23)
if err == nil && s != nil && !looksLikeSkills(s) {
// The block moved (or we locked onto a false positive): re-locate.
debugf("Skills data no longer valid, re-locating randomizer block...\n")
dm.BlockFound = false
} else if err == nil && s != nil {
// Refresh the skill->shine map (which shine grants each ability).
if shineData, e := dm.Read(dm.ShinesAddr, 23*4); e == nil && shineData != nil {
dm.ShineIDs = dm.ShineIDs[:0]
for i := 0; i < 23; i++ {
dm.ShineIDs = append(dm.ShineIDs, binary.BigEndian.Uint32(shineData[i*4:(i+1)*4]))
}
}
dm.LastSkills = s
if oldSkills != nil && !bytes.Equal(oldSkills, s) {
reportSkillChanges(oldSkills, s, oldLocation, oldEpisode)
}
if seed, e := dm.ReadSeed(); e == nil {
dm.Seed = seed
}
}
}
// Wait before next scan
time.Sleep(500 * time.Millisecond)
}
}
// reportSkillChanges logs which ability just flipped and, via the shine map,
// which shine granted it. Unmapped shine IDs are surfaced loudly so they can be
// added to the JSON.
func reportSkillChanges(oldSkills, s []byte, oldLocation, oldEpisode string) {
for i := 0; i < len(s); i++ {
if i >= len(oldSkills) || oldSkills[i] == s[i] {
continue
}
debugf("Skill %s changed from %d to %d\n", skillNames[i], oldSkills[i], s[i])
if i >= len(dm.ShineIDs) {
continue
}
// Some abilities have no granting shine (sentinel ID), e.g. TALKING is
// always unlocked. That's expected, not a missing mapping.
if sid := dm.ShineIDs[i]; sid == shineSentinelA || sid == shineSentinelB {
continue
}
var foundShine bool
for j, zone := range currentWorld.Zones {
for _, shine := range zone.ShinesAvailable {
if shine.NumID == int(dm.ShineIDs[i]) {
debugf("This is shineID %d which is linked to this skill, total shines collected: %d\n", dm.ShineIDs[i], dm.GetTotalShines())
debugf("This shine is located in zone %s (%s) and is called %s\n", j, zone.Name, shine.Name)
foundShine = true
break
}
}
}
if !foundShine {
debugf("\n[!!!] MISSING MAPPING [!!!]\n")
debugf("shineID %d linked to skill %s, total shines collected: %d\n", dm.ShineIDs[i], skillNames[i], dm.GetTotalShines())
debugf("ID: %d | Level: %s | Ep: %s - Old Location: %s | Old Episode: %s\n",
dm.ShineIDs[i], dm.CurrentLevel, dm.CurrentEpisode, oldLocation, oldEpisode)
if debugEnabled {
go ShowPopup("Missing Shine Mapping", "Found unmapped ID! Check debug.log for details.")
}
}
}
}
func main() {
for _, a := range os.Args[1:] {
if a == "-debug" || a == "debug" {
debugEnabled = true
}
}
globalCfg = LoadConfig()
loadGameData()
go runMemoryScanner()
go RunOffsetTracker()
publicFiles, err := fs.Sub(staticEmbed, "static")
if err != nil {
log.Fatal(err)
}
http.Handle("/", http.FileServer(http.FS(publicFiles)))
http.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(currentWorld)
if err != nil {
http.Error(w, "Failed to encode data", http.StatusInternalServerError)
}
})
http.HandleFunc("/api/memory", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
unlockMap := make(map[string]bool)
if dm.LastSkills != nil {
for i, name := range skillNames {
if i < len(dm.LastSkills) {
unlockMap[name] = dm.LastSkills[i] != 0
}
}
}
state := MemoryState{
IsHooked: dm.IsHooked,
CurrentLevel: dm.CurrentLevel,
LevelAddress: fmt.Sprintf("0x%08X", dm.LevelAddress),
CurrentEpisode: dm.CurrentEpisode,
EpisodeAddress: fmt.Sprintf("0x%08X", dm.EpisodeAddress),
EpisodeNumber: dm.EpisodeNumber,
Unlocks: unlockMap,
BlueCoins: snapshotBlueCoins(),
Shines: snapshotShines(),
BlueCoinTrades: snapshotTradeCount(),
Interval: globalCfg.TrackerIntervalSeconds,
AutoTrack: globalCfg.AutoTrackDefault,
Seed: dm.Seed,
}
err = json.NewEncoder(w).Encode(state)
if err != nil {
http.Error(w, "Failed to encode memory state", http.StatusInternalServerError)
}
})
// New Endpoint: Skill and Shine Mapping
http.HandleFunc("/api/spoiler", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if dm.LastSkills == nil || dm.ShineIDs == nil {
http.Error(w, "Memory data not yet available", http.StatusServiceUnavailable)
return
}
mappings := make([]SkillMapping, 0)
for i, skill := range skillNames {
if i >= len(dm.LastSkills) || i >= len(dm.ShineIDs) {
break
}
baseMapping := SkillMapping{
SkillName: skill,
HasSkill: dm.LastSkills[i] != 0,
ShineID: dm.ShineIDs[i],
IsMapped: false,
OriginalIndex: i, // Store the index from skillNames
}
foundAtLeastOne := false
for _, zone := range currentWorld.Zones {
for _, shine := range zone.ShinesAvailable {
if shine.NumID == int(baseMapping.ShineID) {
m := baseMapping
m.ShineName = shine.Name
m.ZoneName = zone.Name
m.IsMapped = true
mappings = append(mappings, m)
foundAtLeastOne = true
}
}
}
if !foundAtLeastOne {
mappings = append(mappings, baseMapping)
}
}
// Sort: Primary by OriginalIndex, Secondary by ZoneName
sort.Slice(mappings, func(i, j int) bool {
if mappings[i].OriginalIndex != mappings[j].OriginalIndex {
return mappings[i].OriginalIndex < mappings[j].OriginalIndex
}
return mappings[i].ZoneName < mappings[j].ZoneName
})
if err := json.NewEncoder(w).Encode(mappings); err != nil {
http.Error(w, "Failed to encode skill mapping", http.StatusInternalServerError)
}
})
addr := fmt.Sprintf("localhost:%d", globalCfg.Port)
addrStr := []string{"localhost"}
if globalCfg.HostInNetwork {
addr = fmt.Sprintf("0.0.0.0:%d", globalCfg.Port)
localIPs := getLocalIPs()
addrStr = append(addrStr, localIPs...)
}
fmt.Println("Starting server... Web interface available at:")
for i, a := range addrStr {
if i == 1 {
if globalCfg.HostInNetwork {
fmt.Println(" - Listening on all interfaces. - UI is also available in local network at:")
}
}
fmt.Printf(" - http://%s:%d\n", a, globalCfg.Port)
}
fmt.Printf("Open your web browser and navigate to the above URL to access the tracker interface.\n")
fmt.Printf("You can alternativly open the link by holding Ctrl and clicking it in supported terminals.\n")
fmt.Println("Press Ctrl+C to stop the server.")
log.Fatal(http.ListenAndServe(addr, nil))
}
func getLocalIPs() []string {
var ips []string
addresses, err := net.InterfaceAddrs()
if err != nil {
return ips
}
for _, addr := range addresses {
// Check the address type and ensure it's not a loopback (127.0.0.1)
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ips = append(ips, ipnet.IP.String())
}
}
}
return ips
}
func (d *DolphinHookManager) ReadSeed() (string, error) {
if !d.IsHooked || !d.BlockFound {
return "", fmt.Errorf("randomizer block not located")
}
data, err := d.Read(d.SeedAddr, 4)
if err != nil || data == nil {
return "", err
}
return fmt.Sprintf("%X", data), nil
}