-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
1274 lines (1115 loc) · 44.6 KB
/
Copy pathapp.py
File metadata and controls
1274 lines (1115 loc) · 44.6 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
from __future__ import annotations
import argparse
import hashlib
import json
import mimetypes
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import urllib.request
import webbrowser
import winreg
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
APP_VERSION = "0.1.10"
APP_CN_NAME = "异环光追解锁面板"
APP_FULL_CN_NAME = "异环光线追踪 / 全景光追一键解锁工具"
APP_EN_NAME = "NTE Ray Tracing Panel"
APP_SEARCH_KEYWORDS = [
"异环怎么开光追",
"异环光追怎么开",
"异环全景光追怎么开",
"异环没有光追选项",
"异环光追打不开",
"异环光追开不了",
"异环光追解锁",
"异环光追一键开启",
"异环光追一键部署",
"异环光追一键安装",
"异环开光追工具",
"异环光追工具",
"异环光追补丁",
"异环光线追踪怎么开",
"异环光线追踪开启",
"异环全景光追",
"异环全景光追开启",
"异环光追开启",
"异环光追选项不显示",
"异环光追灰色",
"异环 5060 没有光追",
"异环 4060 没有光追",
"异环 RTX 5060 怎么开光追",
"异环 RTX 4060 怎么开光追",
"异环 RTX 5060 开光追",
"异环 RTX 4060 开光追",
"异环显卡伪装",
"异环 不改注册表 光追",
"异环 winmm.dll 光追",
"异环 winmm.dll 一键安装",
"异环 HTGame.exe 光追",
"异环 OptiScaler",
"异环 OptiScaler 一键安装",
"异环 RTX 5090 spoof",
"异环 RTX 4090 spoof",
"异环 RTX 5080M spoof",
"NTE how to enable ray tracing",
"how to enable ray tracing in NTE",
"NTE no ray tracing option",
"NTE ray tracing fix",
"NTE ray tracing tool",
"NTE one-click ray tracing unlock",
"NTE one-click OptiScaler install",
"NTE ray tracing unlock",
"Neverness To Everness ray tracing",
"Neverness To Everness ray tracing unlock",
"Neverness To Everness how to enable ray tracing",
"Neverness To Everness no ray tracing option",
"NTE ray tracing option missing",
"NTE ray tracing not showing",
"NTE GPU spoof",
"NTE OptiScaler DXGI spoof",
"Ananta how to enable ray tracing",
"Ananta no ray tracing option",
"Ananta path tracing",
"Ananta ray tracing unlock",
]
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 22642
GITHUB_RELEASE_API = "https://api.github.com/repos/optiscaler/OptiScaler/releases/latest"
GAME_EXE = "HTGame.exe"
RUN_DIR = Path(sys.executable).resolve().parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent
RESOURCE_DIR = Path(getattr(sys, "_MEIPASS", RUN_DIR))
WEB_DIR = RESOURCE_DIR / "web"
TOOLS_DIR = RUN_DIR / "tools" / "optiscaler"
MANIFEST_OWNER = "nte-ray-tracing-panel"
RUNTIME_LAYOUT = "rt-optiscaler-winmm-v2"
MANAGED_FILES = (
"winmm.dll",
"OptiScaler.ini",
"OptiScaler.log",
)
MANAGED_DIRS = ("OptiScaler",)
CANONICAL_MANAGED_RELS = {name.lower() for name in (*MANAGED_FILES, *MANAGED_DIRS)}
DLSS_PANEL_RELS = {"nvngx.dll", "dlsstweaks.ini", "dlsstweaks.log"}
BACKUP_DIR_NAME = "_nte_rt_backups"
FALLBACK_LOCAL_PROFILE = {
"id": "local",
"label": "本机原配置",
"gpuName": "NVIDIA GeForce RTX 5060 Laptop GPU",
"vendorId": "0x10de",
"deviceId": "0x2d19",
"vramGb": "auto",
"description": "使用当前机器检测到的 NVIDIA 显卡名称和 DeviceId,适合回到本机识别。",
}
STATIC_PROFILES = {
"rtx5090": {
"id": "rtx5090",
"label": "RTX 5090",
"gpuName": "NVIDIA GeForce RTX 5090",
"vendorId": "0x10de",
"deviceId": "0x2B85",
"vramGb": "32",
"description": "当前默认推荐目标,使用 32GB VRAM 的 RTX 5090 白名单配置。",
},
"rtx4090": {
"id": "rtx4090",
"label": "RTX 4090",
"gpuName": "NVIDIA GeForce RTX 4090",
"vendorId": "0x10de",
"deviceId": "0x2684",
"vramGb": "16",
"description": "已验证可正常显示光线追踪选项的备用白名单目标。",
},
"rtx5080m": {
"id": "rtx5080m",
"label": "RTX 5080M",
"gpuName": "NVIDIA GeForce RTX 5080 Laptop GPU",
"vendorId": "0x10de",
"deviceId": "0x2C59",
"vramGb": "16",
"description": "实验性目标,保留用于对照测试,不作为默认推荐。",
},
}
DEFAULT_PROFILE_ID = "rtx5090"
class AppError(Exception):
def __init__(self, message: str, status: int = 400):
super().__init__(message)
self.status = status
def safe_log(message: str, *, error: bool = False) -> None:
stream = sys.stderr if error else sys.stdout
if stream is None:
return
try:
stream.write(message + "\n")
stream.flush()
except Exception:
pass
def now_id() -> str:
stamp = datetime.now()
return stamp.strftime("%Y%m%d-%H%M%S") + f"-{stamp.microsecond // 1000:03d}"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest().upper()
def normalize_rel(rel: str) -> str:
return rel.replace("/", "\\").strip("\\").lower()
def rel_name(rel: str) -> str:
return normalize_rel(rel).split("\\")[-1]
def is_dlss_panel_rel(rel: str) -> bool:
return rel_name(rel) in DLSS_PANEL_RELS
def is_canonical_managed_rel(rel: str) -> bool:
return normalize_rel(rel) in CANONICAL_MANAGED_RELS
def contains_bytes(path: Path, needle: bytes, *, limit: int | None = None) -> bool:
if not path.is_file():
return False
remaining = limit
with path.open("rb") as fh:
while True:
if remaining is not None and remaining <= 0:
return False
size = 1024 * 1024 if remaining is None else min(1024 * 1024, remaining)
chunk = fh.read(size)
if not chunk:
return False
if needle in chunk:
return True
if remaining is not None:
remaining -= len(chunk)
def looks_like_optiscaler_proxy(path: Path) -> bool:
try:
return path.is_file() and path.stat().st_size > 1_000_000 and contains_bytes(path, b"OptiScaler")
except OSError:
return False
def looks_like_rt_optiscaler_ini(path: Path) -> bool:
if not path.is_file():
return False
text = path.read_text(encoding="utf-8", errors="replace")
return "OptiDllPath" in text and r".\OptiScaler" in text and "TargetProcessName=HTGame.exe" in text
def looks_like_optiscaler_dir(path: Path) -> bool:
if not path.is_dir():
return False
return (path / "_source_OptiScaler.ini").is_file() or any(path.glob("*.dll"))
def looks_like_optiscaler_log(path: Path) -> bool:
if not path.is_file():
return False
if path.stat().st_size == 0:
return True
text = path.read_text(encoding="utf-8", errors="replace")
return "OptiScaler" in text
def directory_fingerprint(path: Path) -> dict:
digest = hashlib.sha256()
count = 0
for file in sorted((item for item in path.rglob("*") if item.is_file()), key=lambda item: str(item.relative_to(path)).lower()):
rel = file.relative_to(path).as_posix().lower()
digest.update(rel.encode("utf-8"))
digest.update(b"\0")
digest.update(sha256(file).encode("ascii"))
digest.update(b"\0")
count += 1
return {"exists": True, "kind": "dir", "fileCount": count, "sha256": digest.hexdigest().upper()}
def item_fingerprint(path: Path) -> dict:
if not path.exists():
return {"exists": False}
if path.is_dir():
return directory_fingerprint(path)
return {
"exists": True,
"kind": "file",
"size": path.stat().st_size,
"sha256": sha256(path),
}
def fingerprint_matches(path: Path, expected: dict | None) -> bool:
if not expected:
return False
current = item_fingerprint(path)
if bool(current.get("exists")) != bool(expected.get("exists")):
return False
if not current.get("exists"):
return True
return current.get("kind") == expected.get("kind") and current.get("sha256") == expected.get("sha256")
def ensure_under(path: Path, base: Path) -> Path:
resolved = path.resolve()
root = base.resolve()
if resolved != root and root not in resolved.parents:
raise AppError(f"拒绝操作工作目录外路径: {resolved}", 500)
return resolved
def run_command(args: list[str], *, timeout: int = 30) -> subprocess.CompletedProcess[str]:
return subprocess.run(
args,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
)
def run_powershell(script: str, *, timeout: int = 15) -> str:
proc = run_command(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script],
timeout=timeout,
)
if proc.returncode != 0:
raise AppError(proc.stderr.strip() or "PowerShell 命令执行失败。", 500)
return proc.stdout.strip()
def running_processes() -> list[dict]:
try:
text = run_powershell(
"Get-Process HTGame,NTEGame,NTEBrowser,NTEWebBooster -ErrorAction SilentlyContinue | "
"Select-Object ProcessName,Id,Path | ConvertTo-Json -Compress",
timeout=8,
)
except Exception:
return []
if not text:
return []
try:
data = json.loads(text)
except json.JSONDecodeError:
return []
if isinstance(data, dict):
data = [data]
return data if isinstance(data, list) else []
def close_game_processes() -> list[dict]:
before = running_processes()
if not before:
return []
run_powershell(
"Get-Process HTGame,NTEGame,NTEBrowser,NTEWebBooster -ErrorAction SilentlyContinue | Stop-Process -Force",
timeout=15,
)
time.sleep(1.5)
return before
def procmon_filter_state() -> dict:
try:
proc = run_command(["fltmc", "filters"], timeout=6)
except Exception as exc:
return {"available": False, "present": False, "message": str(exc)}
text = (proc.stdout or "") + (proc.stderr or "")
present = "PROCMON" in text.upper()
return {
"available": proc.returncode == 0,
"present": present,
"message": "检测到 PROCMON 过滤驱动,建议重启后再启动游戏。" if present else "未检测到 PROCMON 过滤驱动。",
}
def get_nvidia_adapters() -> list[dict]:
try:
text = run_powershell(
"Get-CimInstance Win32_VideoController | "
"Select-Object Name,PNPDeviceID,DriverVersion,AdapterRAM,VideoProcessor | ConvertTo-Json -Compress",
timeout=10,
)
except Exception:
return []
if not text:
return []
try:
data = json.loads(text)
except json.JSONDecodeError:
return []
if isinstance(data, dict):
data = [data]
rows = []
for item in data:
pnp = item.get("PNPDeviceID") or ""
if "VEN_10DE" not in pnp.upper() and "NVIDIA" not in (item.get("Name") or "").upper():
continue
device_match = re.search(r"DEV_([0-9A-Fa-f]{4})", pnp)
device_id = f"0x{device_match.group(1).lower()}" if device_match else None
item["DeviceIdHex"] = device_id
item["Registry"] = read_device_registry(pnp)
rows.append(item)
return rows
def local_profile_from_adapter(adapters: list[dict] | None = None) -> dict:
profile = dict(FALLBACK_LOCAL_PROFILE)
adapter = adapters[0] if adapters else None
if adapter:
profile["gpuName"] = adapter.get("Name") or profile["gpuName"]
profile["deviceId"] = adapter.get("DeviceIdHex") or profile["deviceId"]
profile["description"] = f"当前检测到的本机显卡:{profile['gpuName']} / {profile['deviceId']}。"
return profile
def spoof_profiles(adapters: list[dict] | None = None) -> list[dict]:
return [
local_profile_from_adapter(adapters),
dict(STATIC_PROFILES["rtx5090"]),
dict(STATIC_PROFILES["rtx4090"]),
dict(STATIC_PROFILES["rtx5080m"]),
]
def resolve_profile(profile_id: str | None, adapters: list[dict] | None = None) -> dict:
selected = (profile_id or DEFAULT_PROFILE_ID).strip().lower()
if selected == "local":
return local_profile_from_adapter(adapters)
if selected in STATIC_PROFILES:
return dict(STATIC_PROFILES[selected])
raise AppError("目标显卡配置无效。")
def read_device_registry(pnp_device_id: str) -> dict:
if not pnp_device_id:
return {}
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, rf"SYSTEM\CurrentControlSet\Enum\{pnp_device_id}") as key:
result = {}
for value in ("DeviceDesc", "FriendlyName"):
try:
result[value], _ = winreg.QueryValueEx(key, value)
except FileNotFoundError:
result[value] = None
return result
except OSError:
return {}
def expand_user_path(value: str | None) -> Path:
if not value or not value.strip():
raise AppError("请选择或输入游戏路径。")
cleaned = value.strip().strip('"')
return Path(os.path.expandvars(cleaned)).expanduser()
def likely_game_paths(base: Path) -> list[Path]:
return [
base / GAME_EXE,
base / "Client" / "WindowsNoEditor" / "HT" / "Binaries" / "Win64" / GAME_EXE,
base / "WindowsNoEditor" / "HT" / "Binaries" / "Win64" / GAME_EXE,
base / "HT" / "Binaries" / "Win64" / GAME_EXE,
base / "Binaries" / "Win64" / GAME_EXE,
]
def limited_find_game(base: Path, limit: int = 160000) -> Path | None:
if not base.is_dir():
return None
skipped = {"$RECYCLE.BIN", "System Volume Information", "Saved", "Logs", "UserData", "cef_cache_0"}
checked = 0
for root, dirs, files in os.walk(base):
dirs[:] = [d for d in dirs if d not in skipped and not d.startswith(".")]
checked += len(files)
if GAME_EXE in files:
return Path(root) / GAME_EXE
if checked > limit:
break
return None
def detect_game(path_value: str | None) -> dict:
base = expand_user_path(path_value)
if not base.exists():
raise AppError("路径不存在。")
exe: Path | None = None
if base.is_file():
if base.name.lower() != GAME_EXE.lower():
raise AppError("请选择异环安装根目录、Win64 文件夹,或 HTGame.exe。")
exe = base
else:
for candidate in likely_game_paths(base):
if candidate.is_file():
exe = candidate
break
if exe is None:
exe = limited_find_game(base)
if exe is None:
raise AppError("没有找到 HTGame.exe。")
win64 = exe.parent
return {
"input": str(base),
"exe": str(exe),
"win64": str(win64),
"install": inspect_install(win64),
"backups": list_backups(win64),
}
def common_game_candidates() -> list[Path]:
candidates = []
if os.environ.get("NTE_GAME_PATH"):
candidates.append(Path(os.environ["NTE_GAME_PATH"]))
candidates.extend(Path(f"{drive}:\\Neverness To Everness") for drive in "CDEFGHIJKLMNOPQRSTUVWXYZ")
return candidates
def detect_common_game() -> dict | None:
for candidate in common_game_candidates():
try:
if candidate.exists():
return detect_game(str(candidate))
except Exception:
continue
return None
def run_folder_dialog() -> str | None:
script = r"""
Add-Type -AssemblyName System.Windows.Forms
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
$dialog = New-Object System.Windows.Forms.FolderBrowserDialog
$dialog.Description = '选择异环安装根目录,或选择包含 HTGame.exe 的 Win64 文件夹'
$dialog.ShowNewFolderButton = $false
$form = New-Object System.Windows.Forms.Form
$form.TopMost = $true
$form.ShowInTaskbar = $false
$form.Width = 1
$form.Height = 1
$form.StartPosition = 'CenterScreen'
$result = $dialog.ShowDialog($form)
if ($result -eq [System.Windows.Forms.DialogResult]::OK) { Write-Output $dialog.SelectedPath }
"""
proc = run_command(
["powershell", "-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-Command", script],
timeout=120,
)
if proc.returncode != 0:
raise AppError(proc.stderr.strip() or "文件夹选择器启动失败。", 500)
selected = proc.stdout.strip()
return selected or None
def fetch_latest_release() -> dict:
request = urllib.request.Request(GITHUB_RELEASE_API, headers={"User-Agent": "nte-ray-tracing-panel"})
with urllib.request.urlopen(request, timeout=30) as response:
data = json.loads(response.read().decode("utf-8"))
assets = data.get("assets") or []
asset = next((item for item in assets if str(item.get("name", "")).lower().endswith(".7z")), None)
if not asset:
raise AppError("OptiScaler 最新 Release 没有找到 .7z 资产。", 502)
return {
"tag": data.get("tag_name"),
"name": data.get("name"),
"url": data.get("html_url"),
"published": data.get("published_at"),
"assetName": asset.get("name"),
"assetUrl": asset.get("browser_download_url"),
}
def download_file(url: str, target: Path) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
request = urllib.request.Request(url, headers={"User-Agent": "nte-ray-tracing-panel"})
with urllib.request.urlopen(request, timeout=120) as response, target.open("wb") as fh:
shutil.copyfileobj(response, fh)
def short_error(value: object, *, limit: int = 1600) -> str:
text = str(value or "").strip()
if not text:
return "无详细错误。"
if len(text) > limit:
return text[:limit].rstrip() + "..."
return text
def reset_extract_dir(extract_dir: Path) -> Path:
target = ensure_under(extract_dir, TOOLS_DIR)
if target.exists():
shutil.rmtree(target)
target.mkdir(parents=True, exist_ok=True)
return target
def optiscaler_extract_error(archive: Path, extract_dir: Path, attempts: list[dict]) -> AppError:
details = "\n".join(f"- {item['method']}: {item['error']}" for item in attempts)
message = (
"OptiScaler 已下载,但自动解压失败。\n\n"
"原因:自动解压链路没有成功。常见情况是当前 Windows tar.exe 不支持 "
"OptiScaler .7z 使用的 LZMA/LZMA2/BCJ2 压缩格式。\n\n"
"你可以:\n"
"1. 点击“重新下载/准备 OptiScaler”重试。\n"
f"2. 或手动解压下载到的 .7z:{archive}\n"
f" 把包含 OptiScaler.dll 和 OptiScaler.ini 的文件放到 {extract_dir} 目录。\n\n"
f"解压尝试:\n{details}"
)
return AppError(message, 500)
def seven_zip_executable_candidates() -> list[str]:
names = ("7zz.exe", "7z.exe", "7za.exe") if os.name == "nt" else ("7zz", "7z", "7za")
candidates: list[Path] = []
for root in (RUN_DIR, RESOURCE_DIR):
for name in names:
candidates.append(root / "tools" / "7zip" / name)
candidates.append(root / name)
for env_name in ("ProgramFiles", "ProgramFiles(x86)"):
program_root = os.environ.get(env_name)
if program_root:
for name in names:
candidates.append(Path(program_root) / "7-Zip" / name)
resolved: list[str] = []
seen = set()
for candidate in candidates:
if candidate.is_file():
text = str(candidate)
key = text.lower()
if key not in seen:
seen.add(key)
resolved.append(text)
for name in names:
found = shutil.which(name)
if found:
key = found.lower()
if key not in seen:
seen.add(key)
resolved.append(found)
return resolved
def extract_with_py7zz(archive: Path, extract_dir: Path) -> None:
import logging
import py7zz
logging.getLogger("py7zz").setLevel(logging.WARNING)
with py7zz.SevenZipFile(archive, mode="r") as seven_zip:
seven_zip.extractall(path=str(extract_dir))
def extract_with_py7zr(archive: Path, extract_dir: Path) -> None:
import py7zr
with py7zr.SevenZipFile(archive, mode="r") as seven_zip:
seven_zip.extractall(path=str(extract_dir))
def extract_with_7zip_command(executable: str, archive: Path, extract_dir: Path) -> None:
proc = run_command([executable, "x", "-y", f"-o{extract_dir}", str(archive)], timeout=180)
if proc.returncode != 0:
raise RuntimeError(short_error(proc.stderr or proc.stdout or "7-Zip 解压失败。"))
def extract_archive(archive: Path, extract_dir: Path) -> dict:
attempts: list[dict] = []
if archive.name.lower().endswith(".7z"):
try:
reset_extract_dir(extract_dir)
extract_with_py7zz(archive, extract_dir)
return {"method": "py7zz", "fallbacks": attempts}
except Exception as exc:
attempts.append({"method": "py7zz", "error": short_error(exc)})
try:
reset_extract_dir(extract_dir)
extract_with_py7zr(archive, extract_dir)
return {"method": "py7zr", "fallbacks": attempts}
except Exception as exc:
attempts.append({"method": "py7zr", "error": short_error(exc)})
seven_zip_candidates = seven_zip_executable_candidates()
for executable in seven_zip_candidates:
try:
reset_extract_dir(extract_dir)
extract_with_7zip_command(executable, archive, extract_dir)
return {"method": f"7-Zip ({Path(executable).name})", "fallbacks": attempts}
except Exception as exc:
attempts.append({"method": f"7-Zip ({executable})", "error": short_error(exc)})
if not seven_zip_candidates:
attempts.append({"method": "7-Zip executable", "error": "未找到 bundled 或已安装的 7z.exe / 7zz.exe。"})
tar = shutil.which("tar")
if tar:
try:
reset_extract_dir(extract_dir)
proc = run_command([tar, "-xf", str(archive), "-C", str(extract_dir)], timeout=180)
if proc.returncode != 0:
raise RuntimeError(short_error(proc.stderr or proc.stdout or "tar.exe 解压失败。"))
return {"method": "tar.exe", "fallbacks": attempts}
except Exception as exc:
attempts.append({"method": "tar.exe", "error": short_error(exc)})
else:
attempts.append({"method": "tar.exe", "error": "未找到 Windows tar.exe。"})
reset_extract_dir(extract_dir)
raise optiscaler_extract_error(archive, extract_dir, attempts)
def find_optiscaler_stage() -> dict | None:
if not TOOLS_DIR.is_dir():
return None
candidates = []
for folder in TOOLS_DIR.iterdir():
if not folder.is_dir():
continue
dll = next(folder.rglob("OptiScaler.dll"), None)
ini = next(folder.rglob("OptiScaler.ini"), None)
if dll and ini:
candidates.append((folder.stat().st_mtime, folder, dll, ini))
if not candidates:
return None
_, folder, dll, ini = sorted(candidates, reverse=True)[0]
return {"dir": str(folder), "dll": str(dll), "ini": str(ini), "tag": folder.name}
def ensure_optiscaler(force: bool = False) -> dict:
existing = find_optiscaler_stage()
if existing and not force:
existing["downloaded"] = False
return existing
release = fetch_latest_release()
archive = TOOLS_DIR / str(release["assetName"])
extract_dir = TOOLS_DIR / str(release["tag"])
if force and extract_dir.exists():
ensure_under(extract_dir, TOOLS_DIR)
shutil.rmtree(extract_dir)
if force or not archive.is_file():
download_file(str(release["assetUrl"]), archive)
extraction = extract_archive(archive, extract_dir)
stage = find_optiscaler_stage()
if not stage:
raise AppError("OptiScaler 已下载但未找到 OptiScaler.dll。", 500)
stage.update({"downloaded": True, "release": release, "archive": str(archive), "extractor": extraction["method"]})
return stage
def list_backups(win64: Path) -> list[dict]:
root = win64 / BACKUP_DIR_NAME
if not root.is_dir():
return []
rows = []
for folder in sorted(root.iterdir(), reverse=True):
manifest = folder / "manifest.json"
if not manifest.is_file():
continue
try:
data = json.loads(manifest.read_text(encoding="utf-8"))
except Exception:
data = {}
rows.append({
"id": folder.name,
"path": str(folder),
"created": data.get("created"),
"owner": data.get("owner") or data.get("tool"),
"runtimeLayout": data.get("runtimeLayout"),
"mode": data.get("mode"),
"profile": data.get("profile", {}).get("label") or data.get("profile", {}).get("gpuName"),
"operations": data.get("operations", []),
})
return rows
def read_ini_values(path: Path) -> dict:
if not path.is_file():
return {}
values: dict[str, str] = {}
wanted = {
"SpoofedGPUName",
"SpoofedVendorId",
"SpoofedDeviceId",
"TargetVendorId",
"TargetDeviceId",
"StreamlineSpoofing",
"Dxgi",
"DxgiVRAM",
"Registry",
"User32",
"UseFakenvapi",
"TargetProcessName",
"OptiDllPath",
"HookOriginalNvngxOnly",
}
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
match = re.match(r"\s*([A-Za-z0-9_]+)\s*=\s*(.*)\s*$", line)
if match and match.group(1) in wanted:
values[match.group(1)] = match.group(2)
return values
def read_log_summary(path: Path) -> dict:
if not path.is_file():
return {"exists": False, "loaded": False, "spoofMentioned": False, "tail": ""}
text = path.read_text(encoding="utf-8", errors="replace")
tail = "\n".join(text.splitlines()[-120:])
return {
"exists": True,
"size": path.stat().st_size,
"modified": path.stat().st_mtime,
"loaded": "OptiScaler" in text,
"spoofMentioned": "Spoof" in text or "spoof" in text,
"tail": tail,
}
def file_summary(path: Path) -> dict:
if not path.is_file():
return {"exists": False}
return {
"exists": True,
"size": path.stat().st_size,
"modified": path.stat().st_mtime,
"sha256": sha256(path),
}
def inspect_install(win64: Path) -> dict:
winmm = win64 / "winmm.dll"
opt_ini = win64 / "OptiScaler.ini"
opt_dir = win64 / "OptiScaler"
nvngx = win64 / "nvngx.dll"
dlsstweaks_ini = win64 / "dlsstweaks.ini"
winmm_info = None
if winmm.is_file():
winmm_info = {
"size": winmm.stat().st_size,
"modified": winmm.stat().st_mtime,
"sha256": sha256(winmm),
"looksLikeOptiScaler": looks_like_optiscaler_proxy(winmm),
}
dlss_panel_installed = nvngx.is_file() and dlsstweaks_ini.is_file()
info = {
"win64": str(win64),
"installed": bool(winmm_info and winmm_info["looksLikeOptiScaler"] and opt_ini.is_file()),
"runtimeLayout": RUNTIME_LAYOUT,
"managedBy": MANIFEST_OWNER,
"winmm": winmm_info,
"optScalerIni": read_ini_values(opt_ini),
"optScalerDirExists": opt_dir.is_dir(),
"log": read_log_summary(win64 / "OptiScaler.log"),
"dlssPanel": {
"installed": dlss_panel_installed,
"status": (
"检测到 nvngx.dll + dlsstweaks.ini;DLSS Panel 已安装,RT Panel 只显示兼容状态,不接管这些文件。"
if dlss_panel_installed
else "未检测到 nvngx.dll + dlsstweaks.ini 的 DLSS Panel 布局。"
),
"nvngx": file_summary(nvngx),
"dlsstweaksIni": file_summary(dlsstweaks_ini),
},
}
return info
def backup_path_for(rel: str, backup_dir: Path) -> Path:
return backup_dir / "files" / rel
def backup_item(game_dir: Path, rel: str, backup_dir: Path, *, kind: str) -> dict:
source = ensure_under(game_dir / rel, game_dir)
record = {
"rel": rel,
"kind": kind,
"owner": MANIFEST_OWNER,
"runtimeLayout": RUNTIME_LAYOUT,
"existed": source.exists(),
}
if not source.exists():
return record
destination = backup_path_for(rel, backup_dir)
destination.parent.mkdir(parents=True, exist_ok=True)
if source.is_dir():
shutil.copytree(source, destination)
record["backupRel"] = str(Path("files") / rel)
else:
shutil.copy2(source, destination)
record.update({
"backupRel": str(Path("files") / rel),
"size": source.stat().st_size,
"sha256": sha256(source),
})
return record
def current_target_looks_rt_owned(target: Path, rel: str) -> bool:
rel = normalize_rel(rel)
if not target.exists():
return True
if rel == "winmm.dll":
return looks_like_optiscaler_proxy(target)
if rel == "optiscaler.ini":
return looks_like_rt_optiscaler_ini(target)
if rel == "optiscaler.log":
return looks_like_optiscaler_log(target)
if rel == "optiscaler":
return looks_like_optiscaler_dir(target)
return False
def restore_record_allowed(record: dict) -> tuple[bool, str | None]:
rel = str(record.get("rel", ""))
if not rel:
return False, "跳过未知记录:缺少 rel"
if is_dlss_panel_rel(rel):
return False, f"跳过 {rel}:DLSS Panel 文件不由 RT Panel 恢复"
if not is_canonical_managed_rel(rel):
return False, f"跳过 {rel}:不属于当前 RT Panel runtime layout"
owner = record.get("owner")
if owner and owner != MANIFEST_OWNER:
return False, f"跳过 {rel}:manifest owner={owner}"
return True, None
def restore_item(game_dir: Path, backup_dir: Path, record: dict) -> str:
allowed, reason = restore_record_allowed(record)
if not allowed:
return reason or "跳过未知记录"
rel = record["rel"]
target = ensure_under(game_dir / rel, game_dir)
installed = record.get("installed")
if target.exists():
if installed:
safe_to_replace = fingerprint_matches(target, installed)
if not safe_to_replace and normalize_rel(rel) == "optiscaler.log":
safe_to_replace = looks_like_optiscaler_log(target)
else:
safe_to_replace = current_target_looks_rt_owned(target, rel)
if not safe_to_replace:
return f"跳过 {rel}:当前目标不像本工具写入的版本,避免覆盖其他文件"
if target.exists():
if target.is_dir():
shutil.rmtree(target)
else:
target.unlink()
if record.get("existed") and record.get("backupRel"):
source = ensure_under(backup_dir / record["backupRel"], backup_dir)
if source.is_dir():
shutil.copytree(source, target)
else:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, target)
return f"恢复 {rel}"
return f"移除 {rel}"
def set_ini_value(lines: list[str], key: str, value: str) -> list[str]:
pattern = re.compile(r"^\s*" + re.escape(key) + r"\s*=")
changed = False
out = []
for line in lines:
if not changed and pattern.match(line):
out.append(f"{key}={value}")
changed = True
else:
out.append(line)
if not changed:
out.append(f"{key}={value}")
return out
def set_ini_section_value(lines: list[str], section: str, key: str, value: str) -> list[str]:
key_pattern = re.compile(r"^\s*" + re.escape(key) + r"\s*=", re.IGNORECASE)
section_pattern = re.compile(r"^\s*\[" + re.escape(section) + r"\]\s*$", re.IGNORECASE)
cleaned = [line for line in lines if not key_pattern.match(line)]
section_index = next((index for index, line in enumerate(cleaned) if section_pattern.match(line)), None)
if section_index is None:
if cleaned and cleaned[-1].strip():
cleaned.append("")
cleaned.extend([f"[{section}]", f"{key}={value}"])
return cleaned
cleaned.insert(section_index + 1, f"{key}={value}")
return cleaned
def build_optiscaler_config(template: Path, *, mode: str, target_device_id: str | None, profile: dict) -> str:
lines = template.read_text(encoding="utf-8", errors="replace").splitlines()
values = {
"SpoofedVendorId": profile["vendorId"],
"SpoofedDeviceId": profile["deviceId"],
"TargetVendorId": "0x10de",
"TargetDeviceId": target_device_id or "auto",
"SpoofedGPUName": profile["gpuName"],
"OptiDllPath": r".\OptiScaler",
"StreamlineSpoofing": "true",
"Dxgi": "true",
"DxgiFactoryWrapping": "false",
"DxgiVRAM": profile["vramGb"],
"Registry": "true" if mode == "full" else "false",
"User32": "true" if mode == "full" else "false",
"UseFakenvapi": "true" if mode == "full" else "false",
"TargetProcessName": GAME_EXE,
"LogToFile": "true",
"LogLevel": "0",
"SingleFile": "true",
"CheckForUpdate": "false",
}
if mode == "full":
values["NvapiPath"] = r".\OptiScaler\fakenvapi.dll"
for key, value in values.items():
lines = set_ini_value(lines, key, value)
lines = set_ini_section_value(lines, "Hooks", "HookOriginalNvngxOnly", "true")
return "\n".join(lines).rstrip() + "\n"
def copy_optiscaler_payload(stage: dict, game_dir: Path) -> None:
dll = Path(stage["dll"])
ini = Path(stage["ini"])
release_root = dll.parent
winmm = game_dir / "winmm.dll"
shutil.copy2(dll, winmm)
if sha256(dll) != sha256(winmm) or not looks_like_optiscaler_proxy(winmm):