-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathapp.js
More file actions
2435 lines (2254 loc) · 69.7 KB
/
Copy pathapp.js
File metadata and controls
2435 lines (2254 loc) · 69.7 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
let createAzaharModuleFactoryPromise = null;
let azaharRuntimeScriptPromise = null;
let azaharRuntimeFormatPromise = null;
const AZAHAR_RUNTIME_SNIFF_LIMIT = 65536;
function looksLikeModuleRuntime(text) {
return text.includes("import.meta") || text.includes("export default createAzaharModule");
}
function looksLikeClassicRuntime(text) {
return (
text.includes("var createAzaharModule =") &&
!text.includes("import.meta") &&
!text.includes("export default createAzaharModule")
);
}
async function detectAzaharRuntimeFormat(src) {
if (azaharRuntimeFormatPromise) {
return azaharRuntimeFormatPromise;
}
azaharRuntimeFormatPromise = (async () => {
const response = await fetch(src, { cache: "no-store" });
if (!response.ok) {
throw new Error(`Failed to inspect Azahar runtime: ${response.status} ${response.statusText}`);
}
if (!response.body) {
const text = await response.text();
if (looksLikeModuleRuntime(text)) return "module";
if (looksLikeClassicRuntime(text)) return "classic";
return "module";
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
const chunks = [];
let totalLength = 0;
while (totalLength < AZAHAR_RUNTIME_SNIFF_LIMIT) {
const { value, done } = await reader.read();
if (done) {
break;
}
if (!value?.length) {
continue;
}
chunks.push(value);
totalLength += value.length;
const snippet = decoder.decode(value, { stream: true });
if (looksLikeModuleRuntime(snippet)) {
await reader.cancel();
return "module";
}
}
await reader.cancel();
const merged = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
merged.set(chunk, offset);
offset += chunk.length;
}
const snippet = decoder.decode(merged);
if (looksLikeModuleRuntime(snippet)) return "module";
if (looksLikeClassicRuntime(snippet)) return "classic";
return "module";
})();
return azaharRuntimeFormatPromise;
}
function loadClassicRuntimeScript(src) {
if (azaharRuntimeScriptPromise) {
return azaharRuntimeScriptPromise;
}
const absoluteSrc = new URL(src, window.location.href).href;
azaharRuntimeScriptPromise = new Promise((resolve, reject) => {
const complete = () => resolve();
const fail = () => reject(new Error(`Failed to load classic Azahar runtime script: ${absoluteSrc}`));
const existing = Array.from(document.scripts).find((script) => script.src === absoluteSrc);
if (existing) {
if (existing.dataset.azaharLoaded === "true") {
resolve();
return;
}
existing.addEventListener("load", () => {
existing.dataset.azaharLoaded = "true";
complete();
}, { once: true });
existing.addEventListener("error", fail, { once: true });
return;
}
const script = document.createElement("script");
script.src = absoluteSrc;
script.async = true;
script.addEventListener("load", () => {
script.dataset.azaharLoaded = "true";
complete();
}, { once: true });
script.addEventListener("error", fail, { once: true });
document.head.append(script);
});
return azaharRuntimeScriptPromise;
}
async function getCreateAzaharModule() {
if (typeof window !== "undefined" && typeof window.createAzaharModule === "function") {
return window.createAzaharModule;
}
if (!createAzaharModuleFactoryPromise) {
const moduleUrl = new URL("./Build/azahar_libretro.js", window.location.href).href;
createAzaharModuleFactoryPromise = (async () => {
const runtimeFormat = await detectAzaharRuntimeFormat(moduleUrl);
if (runtimeFormat === "classic") {
await loadClassicRuntimeScript(moduleUrl);
if (typeof window !== "undefined" && typeof window.createAzaharModule === "function") {
return window.createAzaharModule;
}
throw new Error("Classic Azahar runtime loaded without exposing createAzaharModule");
}
const moduleExports = await import(moduleUrl);
const factory =
moduleExports?.default ||
moduleExports?.createAzaharModule ||
moduleExports;
if (typeof factory !== "function") {
throw new Error("Azahar module factory export was not found");
}
if (typeof window !== "undefined") {
window.createAzaharModule = factory;
}
return factory;
})();
}
return createAzaharModuleFactoryPromise;
}
const RETRO_DEVICE_JOYPAD = 1;
const RETRO_DEVICE_MOUSE = 2;
const RETRO_DEVICE_ANALOG = 5;
const RETRO_DEVICE_POINTER = 6;
const RETRO_DEVICE_INDEX_ANALOG_RIGHT = 1;
const RETRO_DEVICE_ID_ANALOG_X = 0;
const RETRO_DEVICE_ID_ANALOG_Y = 1;
const RETRO_DEVICE_ID_MOUSE_X = 0;
const RETRO_DEVICE_ID_MOUSE_Y = 1;
const RETRO_DEVICE_ID_MOUSE_LEFT = 2;
const RETRO_DEVICE_ID_POINTER_X = 0;
const RETRO_DEVICE_ID_POINTER_Y = 1;
const RETRO_DEVICE_ID_POINTER_PRESSED = 2;
const RETRO_ENVIRONMENT_SET_MESSAGE = 6;
const RETRO_ENVIRONMENT_SET_PIXEL_FORMAT = 10;
const RETRO_ENVIRONMENT_SET_HW_RENDER = 14;
const RETRO_ENVIRONMENT_GET_VARIABLE = 15;
const RETRO_ENVIRONMENT_SET_VARIABLES = 16;
const RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE = 17;
const RETRO_ENVIRONMENT_GET_LOG_INTERFACE = 27;
const RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO = 32;
const RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS = 11;
const RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME = 18;
const RETRO_ENVIRONMENT_SET_MEMORY_MAPS = 36;
const RETRO_ENVIRONMENT_SET_GEOMETRY = 37;
const RETRO_ENVIRONMENT_SET_SERIALIZATION_QUIRKS = 44;
const RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION = 52;
const RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER = 56;
const RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY = 31;
const RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY = 9;
const RETRO_ENVIRONMENT_GET_CAN_DUPE = 3;
const RETRO_ENVIRONMENT_EXPERIMENTAL = 0x10000;
const RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE =
25 | RETRO_ENVIRONMENT_EXPERIMENTAL;
const RETRO_ENVIRONMENT_GET_MICROPHONE_INTERFACE =
75 | RETRO_ENVIRONMENT_EXPERIMENTAL;
const RETRO_ENVIRONMENT_SET_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE =
43 | RETRO_ENVIRONMENT_EXPERIMENTAL;
const RETRO_ENVIRONMENT_SET_HW_SHARED_CONTEXT =
44 | RETRO_ENVIRONMENT_EXPERIMENTAL;
const RETRO_HW_CONTEXT_OPENGL_CORE = 3;
const RETRO_HW_CONTEXT_OPENGLES3 = 4;
const RETRO_HW_FRAME_BUFFER_VALID = -1;
const PIXEL_XRGB8888 = 1;
const PIXEL_RGB565 = 2;
const HW_RENDER_CONTEXT_TYPE_OFFSET = 0;
const HW_RENDER_CONTEXT_RESET_OFFSET = 4;
const HW_RENDER_GET_FRAMEBUFFER_OFFSET = 8;
const HW_RENDER_GET_PROC_ADDRESS_OFFSET = 12;
const HW_RENDER_VERSION_MAJOR_OFFSET = 20;
const HW_RENDER_VERSION_MINOR_OFFSET = 24;
const HW_RENDER_CONTEXT_DESTROY_OFFSET = 32;
const urlSearchParams =
typeof window !== "undefined"
? new URLSearchParams(window.location.search)
: null;
const rendererQuery = urlSearchParams?.get("renderer") || "";
const hwShadersQuery = urlSearchParams?.get("hwshaders") || "";
const rendererPreset =
rendererQuery === "software"
? "software"
: rendererQuery === "webgl-full"
? "webgl-full"
: "webgl-hybrid";
const HOMEBREW_EXTENSIONS = new Set(["3dsx", "z3dsx", "elf", "axf"]);
const CORE_AUDIO_SAMPLE_RATE = 32728;
const state = {
module: null,
exports: {},
callbacks: [],
coreLoaded: false,
coreLoadPromise: null,
gameLoaded: false,
romFile: null,
romBytes: null,
romHash: "",
romName: "",
romVirtualPath: "",
animFrame: 0,
pixelFormat: PIXEL_XRGB8888,
frameWidth: 400,
frameHeight: 480,
framePitch: 1600,
variables: new Map(),
variablePointers: new Map(),
variableUpdated: false,
saveDirPtr: 0,
systemDirPtr: 0,
lastFrame: null,
keys: new Set(),
pointerX: 0,
pointerY: 0,
pointerPressed: false,
mouseLeft: false,
fpsFrames: 0,
fpsLastUpdate: performance.now(),
fpsValue: 0,
audioContext: null,
audioNextTime: 0,
audioLeadTime: 0.03,
audioMaxBacklog: 0.15,
audioSources: new Set(),
audioUnavailableLogged: false,
audioUnlockedLogged: false,
canvas2dContext: null,
webglContext: null,
webglContextHandle: 0,
usingHardwareVideo: false,
hwContextType: 0,
hwContextResetPtr: 0,
hwContextDestroyPtr: 0,
hwFramebufferCallbackPtr: 0,
hwProcAddressCallbackPtr: 0,
softwarePresentStride: 1,
softwareFrameCounter: 0,
sdImportCount: 0,
rendererPreset,
experimentalHardwareRenderer: rendererPreset !== "software",
experimentalHardwareShaders:
rendererPreset === "webgl-full" ||
(rendererPreset === "webgl-hybrid" && hwShadersQuery === "on"),
softwareKeyboardOpen: false,
softwareKeyboardOkButton: 0,
softwareKeyboardCancelButton: -1,
};
const elements = {
loadCore: document.querySelector("#load-core"),
resetCore: document.querySelector("#reset-core"),
stopCore: document.querySelector("#stop-core"),
bootGame: document.querySelector("#boot-game"),
unloadGame: document.querySelector("#unload-game"),
romInput: document.querySelector("#rom-input"),
sdImportFiles: document.querySelector("#sd-import-files"),
sdImportFolder: document.querySelector("#sd-import-folder"),
sdStatusText: document.querySelector("#sd-status-text"),
romName: document.querySelector("#rom-name span"),
coreStatus: document.querySelector("#core-status"),
coreStatusText: document.querySelector("#core-status-text"),
log: document.querySelector("#log"),
metaLibrary: document.querySelector("#meta-library"),
metaRom: document.querySelector("#meta-rom"),
metaStateSize: document.querySelector("#meta-state-size"),
metaFrame: document.querySelector("#meta-frame"),
metaFps: document.querySelector("#meta-fps"),
emptyState: document.querySelector("#empty-state"),
saveStateButton: document.querySelector("#save-state-btn"),
exportState: document.querySelector("#export-state"),
importState: document.querySelector("#import-state"),
slotGrid: document.querySelector("#slot-grid"),
canvas: document.querySelector("#screen"),
softwareCanvas: document.querySelector("#screen-software"),
runtimePanel: document.querySelector("#runtime-panel"),
runtimeSummary: document.querySelector("#runtime-summary"),
runtimeDetails: document.querySelector("#runtime-details"),
runtimeCopy: document.querySelector("#runtime-copy"),
runtimeDismiss: document.querySelector("#runtime-dismiss"),
softwareKeyboard: document.querySelector("#software-keyboard"),
softwareKeyboardForm: document.querySelector("#software-keyboard-form"),
softwareKeyboardHint: document.querySelector("#software-keyboard-hint"),
softwareKeyboardError: document.querySelector("#software-keyboard-error"),
softwareKeyboardInput: document.querySelector("#software-keyboard-input"),
softwareKeyboardTextarea: document.querySelector(
"#software-keyboard-textarea",
),
softwareKeyboardButtons: document.querySelector("#software-keyboard-buttons"),
};
const imageDataCache = new Map();
const logLines = [];
const MAX_LOG_LINES = 250;
const IGNORED_LOG_PATTERNS = [
"<Debug>",
"called service=",
"Mapping 0x",
"LogLayout:",
"Allocating TLS",
"Registered archive",
"Starting title scan",
"Finished title scan",
"path exists ",
"stat failed on ",
];
function attachCanvasInputHandlers() {
elements.canvas.addEventListener("mousedown", (event) => {
if (state.softwareKeyboardOpen) return;
updatePointerFromClient(event.clientX, event.clientY, true);
elements.canvas.focus?.();
event.preventDefault();
});
elements.canvas.addEventListener(
"touchstart",
(event) => {
if (state.softwareKeyboardOpen) return;
const touch = event.touches[0];
if (!touch) return;
updatePointerFromClient(touch.clientX, touch.clientY, true);
event.preventDefault();
},
{ passive: false },
);
elements.canvas.addEventListener(
"touchmove",
(event) => {
if (state.softwareKeyboardOpen) return;
const touch = event.touches[0];
if (!touch) return;
updatePointerFromClient(touch.clientX, touch.clientY, true);
event.preventDefault();
},
{ passive: false },
);
elements.canvas.addEventListener("touchend", () => {
releasePointer();
});
elements.canvas.addEventListener("touchcancel", () => {
releasePointer();
});
elements.canvas.addEventListener("webglcontextlost", (event) => {
event.preventDefault();
stopRunLoop();
state.usingHardwareVideo = false;
reportRuntimeFailure(
"WebGL context lost",
event.statusMessage || "The browser dropped the WebGL context.",
);
});
elements.canvas.addEventListener("webglcontextrestored", () => {
reportRuntimeFailure(
"WebGL context restored",
"The browser restored WebGL, but the game needs a reboot to recover.",
);
});
}
function resetCanvasElement() {
state.canvas2dContext = null;
state.webglContext = null;
state.lastFrame = null;
if (elements.softwareCanvas) {
elements.softwareCanvas.hidden = true;
}
releasePointer();
}
function logLine(text) {
const stamp = new Date().toLocaleTimeString();
logLines.push(`[${stamp}] ${text}`);
if (logLines.length > MAX_LOG_LINES) {
logLines.splice(0, logLines.length - MAX_LOG_LINES);
}
elements.log.textContent = `${logLines.join("\n")}\n`;
elements.log.scrollTop = elements.log.scrollHeight;
}
function getRecentLogLines(limit = 40) {
return logLines.slice(-limit).join("\n");
}
function shouldIgnoreLog(text) {
return IGNORED_LOG_PATTERNS.some((pattern) => text.includes(pattern));
}
function formatError(error) {
if (error instanceof Error) {
return error.stack || error.message || error.toString();
}
if (typeof error === "string") {
return error;
}
if (error === undefined) {
return "undefined";
}
try {
return JSON.stringify(error);
} catch {
return String(error);
}
}
function setStatus(kind, text) {
elements.coreStatus.className = `status ${kind}`;
elements.coreStatusText.textContent = text;
}
function clearRuntimePanel() {
if (!elements.runtimePanel) {
return;
}
elements.runtimePanel.hidden = true;
elements.runtimeSummary.textContent = "";
elements.runtimeDetails.textContent = "";
}
function showRuntimePanel(summary, details) {
if (!elements.runtimePanel) {
return;
}
elements.runtimeSummary.textContent = summary || "Runtime crash";
elements.runtimeDetails.textContent = details || "No further details.";
elements.runtimePanel.hidden = false;
}
function reportRuntimeFailure(summary, error, options = {}) {
const formattedError = error ? formatError(error) : "";
const summaryText = summary || "Runtime crash";
const detailParts = [];
if (options.note) {
detailParts.push(options.note);
}
if (formattedError) {
detailParts.push(formattedError);
}
const recentLog = getRecentLogLines();
if (recentLog) {
detailParts.push(`Recent log:\n${recentLog}`);
}
logLine(`${summaryText}: ${formattedError || "No error detail available"}`);
setStatus("error", "Runtime crash");
showRuntimePanel(summaryText, detailParts.join("\n\n"));
}
function formatBytes(bytes) {
if (!bytes) return "0 B";
const units = ["B", "KB", "MB", "GB"];
let value = bytes;
let index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index += 1;
}
return `${value.toFixed(value >= 10 || index === 0 ? 0 : 1)} ${units[index]}`;
}
function getFileExtension(name) {
const text = String(name || "");
const dot = text.lastIndexOf(".");
return dot >= 0 ? text.slice(dot + 1).toLowerCase() : "";
}
function isHomebrewFileName(name) {
return HOMEBREW_EXTENSIONS.has(getFileExtension(name));
}
function sanitizePathSegment(name) {
const sanitized = String(name || "")
.replace(/[<>:"|?*\u0000-\u001f]/g, "_")
.replace(/[\\/]/g, "_")
.trim();
if (!sanitized || sanitized === "." || sanitized === "..") {
return "item";
}
return sanitized;
}
function joinFsPath(...parts) {
const segments = parts
.flatMap((part) =>
String(part || "")
.replace(/\\/g, "/")
.split("/"),
)
.filter(Boolean);
return `/${segments.join("/")}`;
}
function getHomebrewAppName(name) {
return sanitizePathSegment(
String(name || "").replace(/\.(?:z3dsx|3dsx|elf|axf)$/i, ""),
);
}
function getDefaultRomVirtualPath(name) {
if (isHomebrewFileName(name)) {
return joinFsPath(
"save",
"sdmc",
"3ds",
getHomebrewAppName(name),
sanitizePathSegment(name),
);
}
return joinFsPath("game", sanitizePathSegment(name));
}
function ensureFsDirectory(path) {
let current = "";
for (const segment of String(path || "")
.replace(/\\/g, "/")
.split("/")
.filter(Boolean)) {
current = `${current}/${segment}`;
if (state.module.FS.analyzePath(current).exists === false) {
state.module.FS.mkdir(current);
}
}
}
function ensureFsParentDirectory(path) {
const segments = String(path || "")
.replace(/\\/g, "/")
.split("/")
.filter(Boolean);
segments.pop();
if (segments.length) {
ensureFsDirectory(segments.join("/"));
}
}
function stageBytesAtPath(path, bytes) {
ensureFsParentDirectory(path);
state.module.FS.writeFile(path, bytes);
}
function updateSdStatus(message = null) {
if (message) {
elements.sdStatusText.textContent = message;
return;
}
if (!state.sdImportCount) {
elements.sdStatusText.textContent = "No SD content staged";
return;
}
elements.sdStatusText.textContent =
state.sdImportCount === 1
? "1 SD file staged"
: `${state.sdImportCount} SD files staged`;
}
function normalizeImportedRelativePath(path, mode) {
const segments = String(path || "")
.replace(/\\/g, "/")
.split("/")
.filter(Boolean)
.map((segment) => sanitizePathSegment(segment));
if (!segments.length) {
return "3ds/item";
}
const first = segments[0]?.toLowerCase();
const second = segments[1]?.toLowerCase();
if (first === "sdmc") {
segments.shift();
} else if (
segments.length > 1 &&
(second === "3ds" || second === "nintendo 3ds")
) {
segments.shift();
}
if (mode === "folder" && segments[0]) {
const root = segments[0].toLowerCase();
if (root !== "3ds" && root !== "nintendo 3ds") {
segments.unshift("3ds");
}
}
return segments.join("/");
}
function buildSdImportPlan(files, mode) {
const list = Array.from(files || []).filter(Boolean);
if (!list.length) {
return [];
}
const executable = list.find((file) => isHomebrewFileName(file.name));
const defaultHomebrewRoot = executable
? joinFsPath("save", "sdmc", "3ds", getHomebrewAppName(executable.name))
: joinFsPath("save", "sdmc", "3ds", `import-${Date.now()}`);
return list.map((file) => {
const relativePath = file.webkitRelativePath
? normalizeImportedRelativePath(file.webkitRelativePath, mode)
: sanitizePathSegment(file.name);
const virtualPath = file.webkitRelativePath
? joinFsPath("save", "sdmc", relativePath)
: joinFsPath(defaultHomebrewRoot, relativePath);
return { file, virtualPath };
});
}
async function selectRomBytes(
file,
bytes,
virtualPath = getDefaultRomVirtualPath(file.name),
) {
state.romFile = file;
state.romBytes = bytes;
state.romName = file.name;
state.romVirtualPath = virtualPath;
state.romHash = await hashBytes(bytes);
elements.romName.textContent = file.name;
elements.metaRom.textContent = file.name;
await refreshSlots();
updateUi();
}
async function selectRomData(name, bytes, options = {}) {
const normalizedBytes = toUint8Array(bytes);
const romName = sanitizePathSegment(name || "game.3ds");
await selectRomBytes(
{ name: romName },
normalizedBytes,
options.virtualPath || getDefaultRomVirtualPath(romName),
);
if (options.log !== false) {
logLine(`Selected ROM ${romName}`);
}
if (isHomebrewFileName(romName) && options.log !== false) {
logLine(`Homebrew will boot from ${state.romVirtualPath}`);
}
return {
name: state.romName,
virtualPath: state.romVirtualPath,
hash: state.romHash,
};
}
async function importSdFiles(files, mode) {
if (!files?.length) {
return;
}
if (!state.coreLoaded) {
await loadCore();
}
const plan = buildSdImportPlan(files, mode);
let selectedExecutable = null;
for (const entry of plan) {
const bytes = new Uint8Array(await entry.file.arrayBuffer());
stageBytesAtPath(entry.virtualPath, bytes);
if (!selectedExecutable && isHomebrewFileName(entry.file.name)) {
selectedExecutable = {
file: entry.file,
bytes,
virtualPath: entry.virtualPath,
};
}
}
state.sdImportCount += plan.length;
updateSdStatus();
if (selectedExecutable) {
await selectRomBytes(
selectedExecutable.file,
selectedExecutable.bytes,
selectedExecutable.virtualPath,
);
logLine(
`Imported ${plan.length} SD file(s) and selected ${selectedExecutable.file.name} for boot`,
);
return;
}
logLine(`Imported ${plan.length} file(s) into the virtual SD card`);
}
async function importSdEntries(entries, options = {}) {
const list = Array.from(entries || []).filter(Boolean);
if (!list.length) {
return [];
}
if (!state.coreLoaded) {
await loadCore();
}
const importedEntries = [];
let selectedExecutable = null;
const defaultRoot = joinFsPath("save", "sdmc", "3ds", `import-${Date.now()}`);
for (const entry of list) {
const name = sanitizePathSegment(entry.name || getPathLeaf(entry.relativePath || entry.virtualPath));
const bytes = toUint8Array(entry.bytes);
let virtualPath = entry.virtualPath;
if (!virtualPath) {
if (entry.relativePath) {
virtualPath = joinFsPath(
"save",
"sdmc",
normalizeImportedRelativePath(entry.relativePath, "folder"),
);
} else if (isHomebrewFileName(name)) {
virtualPath = joinFsPath(
"save",
"sdmc",
"3ds",
getHomebrewAppName(name),
name,
);
} else {
virtualPath = joinFsPath(defaultRoot, name);
}
}
stageBytesAtPath(virtualPath, bytes);
importedEntries.push({ name, virtualPath, size: bytes.byteLength });
if (!selectedExecutable && isHomebrewFileName(name)) {
selectedExecutable = { name, bytes, virtualPath };
}
}
state.sdImportCount += importedEntries.length;
updateSdStatus();
if (selectedExecutable && options.autoSelectExecutable !== false) {
await selectRomData(selectedExecutable.name, selectedExecutable.bytes, {
virtualPath: selectedExecutable.virtualPath,
log: false,
});
if (options.log !== false) {
logLine(
`Imported ${importedEntries.length} SD file(s) and selected ${selectedExecutable.name} for boot`,
);
}
} else if (options.log !== false) {
logLine(`Imported ${importedEntries.length} file(s) into the virtual SD card`);
}
return importedEntries;
}
function updateUi() {
elements.bootGame.disabled = !state.coreLoaded || !state.romBytes;
elements.resetCore.disabled = !state.gameLoaded;
elements.stopCore.disabled = !state.gameLoaded;
elements.unloadGame.disabled = !state.gameLoaded;
elements.saveStateButton.disabled = !state.gameLoaded;
elements.exportState.disabled = !state.gameLoaded;
elements.metaRom.textContent = state.romName || "None";
elements.metaFrame.textContent = `${state.frameWidth} x ${state.frameHeight}`;
elements.metaFps.textContent = state.gameLoaded
? state.fpsValue.toFixed(1)
: "0.0";
elements.emptyState.hidden = state.gameLoaded;
}
function getSoftwareKeyboardField() {
return elements.softwareKeyboardTextarea.hidden
? elements.softwareKeyboardInput
: elements.softwareKeyboardTextarea;
}
function hideSoftwareKeyboard() {
state.softwareKeyboardOpen = false;
state.softwareKeyboardOkButton = 0;
state.softwareKeyboardCancelButton = -1;
elements.softwareKeyboard.hidden = true;
elements.softwareKeyboardHint.textContent = "";
elements.softwareKeyboardError.textContent = "";
elements.softwareKeyboardError.hidden = true;
elements.softwareKeyboardInput.value = "";
elements.softwareKeyboardTextarea.value = "";
elements.softwareKeyboardButtons.replaceChildren();
state.keys.clear();
elements.canvas.focus?.();
}
function submitSoftwareKeyboard(button) {
if (!state.exports.azahar_web_keyboard_submit) return;
state.exports.azahar_web_keyboard_submit(
getSoftwareKeyboardField().value ?? "",
button,
);
}
function addSoftwareKeyboardButton(label, button, primary = false) {
const element = document.createElement("button");
element.type = "button";
element.textContent = label;
if (primary) {
element.classList.add("primary");
}
element.addEventListener("click", () => {
submitSoftwareKeyboard(button);
});
elements.softwareKeyboardButtons.append(element);
}
function showSoftwareKeyboard(config = {}) {
const {
hintText = "",
initialText = "",
errorText = "",
maxTextLength = 32,
multilineMode = false,
buttonConfig = 0,
cancelText = "Cancel",
forgotText = "I Forgot",
okText = "Ok",
} = config;
const singleLine = !multilineMode;
const field = singleLine
? elements.softwareKeyboardInput
: elements.softwareKeyboardTextarea;
const fallbackOkButton = buttonConfig <= 2 ? buttonConfig : 3;
state.softwareKeyboardOpen = true;
state.softwareKeyboardOkButton = fallbackOkButton;
state.softwareKeyboardCancelButton =
buttonConfig >= 1 && buttonConfig <= 2 ? 0 : -1;
state.keys.clear();
releasePointer();
elements.softwareKeyboardInput.hidden = !singleLine;
elements.softwareKeyboardTextarea.hidden = singleLine;
elements.softwareKeyboardInput.maxLength = maxTextLength;
elements.softwareKeyboardTextarea.maxLength = maxTextLength;
field.placeholder = hintText;
field.value = initialText;
elements.softwareKeyboardHint.textContent = hintText;
elements.softwareKeyboardError.textContent = errorText;
elements.softwareKeyboardError.hidden = !errorText;
elements.softwareKeyboardButtons.replaceChildren();
if (buttonConfig === 2) {
addSoftwareKeyboardButton(cancelText, 0);
addSoftwareKeyboardButton(forgotText, 1);
addSoftwareKeyboardButton(okText, 2, true);
} else if (buttonConfig === 1) {
addSoftwareKeyboardButton(cancelText, 0);
addSoftwareKeyboardButton(okText, 1, true);
} else if (buttonConfig === 3) {
addSoftwareKeyboardButton(okText, 3, true);
} else {
addSoftwareKeyboardButton(okText, 0, true);
}
elements.softwareKeyboard.hidden = false;
requestAnimationFrame(() => {
field.focus();
field.select?.();
});
}
function reportSoftwareKeyboardError(message) {
if (!message) return;
logLine(`Software keyboard: ${message}`);
if (state.softwareKeyboardOpen) {
elements.softwareKeyboardError.textContent = message;
elements.softwareKeyboardError.hidden = false;
}
}
window.azaharShowSoftwareKeyboard = showSoftwareKeyboard;
window.azaharHideSoftwareKeyboard = hideSoftwareKeyboard;
window.azaharShowSoftwareKeyboardError = reportSoftwareKeyboardError;
function get2dContext() {
if (!state.canvas2dContext) {
state.canvas2dContext =
elements.softwareCanvas?.getContext("2d", { alpha: false }) || null;
}
return state.canvas2dContext;
}
function syncSoftwareCanvasSize(width, height) {
if (!elements.softwareCanvas) {
return;
}
if (
elements.softwareCanvas.width !== width ||
elements.softwareCanvas.height !== height
) {
elements.softwareCanvas.width = width;
elements.softwareCanvas.height = height;
state.canvas2dContext = null;
}
}
function setSoftwareCanvasVisible(visible) {
if (!elements.softwareCanvas) {
return;
}
elements.softwareCanvas.hidden = !visible;
}
function getWebGlContext() {
if (
!state.webglContext &&
state.webglContextHandle &&
state.module?.GL?.getContext
) {
const registeredContext =
state.module.GL.getContext(state.webglContextHandle)?.GLctx;
if (registeredContext) {
state.webglContext = registeredContext;
}
}
if (!state.webglContext) {
state.webglContext =
elements.canvas.getContext("webgl2", {
alpha: false,
antialias: false,
depth: true,
stencil: true,
preserveDrawingBuffer: false,
powerPreference: "high-performance",
}) || null;
}
return state.webglContext;
}
function ensureRegisteredWebGlContext() {
const moduleGl = state.module?.GL;
if (!moduleGl?.createContext || !moduleGl?.makeContextCurrent) {
return !!getWebGlContext();
}
if (!state.webglContextHandle) {
const contextHandle = moduleGl.createContext(elements.canvas, {
majorVersion: 2,
minorVersion: 0,
alpha: false,
depth: true,
stencil: true,
antialias: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
});
if (!contextHandle) {
return false;
}
state.webglContextHandle = contextHandle;
}
moduleGl.makeContextCurrent(state.webglContextHandle);
const registeredContext =
moduleGl.getContext?.(state.webglContextHandle)?.GLctx;
if (registeredContext) {
state.webglContext = registeredContext;
}
return !!getWebGlContext();
}
function destroyHardwareRenderContext() {
if (!state.hwContextDestroyPtr) {
return;
}
try {
if (state.webglContextHandle && state.module?.GL?.makeContextCurrent) {
state.module.GL.makeContextCurrent(state.webglContextHandle);
const registeredContext =
state.module.GL.getContext?.(state.webglContextHandle)?.GLctx;
if (registeredContext) {