forked from Gennadiyev/STS2MCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpMod.ForkEndpoints.cs
More file actions
653 lines (581 loc) · 24.2 KB
/
Copy pathMcpMod.ForkEndpoints.cs
File metadata and controls
653 lines (581 loc) · 24.2 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using MegaCrit.Sts2.Core.HoverTips;
using MegaCrit.Sts2.Core.Models;
using MegaCrit.Sts2.Core.Models.CardPools;
using MegaCrit.Sts2.Core.Models.Events;
using MegaCrit.Sts2.Core.Models.Monsters;
using MegaCrit.Sts2.Core.Models.PotionPools;
using MegaCrit.Sts2.Core.Models.RelicPools;
using MegaCrit.Sts2.Core.Runs;
using MegaCrit.Sts2.Core.Saves;
namespace STS2_MCP;
public static partial class McpMod
{
private const string RunNotInProgressErrorCode = "run_not_in_progress";
private const string RunStateUnavailableErrorCode = "run_state_unavailable";
private static void HandleGetSettings(HttpListenerResponse response)
{
try
{
var dataTask = RunOnMainThread(BuildSettings);
SendReadResultJson(response, dataTask.GetAwaiter().GetResult());
}
catch (Exception ex)
{
SendError(response, 500, $"Failed to read settings: {ex.Message}", "settings_read_failed");
}
}
internal static object BuildSettings()
{
var sm = SaveManager.Instance;
if (sm == null)
return Error("Save manager is not available", "save_manager_unavailable");
var settings = sm.SettingsSave;
var prefs = sm.PrefsSave;
if (settings == null || prefs == null)
return Error("Settings data is not available", "settings_data_unavailable");
return new Dictionary<string, object?>
{
["status"] = "ok",
["kind"] = "settings",
["display"] = new Dictionary<string, object?>
{
["fullscreen"] = settings.Fullscreen,
["resolution"] = $"{settings.WindowSize.X}x{settings.WindowSize.Y}",
["fps_limit"] = settings.FpsLimit,
["vsync"] = settings.VSync.ToString(),
["msaa"] = settings.Msaa,
["aspect_ratio"] = settings.AspectRatioSetting.ToString(),
["target_display"] = settings.TargetDisplay,
["limit_fps_background"] = settings.LimitFpsInBackground,
},
["audio"] = new Dictionary<string, object?>
{
["master"] = settings.VolumeMaster,
["bgm"] = settings.VolumeBgm,
["sfx"] = settings.VolumeSfx,
["ambience"] = settings.VolumeAmbience,
},
["gameplay"] = new Dictionary<string, object?>
{
["fast_mode"] = prefs.FastMode.ToString(),
["screen_shake"] = prefs.ScreenShakeOptionIndex,
["show_run_timer"] = prefs.ShowRunTimer,
["show_card_indices"] = prefs.ShowCardIndices,
["text_effects"] = prefs.TextEffectsEnabled,
["long_press"] = prefs.IsLongPressEnabled,
},
["mods"] = new Dictionary<string, object?>
{
["enabled"] = settings.ModSettings?.PlayerAgreedToModLoading ?? false,
},
["language"] = settings.Language,
["skip_intro"] = settings.SkipIntroLogo,
};
}
private static void HandleGetBestiary(HttpListenerResponse response)
{
try
{
var dataTask = RunOnMainThread(BuildBestiary);
SendJson(response, dataTask.GetAwaiter().GetResult());
}
catch (Exception ex)
{
SendError(response, 500, $"Failed to build bestiary: {ex.Message}", "bestiary_build_failed");
}
}
private static void HandleGetGlossaryCards(HttpListenerResponse response)
{
try
{
var dataTask = RunOnMainThread(() => BuildGlossaryPayload("cards", BuildGlossaryCards));
SendGlossaryJson(response, dataTask.GetAwaiter().GetResult());
}
catch (Exception ex)
{
SendError(response, 500, $"Failed to build glossary: {ex.Message}", "glossary_build_failed");
}
}
private static void HandleGetGlossaryKeywords(HttpListenerResponse response)
{
try
{
var dataTask = RunOnMainThread(() => BuildGlossaryPayload("keywords", BuildGlossaryKeywords));
SendGlossaryJson(response, dataTask.GetAwaiter().GetResult());
}
catch (Exception ex)
{
SendError(response, 500, $"Failed to build glossary: {ex.Message}", "glossary_build_failed");
}
}
private static void HandleGetGlossaryPotions(HttpListenerResponse response)
{
try
{
var dataTask = RunOnMainThread(() => BuildGlossaryPayload("potions", BuildGlossaryPotions));
SendGlossaryJson(response, dataTask.GetAwaiter().GetResult());
}
catch (Exception ex)
{
SendError(response, 500, $"Failed to build glossary: {ex.Message}", "glossary_build_failed");
}
}
private static void HandleGetGlossaryRelics(HttpListenerResponse response)
{
try
{
var dataTask = RunOnMainThread(() => BuildGlossaryPayload("relics", BuildGlossaryRelics));
SendGlossaryJson(response, dataTask.GetAwaiter().GetResult());
}
catch (Exception ex)
{
SendError(response, 500, $"Failed to build glossary: {ex.Message}", "glossary_build_failed");
}
}
private sealed class GlossaryPayload
{
public string Kind { get; init; } = "";
public object Data { get; init; } = new();
public int ProfileId { get; init; }
public string? ProgressPath { get; init; }
public string? ResolvedProgressPath { get; init; }
public string ProfileRoot { get; init; } = "";
public string SaveScope { get; init; } = "vanilla";
public string NetType { get; init; } = "";
public List<Dictionary<string, object?>> Players { get; init; } = new();
}
private static GlossaryPayload BuildGlossaryPayload(string kind, Func<object> buildData)
{
var profileId = SaveManager.Instance?.CurrentProfileId ?? 0;
var progressPath = GetProfileProgressPath(profileId);
var resolvedProgressPath = ResolveProfileProgressPath(profileId);
var profileRoot = GetProfileRootFromProgressPath(progressPath, profileId);
var data = buildData();
if (data is Dictionary<string, object?> error && error.TryGetValue("error_code", out _))
{
return new GlossaryPayload
{
Kind = kind,
Data = error,
ProfileId = profileId,
ProgressPath = progressPath,
ResolvedProgressPath = resolvedProgressPath,
ProfileRoot = profileRoot,
SaveScope = GetSaveScope(profileRoot),
NetType = SafeGetNetTypeName()
};
}
var runState = RunManager.Instance.DebugOnlyGetState();
var players = runState?.Players.Select((player, index) => new Dictionary<string, object?>
{
["index"] = index,
["character"] = player.Character?.Id.Entry,
["character_name"] = SafeGetText(() => player.Character?.Title)
}).ToList() ?? new List<Dictionary<string, object?>>();
return new GlossaryPayload
{
Kind = kind,
Data = data,
ProfileId = profileId,
ProgressPath = progressPath,
ResolvedProgressPath = resolvedProgressPath,
ProfileRoot = profileRoot,
SaveScope = GetSaveScope(profileRoot),
NetType = SafeGetNetTypeName(),
Players = players
};
}
private static string SafeGetNetTypeName()
{
try
{
return RunManager.Instance?.NetService?.Type.ToString() ?? "";
}
catch
{
return "";
}
}
private static void SendGlossaryJson(HttpListenerResponse response, GlossaryPayload payload)
{
var data = payload.Data;
if (data is Dictionary<string, object?> error
&& error.TryGetValue("error_code", out var errorCode))
{
response.StatusCode = (errorCode as string) switch
{
RunNotInProgressErrorCode => 409,
RunStateUnavailableErrorCode => 503,
_ => 500
};
error["kind"] = payload.Kind;
error["scope"] = "active_run";
error["profile_id"] = payload.ProfileId;
error["progress_path"] = NormalizePathForJson(payload.ProgressPath);
error["resolved_progress_path"] = NormalizePathForJson(payload.ResolvedProgressPath);
error["profile_root"] = NormalizePathForJson(payload.ProfileRoot);
error["save_scope"] = payload.SaveScope;
error["net_type"] = payload.NetType;
SendJson(response, data);
return;
}
if (data is not List<Dictionary<string, object?>> items)
{
SendJson(response, data);
return;
}
SendJson(response, new Dictionary<string, object?>
{
["status"] = "ok",
["kind"] = payload.Kind,
["scope"] = "active_run",
["count"] = items.Count,
["profile_id"] = payload.ProfileId,
["progress_path"] = NormalizePathForJson(payload.ProgressPath),
["resolved_progress_path"] = NormalizePathForJson(payload.ResolvedProgressPath),
["profile_root"] = NormalizePathForJson(payload.ProfileRoot),
["save_scope"] = payload.SaveScope,
["current_run"] = BuildCurrentRunContext(
isRunInProgress: true,
profileId: payload.ProfileId,
saveScope: payload.SaveScope,
progressPath: payload.ProgressPath,
profileRoot: payload.ProfileRoot),
["net_type"] = payload.NetType,
["players"] = payload.Players,
["items"] = items
});
}
private static Dictionary<string, object?> GlossaryError(string message, string errorCode)
{
return new Dictionary<string, object?>
{
["status"] = "error",
["error"] = message,
["error_code"] = errorCode
};
}
internal static object BuildGlossaryCards()
{
if (RunManager.Instance?.IsInProgress != true)
return GlossaryError("No run in progress.", RunNotInProgressErrorCode);
var runState = RunManager.Instance.DebugOnlyGetState();
if (runState == null)
return GlossaryError("Could not read run state.", RunStateUnavailableErrorCode);
var result = new List<Dictionary<string, object?>>();
var seen = new HashSet<string>();
foreach (var pool in ModelDb.AllSharedCardPools)
AddCardsFromPool(pool, SafeGetText(() => pool.Title) ?? pool.Id.Entry, result, seen);
foreach (var player in runState.Players)
{
var pool = player.Character?.CardPool;
if (pool == null) continue;
var poolName = SafeGetText(() => pool.Title) ?? "Unknown";
AddCardsFromPool(pool, poolName, result, seen);
}
return SortDictionaryListByStringField(result, "id");
}
private static void AddCardsFromPool(
CardPoolModel pool,
string poolName,
List<Dictionary<string, object?>> result,
HashSet<string> seen)
{
foreach (var card in pool.AllCards)
{
var id = card.Id.Entry;
if (seen.Contains(id)) continue;
seen.Add(id);
var upgradedPreview = SafeBuildUpgradedCardPreview(card);
result.Add(new Dictionary<string, object?>
{
["id"] = id,
["name"] = SafeGetText(() => card.Title),
["type"] = card.Type.ToString(),
["cost"] = GetCostDisplay(card),
["star_cost"] = GetStarCostDisplay(card),
["description"] = SafeGetCardDescription(card),
["rarity"] = card.Rarity.ToString(),
["pool"] = poolName,
["is_upgraded"] = card.IsUpgraded,
["is_upgradable"] = card.IsUpgradable,
["current_upgrade_level"] = card.CurrentUpgradeLevel,
["max_upgrade_level"] = card.MaxUpgradeLevel,
["upgrade_preview_type"] = card.UpgradePreviewType.ToString(),
["upgrade_preview_cost"] = upgradedPreview != null ? GetCostDisplay(upgradedPreview) : null,
["upgrade_preview_star_cost"] = upgradedPreview != null ? GetStarCostDisplay(upgradedPreview) : null,
["upgrade_preview_description"] = SafeGetCardUpgradePreviewDescription(card),
["keywords"] = BuildHoverTips(card.HoverTips)
});
}
}
internal static object BuildGlossaryRelics()
{
if (RunManager.Instance?.IsInProgress != true)
return GlossaryError("No run in progress.", RunNotInProgressErrorCode);
var runState = RunManager.Instance.DebugOnlyGetState();
if (runState == null)
return GlossaryError("Could not read run state.", RunStateUnavailableErrorCode);
var result = new List<Dictionary<string, object?>>();
var seen = new HashSet<string>();
var sharedPool = ModelDb.RelicPool<SharedRelicPool>();
AddRelicsFromPool(sharedPool, "Shared", result, seen);
foreach (var player in runState.Players)
{
var character = player.Character;
if (character == null || character.RelicPool == null) continue;
var pool = character.RelicPool;
var poolName = SafeGetText(() => character.Title) ?? "Unknown";
AddRelicsFromPool(pool, poolName, result, seen);
}
return SortDictionaryListByStringField(result, "id");
}
private static void AddRelicsFromPool(
RelicPoolModel pool,
string poolName,
List<Dictionary<string, object?>> result,
HashSet<string> seen)
{
foreach (var relic in pool.AllRelics)
{
var id = relic.Id.Entry;
if (seen.Contains(id)) continue;
seen.Add(id);
result.Add(new Dictionary<string, object?>
{
["id"] = id,
["name"] = SafeGetText(() => relic.Title),
["description"] = SafeGetText(() => relic.DynamicDescription),
["rarity"] = relic.Rarity.ToString(),
["pool"] = poolName,
["keywords"] = BuildHoverTips(relic.HoverTipsExcludingRelic)
});
}
}
internal static object BuildGlossaryPotions()
{
if (RunManager.Instance?.IsInProgress != true)
return GlossaryError("No run in progress.", RunNotInProgressErrorCode);
var runState = RunManager.Instance.DebugOnlyGetState();
if (runState == null)
return GlossaryError("Could not read run state.", RunStateUnavailableErrorCode);
var result = new List<Dictionary<string, object?>>();
var seen = new HashSet<string>();
var sharedPool = ModelDb.PotionPool<SharedPotionPool>();
AddPotionsFromPool(sharedPool, "Shared", result, seen);
foreach (var player in runState.Players)
{
var character = player.Character;
if (character == null || character.PotionPool == null) continue;
var pool = character.PotionPool;
var poolName = SafeGetText(() => character.Title) ?? "Unknown";
AddPotionsFromPool(pool, poolName, result, seen);
}
return SortDictionaryListByStringField(result, "id");
}
private static void AddPotionsFromPool(
PotionPoolModel pool,
string poolName,
List<Dictionary<string, object?>> result,
HashSet<string> seen)
{
foreach (var potion in pool.AllPotions)
{
var id = potion.Id.Entry;
if (seen.Contains(id)) continue;
seen.Add(id);
result.Add(new Dictionary<string, object?>
{
["id"] = id,
["name"] = SafeGetText(() => potion.Title),
["description"] = SafeGetText(() => potion.DynamicDescription),
["rarity"] = potion.Rarity.ToString(),
["target_type"] = potion.TargetType.ToString(),
["usage"] = potion.Usage.ToString(),
["pool"] = poolName,
["keywords"] = BuildHoverTips(potion.ExtraHoverTips)
});
}
}
internal static object BuildGlossaryKeywords()
{
if (RunManager.Instance?.IsInProgress != true)
return GlossaryError("No run in progress.", RunNotInProgressErrorCode);
var runState = RunManager.Instance.DebugOnlyGetState();
if (runState == null)
return GlossaryError("Could not read run state.", RunStateUnavailableErrorCode);
var keywords = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var pool in ModelDb.AllSharedCardPools)
foreach (var card in pool.AllCards)
AddKeywordTips(card.HoverTips, keywords);
foreach (var relic in ModelDb.RelicPool<SharedRelicPool>().AllRelics)
AddKeywordTips(relic.HoverTipsExcludingRelic, keywords);
foreach (var potion in ModelDb.PotionPool<SharedPotionPool>().AllPotions)
AddKeywordTips(potion.ExtraHoverTips, keywords);
foreach (var player in runState.Players)
{
var cardPool = player.Character?.CardPool;
if (cardPool != null)
{
foreach (var card in cardPool.AllCards)
AddKeywordTips(card.HoverTips, keywords);
}
var relicPool = player.Character?.RelicPool;
if (relicPool != null)
{
foreach (var relic in relicPool.AllRelics)
AddKeywordTips(relic.HoverTipsExcludingRelic, keywords);
}
var potionPool = player.Character?.PotionPool;
if (potionPool != null)
{
foreach (var potion in potionPool.AllPotions)
AddKeywordTips(potion.ExtraHoverTips, keywords);
}
}
var result = new List<Dictionary<string, object?>>();
foreach (var kv in keywords.OrderBy(k => k.Key, StringComparer.Ordinal))
{
result.Add(new Dictionary<string, object?>
{
["name"] = kv.Key,
["description"] = kv.Value
});
}
return result;
}
private static void AddKeywordTips(IEnumerable<IHoverTip>? tips, Dictionary<string, string> keywords)
{
if (tips == null)
return;
foreach (var tip in IHoverTip.RemoveDupes(tips))
{
try
{
if (tip is not HoverTip ht)
continue;
var title = SafeGetText(() => ht.Title);
if (!string.IsNullOrEmpty(title))
keywords.TryAdd(title!, SafeGetText(() => ht.Description) ?? "");
}
catch
{
// Hover-tip getters can throw during state transitions; skip unstable tips.
}
}
}
internal static object BuildBestiary()
{
var bindFlags = System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance;
var monsters = new List<Dictionary<string, object?>>();
foreach (var type in typeof(MonsterModel).Assembly.GetTypes())
{
if (type.IsAbstract || !type.IsSubclassOf(typeof(MonsterModel)) || type.FullName!.Contains("+")) continue;
var entry = new Dictionary<string, object?>
{
["id"] = ModelId.SlugifyCategory(type.Name),
["class"] = type.Name,
};
try
{
var instance = RuntimeHelpers.GetUninitializedObject(type);
var minHp = type.GetProperty("MinInitialHp")?.GetValue(instance);
var maxHp = type.GetProperty("MaxInitialHp")?.GetValue(instance);
if (minHp != null) entry["min_hp"] = minHp;
if (maxHp != null) entry["max_hp"] = maxHp;
}
catch { }
var moves = new List<string>();
foreach (var method in type.GetMethods(bindFlags))
{
if (method.Name.EndsWith("Move")
&& method.DeclaringType == type
&& method.Name != "PerformMove"
&& method.Name != "RollMove"
&& method.Name != "SetMoveImmediate")
{
moves.Add(method.Name.Replace("Move", ""));
}
}
if (moves.Count > 0)
entry["moves"] = moves
.Distinct(StringComparer.Ordinal)
.OrderBy(move => move, StringComparer.Ordinal)
.ToList();
monsters.Add(entry);
}
var encounters = new List<Dictionary<string, object?>>();
foreach (var type in typeof(EncounterModel).Assembly.GetTypes())
{
if (type.IsAbstract || !type.IsSubclassOf(typeof(EncounterModel)) || type.FullName!.Contains("+")) continue;
var entry = new Dictionary<string, object?>
{
["id"] = ModelId.SlugifyCategory(type.Name),
["class"] = type.Name,
};
try
{
var instance = RuntimeHelpers.GetUninitializedObject(type);
var roomType = type.GetProperty("RoomType")?.GetValue(instance);
var isWeak = type.GetProperty("IsWeak")?.GetValue(instance);
var minGold = type.GetProperty("MinGoldReward")?.GetValue(instance);
var maxGold = type.GetProperty("MaxGoldReward")?.GetValue(instance);
if (roomType != null) entry["room_type"] = roomType.ToString();
if (isWeak != null) entry["is_weak"] = isWeak;
if (minGold != null) entry["min_gold"] = minGold;
if (maxGold != null) entry["max_gold"] = maxGold;
}
catch { }
try
{
var allMonstersMethod = type.GetProperty("AllPossibleMonsters");
if (allMonstersMethod != null)
{
foreach (var method in type.GetMethods(bindFlags))
{
if (method.Name == "GenerateMonsters" && method.DeclaringType == type)
break;
}
}
}
catch { }
var baseName = type.Name.Replace("Normal", "").Replace("Weak", "").Replace("Elite", "").Replace("Boss", "");
var matchingMonsters = new List<string>();
foreach (var monsterEntry in monsters)
{
var monsterClass = monsterEntry["class"] as string ?? "";
if (baseName.Contains(monsterClass) || monsterClass.Contains(baseName.TrimEnd('s')))
matchingMonsters.Add(monsterClass);
}
if (matchingMonsters.Count > 0)
entry["likely_monsters"] = matchingMonsters
.Distinct(StringComparer.Ordinal)
.OrderBy(monster => monster, StringComparer.Ordinal)
.ToList();
encounters.Add(entry);
}
var orderedMonsters = monsters
.OrderBy(entry => entry.TryGetValue("id", out var id) ? id?.ToString() : "", StringComparer.Ordinal)
.ToList();
var orderedEncounters = encounters
.OrderBy(entry => entry.TryGetValue("id", out var id) ? id?.ToString() : "", StringComparer.Ordinal)
.ToList();
return new Dictionary<string, object?>
{
["status"] = "ok",
["kind"] = "bestiary",
["source"] = "reflected MonsterModel and EncounterModel metadata",
["monster_count"] = orderedMonsters.Count,
["encounter_count"] = orderedEncounters.Count,
["monsters"] = orderedMonsters,
["encounters"] = orderedEncounters
};
}
}