forked from MatheoVignaud/tmc
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathxmake.lua
More file actions
1447 lines (1319 loc) · 60.4 KB
/
Copy pathxmake.lua
File metadata and controls
1447 lines (1319 loc) · 60.4 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
set_project("tmc")
-- Keep in sync with port/port_version.h.
local TMC_PC_VERSION = "0.7.1.1"
set_version(TMC_PC_VERSION)
set_xmakever("2.7.0")
-- ====================
-- Configuration
-- ====================
add_rules("mode.debug", "mode.release")
set_defaultmode("release")
-- Game version options
option("game_version")
set_default("USA")
set_showmenu(true)
set_description("Game version to build", "USA", "EU", "JP", "DEMO_USA", "DEMO_JP")
option_end()
-- Multi-region (fat) PC binary: one binary that detects the loaded ROM and
-- selects USA/EU/JP data + behavior at runtime. Compiles src/ once; the
-- REGION_IS_* macros (include/region.h) become runtime instead of compile-time.
-- game_version still controls the asset/offset baseline used for the build
-- (USA by default); only behavior sites already converted to REGION_IS_* are
-- runtime-driven. No effect on the matching GBA ROM build.
-- DEFAULT ON (M7): the shipped release has been the fat binary since v0.7.0;
-- defaulting dev builds to match removes the config drift between what
-- developers test and what users run. `--multi_region=n` (or build.py
-- --single-region) still builds the per-region binary — CI keeps it as a
-- guard against half-flattened MULTI_REGION #ifdefs.
option("multi_region")
set_default(true)
set_showmenu(true)
set_description("Build one PC binary supporting USA/EU/JP at runtime (default; =n for per-region)")
option_end()
option("pc_avx2")
set_default(true)
set_showmenu(true)
set_description("Enable AVX2 optimizations for tmc_pc when supported")
option_end()
option("pc_sanitize")
set_default(false)
set_showmenu(true)
set_description("Build tmc_pc with -fsanitize=address,undefined for runtime UB/NULL-deref detection")
option_end()
option("pc_profile")
set_default(false)
set_showmenu(true)
set_description("Build tmc_pc with -pg gprof instrumentation for hotspot profiling")
option_end()
-- GPU shader pipeline (SDL_GPU). Stage 1: scaffold only — init the
-- device, load the passthrough SPIR-V shaders, log. Doesn't yet drive
-- presentation (SDL_Renderer still owns the screen). Stage 2 onward
-- replaces port_ppu.cpp's present path with the SDL_GPU one, unlocking
-- per-pixel shader filters (CRT, scanlines, lcd-grid, etc.) without
-- the CPU-side approximation tradeoff. See port/port_gpu_renderer.{h,cpp}.
option("gpu_renderer")
-- Default ON: GPU (SDL_GPU) presentation is the primary path, with an
-- automatic SDL_Renderer software fallback (render_backend=auto tries GPU
-- first, falls back cleanly — see port_main.c / port_ppu.cpp). Compiling it
-- in everywhere means capable devices use the GPU; devices whose driver
-- can't provide a usable backend (e.g. an Adreno 405 GSI with a stub Vulkan
-- ICD) fall back to software automatically. Costs ~150 KB embedded SPIR-V.
-- Pass --gpu_renderer=n to compile a pure-software binary.
set_default(true)
set_showmenu(true)
set_description("Compile the SDL_GPU presentation path (default ON; auto-falls back to SDL_Renderer).")
option_end()
-- Widescreen: render the GBA frame at a non-native horizontal width by
-- overriding MODE1_GBA_WIDTH at compile time.
-- 240: GBA-native (3:2). No widescreen, no pillarbox, no stretch.
-- >240: ViruaPPU pillarboxes BG/OAM at col 240 (the engine's 32-tile
-- BG buffer holds reliable tile data only in cols 0..29, plus
-- parked off-screen sprites at x>=240). port_ppu.cpp uniformly
-- stretches the 240-px frame to fill the wider window. Real
-- widescreen needs a 64-tile sa2-style BGCNT_TXT512x256 engine
-- extension — Phase 2.
-- Default 240 = clean, no artifacts.
option("widescreen_width")
set_default(240)
set_showmenu(true)
set_description("MODE1_GBA_WIDTH (240=native, >240=stretched until Phase 2)")
option_end()
-- Build directories
local build_dir = "build/$(plat)"
local tools_bin = "tools/bin"
-- True when the active target arch is x86-64. ARM (arm64/aarch64) ports
-- skip x86-only codegen flags (-mavx2, -mno-ms-bitfields) and the GCC-only
-- -static-libgcc/-static-libstdc++ (aarch64 llvm-mingw uses -static alone).
-- 32-bit arches are not listed: the PC port targets 64-bit systems only
-- (enforced by a pointer-size static assert in port/port_types.h).
local function is_x86_target()
return is_arch("x64", "x86_64", "amd64")
end
-- Force GCC-style bitfield packing on MinGW (x86 only).
--
-- MinGW defaults to `-mms-bitfields` (MSVC-compatible bitfield layout),
-- which gives different sizeof() and member offsets than Linux GCC for
-- any `__attribute__((packed))` struct that contains bitfields. The TMC
-- decomp has several such structs (e.g. gUnk_08128DE8_struct_2 in the
-- pause-menu cursor data — 5+5+6 bits, packs to 2 bytes on Linux but
-- 3 bytes on MinGW), so the same C source compiles to different memory
-- layouts on the two platforms — manifests as #44 (Windows pause-map
-- cursor at wrong position, grey-blocks/bouncing). `-mno-ms-bitfields`
-- restores parity with Linux GCC across the board.
--
-- It's an x86 GCC option that doesn't apply to the AArch64 ABI (and
-- aarch64 llvm-mingw clang rejects it), so it's gated to x86 targets.
-- A Windows-ARM64 bitfield divergence would be caught by the
-- PORT_STATIC_ASSERT layout checks.
local function add_mingw_bitfield_parity()
if is_plat("windows", "mingw") and is_x86_target() then
add_cflags("-mno-ms-bitfields", {force = true})
add_cxxflags("-mno-ms-bitfields", {force = true})
end
end
-- Statically link the runtime so the Windows binary is standalone.
-- `-static` covers everything (incl. libgcc/libstdc++ or, on aarch64
-- llvm-mingw, libc++/libunwind/compiler-rt). The extra -static-libgcc/
-- -static-libstdc++ are GCC spellings kept for the established x86 build;
-- aarch64 clang doesn't need them and may reject -static-libstdc++.
local function add_mingw_static_runtime()
if is_plat("windows", "mingw") then
add_ldflags("-static", {force = true})
if is_x86_target() then
add_ldflags("-static-libgcc", {force = true})
end
add_mingw_bitfield_parity()
end
end
local function add_mingw_static_cpp_runtime()
add_mingw_static_runtime()
if is_plat("windows", "mingw") and is_x86_target() then
add_ldflags("-static-libstdc++", {force = true})
end
end
-- ====================
-- Third-party packages
-- ====================
local use_system_packages = is_host("linux") and (os.getenv("XMAKE_USE_SYSTEM_SDL3") or os.getenv("IN_NIX_SHELL"))
if use_system_packages then
add_requires("nlohmann_json", {system = true, configs = {cmake = false}})
add_requires("fmt", {configs = {header_only = true}})
add_requires("libsdl3", {system = true})
else
add_requires("nlohmann_json", {configs = {cmake = false}})
-- #15: passing system=false makes xmake ignore the host's
-- pacman::fmt / apt::libfmt-dev package (which is always shared)
-- and build fmt from source as a header-only target. Without
-- this, header_only=true was silently ignored and the binary
-- recorded a NEEDED dep on libfmt.so.12, which broke on Fedora 43
-- (ships fmt 11.x).
add_requires("fmt", {system = false, configs = {header_only = true}})
add_requires("libsdl3", {configs = {shared = false}})
end
add_requires("guilite")
-- libpng + zlib are linked by port_bugreport (F9 screenshot codec) and
-- by gbagfx (build-time PNG codec). On Linux + macOS we have system
-- packages (apt libpng-dev / brew libpng); on Windows MinGW the system
-- isn't available so xmake has to build from source. Mark the system
-- preference per platform and DON'T pass optional=true on Windows —
-- without libpng there, port_bugreport.cpp fails to compile (png.h
-- missing) and the whole release build dies.
if is_plat("mingw", "windows") then
add_requires("libpng")
add_requires("zlib")
elseif is_plat("android") then
-- NDK triplet has no system packages; build both from source (small,
-- cross-compile cleanly).
add_requires("libpng", {system = false})
add_requires("zlib", {system = false})
else
add_requires("libpng", {system = true, optional = true})
add_requires("zlib", {system = true, optional = true})
end
-- Global -mno-ms-bitfields on MinGW so the entire codebase matches the
-- Linux GCC bitfield layout. MinGW's default `-mms-bitfields` makes
-- packed-bitfield structs (e.g. pauseMenu.c's gUnk_08128DE8_struct_2 —
-- 5+5+6 packed bits) size to 3 bytes instead of 2, shifting every
-- subsequent member offset in the containing struct. Manifests as
-- issue #44 (Windows-only pause-map cursor at wrong position +
-- bouncing). Pin the GCC layout globally — every target picks it up,
-- so we don't have to remember to call a helper per target.
if is_plat("mingw", "windows") and is_x86_target() then
add_cflags("-mno-ms-bitfields", {force = true})
add_cxxflags("-mno-ms-bitfields", {force = true})
end
-- Dear ImGui for the in-game settings UI. Built against the SDL3 +
-- SDL_Renderer backends so it sits on top of the existing PPU present
-- without needing a separate GL/Vulkan context. Header-only-ish: the
-- xmake package builds a tiny static lib that wraps imgui.cpp +
-- imgui_demo.cpp + the two backend cpps.
-- Enable both SDL_Renderer and SDL_GPU ImGui backends so the F8 menu
-- works on the default build (SDL_Renderer) AND on --gpu_renderer=y
-- builds (SDL_GPU). The two backends are mutually exclusive at runtime
-- — port_imgui_menu.cpp picks via TMC_GPU_RENDERER define — but the
-- compiled package needs both files available.
add_requires("imgui v1.92.7", {configs = {sdl3 = true, sdl3_renderer = true, sdl3_gpu = true}})
-- #15: even with `header_only = true` requested above, the xmake fmt
-- package still links the system libfmt.so when one happens to be
-- installed on the build host (Arch ships fmt 12.x; Fedora 43 ships
-- 11.x, so the resulting binary ImportError'd on Fedora). Force the
-- header-only path everywhere by defining FMT_HEADER_ONLY globally;
-- fmt's headers then inline all the formatting code and the binary
-- needs no libfmt at runtime. --as-needed drops the now-unused
-- `-lfmt` xmake still passes on the link line so the binary stops
-- recording libfmt.so as a runtime dependency.
add_defines("FMT_HEADER_ONLY=1")
if is_plat("linux") then
add_ldflags("-Wl,--as-needed", {force = true})
end
-- ====================
-- Tools
-- ====================
-- agb2mid
target("agb2mid")
set_kind("binary")
set_languages("cxx17")
set_targetdir(tools_bin)
add_files("tools/src/agb2mid/*.cpp")
add_includedirs("tools/src/agb2mid")
add_mingw_static_cpp_runtime()
target_end()
-- aif2pcm
target("aif2pcm")
set_kind("binary")
set_languages("c11")
set_targetdir(tools_bin)
add_files("tools/src/aif2pcm/*.c")
add_includedirs("tools/src/aif2pcm")
add_mingw_static_runtime()
target_end()
-- asset_processor
target("asset_processor")
set_kind("binary")
set_languages("cxx17")
set_targetdir(tools_bin)
add_files("tools/src/asset_processor/*.cpp")
add_files("tools/src/asset_processor/assets/*.cpp")
add_includedirs("tools/src/asset_processor")
add_includedirs("tools/src/util")
add_packages("nlohmann_json")
add_mingw_static_cpp_runtime()
target_end()
-- asset_extractor
target("asset_extractor")
set_kind("binary")
set_languages("cxx20")
set_targetdir("build/pc")
add_defines("PC_PORT", "NON_MATCHING", "USA", "ENGLISH", "REVISION=0")
add_files("tools/src/assets_extractor/*.cpp")
remove_files("tools/src/assets_extractor/asset_extractor_runner.cpp")
add_files("port/port_asset_pipeline.cpp")
add_files("port/port_asset_log.cpp")
add_files("port/port_asset_pak.cpp")
add_files("port/port_asset_index.c")
add_includedirs("tools/src/assets_extractor")
add_includedirs("include", "port", ".")
add_packages("nlohmann_json", "fmt")
add_mingw_static_cpp_runtime()
-- Embed assets/sounds.json into the binary so the extractor can guarantee
-- it appears next to itself even when a release tarball forgets to ship
-- the file (the v0.1.6 packaging bug behind issue #50). xmake's bin2c
-- rule writes a raw "0xNN, 0xNN, ..." byte sequence to a header that we
-- #include inside a C array initializer (see embedded_sounds_json.cpp).
add_rules("utils.bin2c", {extensions = {".json"}})
add_files("assets/sounds.json", {rule = "utils.bin2c", nozeroend = true})
after_build(function (target)
local mirrored_exe = path.join(tools_bin, path.filename(target:targetfile()))
if mirrored_exe ~= target:targetfile() then
os.cp(target:targetfile(), mirrored_exe)
end
end)
target_end()
-- bin2c
target("bin2c")
set_kind("binary")
set_languages("c11")
set_targetdir(tools_bin)
add_files("tools/src/bin2c/*.c")
add_includedirs("tools/src/bin2c")
add_mingw_static_runtime()
target_end()
-- gbafix
target("gbafix")
set_kind("binary")
set_languages("c11")
set_targetdir(tools_bin)
add_files("tools/src/gbafix/*.c")
add_includedirs("tools/src/gbafix")
add_mingw_static_runtime()
target_end()
-- gbagfx
target("gbagfx")
set_kind("binary")
set_languages("c11")
set_targetdir(tools_bin)
add_files("tools/src/gbagfx/*.c")
add_includedirs("tools/src/gbagfx")
add_packages("libpng", "zlib")
add_mingw_static_runtime()
target_end()
-- mid2agb
target("mid2agb")
set_kind("binary")
set_languages("cxx17")
set_targetdir(tools_bin)
add_files("tools/src/mid2agb/*.cpp")
add_includedirs("tools/src/mid2agb")
add_mingw_static_cpp_runtime()
target_end()
-- preproc
target("preproc")
set_kind("binary")
set_languages("cxx17")
set_targetdir(tools_bin)
add_files("tools/src/preproc/*.cpp")
add_includedirs("tools/src/preproc")
add_mingw_static_cpp_runtime()
target_end()
-- scaninc
target("scaninc")
set_kind("binary")
set_languages("cxx17")
set_targetdir(tools_bin)
add_files("tools/src/scaninc/*.cpp")
add_includedirs("tools/src/scaninc")
add_packages("fmt")
add_mingw_static_cpp_runtime()
target_end()
-- tmc_strings
target("tmc_strings")
set_kind("binary")
set_languages("cxx17")
set_targetdir(tools_bin)
add_files("tools/src/tmc_strings/*.cpp")
add_includedirs("tools/src/tmc_strings")
add_packages("nlohmann_json", "fmt")
add_mingw_static_cpp_runtime()
target_end()
-- Group all tools
target("tools")
set_kind("phony")
add_deps("agb2mid", "aif2pcm", "asset_processor", "bin2c", "gbafix", "gbagfx", "mid2agb", "preproc", "scaninc", "tmc_strings")
target_end()
-- ====================
-- Asset Tasks
-- ====================
-- Extract assets task
task("extract_assets")
set_category("plugin")
on_run(function ()
import("core.project.config")
config.load()
local game_version = get_config("game_version") or "USA"
local build_assets_dir = "build/" .. game_version .. "/assets"
print("===========================================")
print("Extracting assets for " .. game_version)
print("===========================================")
-- Build tools first
print("[1/3] Building tools...")
os.exec("xmake build tools")
print("[1/3] Tools built successfully!")
-- Create build directory
print("[2/3] Creating build directory: " .. build_assets_dir)
os.mkdir(build_assets_dir)
-- Run asset_processor extract
print("[3/3] Running asset_processor extract (verbose mode)...")
print("-------------------------------------------")
os.execv("tools/bin/asset_processor", {"-v", "extract", game_version, build_assets_dir})
print("-------------------------------------------")
print("===========================================")
print("Assets extracted to " .. build_assets_dir)
print("===========================================")
end)
set_menu {
usage = "xmake extract_assets [options]",
description = "Extract assets from baserom",
options = {}
}
task_end()
-- Convert assets task
task("convert_assets")
set_category("plugin")
on_run(function ()
import("core.project.config")
config.load()
local game_version = get_config("game_version") or "USA"
local build_assets_dir = "build/" .. game_version .. "/assets"
print("===========================================")
print("Converting assets for " .. game_version)
print("===========================================")
-- Build tools first
print("[1/3] Building tools...")
os.exec("xmake build tools")
print("[1/3] Tools built successfully!")
-- Create build directory
print("[2/3] Checking build directory: " .. build_assets_dir)
os.mkdir(build_assets_dir)
-- Run asset_processor convert
print("[3/3] Running asset_processor convert (verbose mode)...")
print("-------------------------------------------")
os.execv("tools/bin/asset_processor", {"-v", "convert", game_version, build_assets_dir})
print("-------------------------------------------")
print("===========================================")
print("Assets converted to " .. build_assets_dir)
print("===========================================")
end)
set_menu {
usage = "xmake convert_assets [options]",
description = "Convert extracted assets",
options = {}
}
task_end()
-- Build assets task
task("build_assets")
set_category("plugin")
on_run(function ()
import("core.project.config")
config.load()
local game_version = get_config("game_version") or "USA"
local build_assets_dir = "build/" .. game_version .. "/assets"
-- Build tools first
os.exec("xmake build tools")
-- Create build directory
os.mkdir(build_assets_dir)
-- Run asset_processor build
os.execv("tools/bin/asset_processor", {"build", game_version, build_assets_dir})
print("Assets built to " .. build_assets_dir)
end)
set_menu {
usage = "xmake build_assets [options]",
description = "Build assets from source",
options = {}
}
task_end()
-- ====================
-- PC Port Target
-- ====================
target("tmc_pc")
if is_plat("android") then
-- Android: SDL's Java glue (SDLActivity) loads the game as a JNI
-- shared library named libmain.so and calls its SDL_main. Own
-- targetdir per ABI so android/gradle can consume them as jniLibs
-- and desktop build/pc is never clobbered.
set_kind("shared")
set_basename("main")
set_targetdir("build/android/" .. (get_config("arch") or "arm64-v8a"))
-- Android 15+ requires 16 KB page-aligned segments (same flag the
-- SameBoy Android port ships).
add_shflags("-Wl,-z,max-page-size=16384", {force = true})
else
set_kind("binary")
set_targetdir("build/pc")
end
set_languages("c11", "cxx20")
local use_avx2 = get_config("pc_avx2")
if use_avx2 == nil then
use_avx2 = true
end
local target_arch = get_config("arch") or ""
local arch_supports_avx2 = is_arch("x64", "x86_64", "amd64")
if not arch_supports_avx2 and target_arch ~= "" then
local arch_l = target_arch:lower()
arch_supports_avx2 = (arch_l == "x64" or arch_l == "x86_64" or arch_l == "amd64")
end
-- The software GBA PPU is now vendored first-party under port/ppu/ (see
-- port/ppu/README.md); there is no longer a ViruaPPU submodule to patch at
-- build time. This before_build only regenerates the embedded sounds blob
-- and logs the AVX2 decision.
before_build(function (target)
-- Regenerate port/generated_sounds_embed.cpp from
-- assets/sounds.json so the binary always carries an
-- up-to-date fallback. The Python helper no-ops when the
-- output is already byte-identical, so xmake's incremental
-- cache stays warm. Missing input -> empty fallback (the
-- audio backend logs "songs will be silent" in that case).
do
local script = path.join(os.projectdir(), "tools", "generate_sounds_embed.py")
local input = path.join(os.projectdir(), "assets", "sounds.json")
local output = path.join(os.projectdir(), "port", "generated_sounds_embed.cpp")
if os.isfile(script) then
local ok = try {
function ()
os.execv("python3", {script, input, output})
return true
end
}
if not ok then
-- Fall back to `python` (Windows installs without
-- the python3 shim).
try {
function ()
os.execv("python", {script, input, output})
return true
end
}
end
end
end
print("[tmc_pc] arch=%s pc_avx2=%s", target_arch ~= "" and target_arch or "auto", use_avx2 and "on" or "off")
if use_avx2 and arch_supports_avx2 then
print("[tmc_pc] AVX2: enabled")
elseif not use_avx2 then
print("[tmc_pc] AVX2: disabled (pc_avx2 option is off)")
else
print("[tmc_pc] AVX2: disabled (unsupported target arch)")
end
end)
-- PC port version configurations
local pc_versions = {
USA = { region = "USA", language = "ENGLISH" },
EU = { region = "EU", language = "ENGLISH" },
-- JP is wired but ROM-gated: building it needs a JP baserom (BZMJ),
-- extracted JP assets in build/JP/, and the generated port_offset_JP.h.
-- region/language become the JP + JAPANESE defines the decomp's
-- #ifdef JP paths expect. See docs/JP_PORT_ENABLEMENT.md.
JP = { region = "JP", language = "JAPANESE" },
}
local pc_game_version = get_config("game_version") or "USA"
local pc_ver = pc_versions[pc_game_version] or pc_versions["USA"]
if pc_versions[pc_game_version] == nil then
print("WARNING: PC port has no config for game_version='" .. pc_game_version
.. "'; falling back to USA. (JP is ROM-gated — see docs/JP_PORT_ENABLEMENT.md.)")
end
add_defines("PC_PORT", "NON_MATCHING", "USE_HDMA", pc_ver.region, pc_ver.language, "REVISION=0")
-- Inject the version string from the top-of-file constant so the
add_defines('TMC_PC_VERSION="' .. TMC_PC_VERSION .. '"')
add_defines('TMC_PORT_VERSION="' .. TMC_PC_VERSION .. '"')
-- Multi-region fat binary: switch REGION_IS_* (include/region.h) to runtime.
-- Force-include region.h everywhere so converted gameplay-behavior sites and
-- the matching ROM build see the same macros. region.h is pure macros in the
-- non-multi-region path, so this is inert for normal single-region builds.
add_forceincludes("region.h")
if get_config("multi_region") then
add_defines("MULTI_REGION")
print("PC port: MULTI_REGION build — one binary for USA/EU/JP at runtime "
.. "(asset/offset baseline: " .. pc_game_version .. ").")
end
-- Widescreen: single source of truth for the rendered viewport width.
-- The orphaned `widescreen_width` option is injected here as
-- MODE1_GBA_WIDTH so BOTH the ViruaPPU renderer (compiled into this
-- target via add_files) and the port's engine-side cull tests
-- (CheckOnScreen / CheckRectOnScreen, via port/port_widescreen.h) key
-- off one value and can never disagree. 240 = GBA-native; the cull
-- bounds collapse to their original literals at 240.
local ws_width = get_config("widescreen_width") or 240
add_defines("MODE1_GBA_WIDTH=" .. ws_width)
-- Discord Rich Presence application ID — optional, gitignored.
-- Local devs/release builders drop their Discord App ID into
-- discord_app_id.txt at repo root and it gets baked in as the
-- compile-time fallback used when TMC_DISCORD_APP_ID env var is
-- unset. The file is in .gitignore so the public repo never
-- contains it (see port/port_discord_rpc.c security-model note).
--
-- File-reading APIs only exist in script-scope (on_load), so we
-- inject the macro from there rather than the surrounding
-- description scope.
on_load(function (target)
if os.isfile("discord_app_id.txt") then
local app_id = io.readfile("discord_app_id.txt")
if app_id then
app_id = app_id:gsub("%s+", "")
if app_id ~= "" then
target:add("defines",
'TMC_DISCORD_APP_ID_DEFAULT="' .. app_id .. '"')
end
end
end
end)
if use_avx2 and arch_supports_avx2 then
add_defines("USE_AVX2")
add_cflags("-mavx2", "-mfma", {tools = {"gcc", "clang"}})
add_cxxflags("-mavx2", "-mfma", {tools = {"gcc", "clang"}})
add_cflags("/arch:AVX2", {tools = {"cl"}})
add_cxxflags("/arch:AVX2", {tools = {"cl"}})
end
-- Include directories
add_includedirs("include", "libs")
add_includedirs("port")
add_includedirs(".")
add_includedirs("build/" .. pc_game_version) -- For assets/map_offsets.h etc (USA, EU, or JP)
add_includedirs("port/ppu/include") -- vendored software GBA PPU
add_includedirs("libs/VirtuaAPU/include")
add_includedirs("libs/agbplay_core")
add_includedirs("tools/src/assets_extractor") -- AssetExtractorApi linked in-process
-- tmc-Modern-Launcher is a private matheo repo; gate on submodule
-- presence so checkouts without access still build. Detect by
-- looking for the launcher's public header (the submodule pointer
-- exists in .gitmodules but the working tree is empty when the
-- clone fails).
if os.isfile("libs/tmc-Modern-Launcher/include/tmc_launcher.h") then
add_defines("launcher", "GUILITE_ON", "TMC_HAS_MODERN_LAUNCHER=1")
add_includedirs("libs/tmc-Modern-Launcher/include")
add_includedirs("libs/tmc-Modern-Launcher/3p")
add_rules("utils.bin2c", {extensions = {".png"}})
add_files("libs/tmc-Modern-Launcher/assets/github.png", {rule = "utils.bin2c", nozeroend = true})
add_files("libs/tmc-Modern-Launcher/src/launcher_github_icon.cpp")
add_files("libs/tmc-Modern-Launcher/src/tmc_launcher.cpp")
add_files("port/port_launcher_bootstrap.cpp")
end
add_files("port/port_main.c")
add_files("port/port_android_log.c") -- stderr->logcat bridge (no-op off Android)
add_files("port/port_audio.c")
add_files("port/port_shm_framebuffer.c") -- publishes GBA framebuffer to shm (opt-in)
add_files("port/port_runtime_config.cpp")
add_files("port/port_debug_menu.cpp")
add_files("port/port_imgui_menu.cpp")
add_files("port/port_prelaunch_logo.cpp")
add_files("port/port_tts.cpp")
add_files("port/port_a11y_cues.c") -- accessibility audio cues (surroundings scan, F10)
add_files("port/port_a11y_audio.c") -- spatialized tone cues (audio-thread mixer)
-- Embed docs/picori-logo.png into the binary so the prelaunch
-- screen always has the logo regardless of cwd / install layout.
-- xmake's utils.bin2c rule writes a "0xNN, 0xNN, ..." byte sequence
-- to a header we include inside an array initializer
-- (see port_prelaunch_logo.cpp).
add_rules("utils.bin2c", {extensions = {".png"}})
add_files("docs/picori-logo.png", {rule = "utils.bin2c", nozeroend = true})
add_files("port/port_debug_actions.c")
add_files("port/port_debug_entities.c")
add_files("port/port_debug_memory_watch.c") -- live GBA memory-watch list (F8 Memory tab)
add_files("port/port_quicksave.c")
add_files("port/port_practice.c") -- Speedrun practice mode (timer/inputs/reload/slow-mo)
add_files("port/port_inline_ptrs.c")
add_files("port/port_script_addrs.c") -- per-region GBA_script_* address translation (M3)
add_files("port/port_offset_remap.c") -- per-region compiled blob-offset remap (M7, generated)
add_files("port/port_asset_bootstrap.cpp")
add_files("port/port_asset_index.c")
add_files("port/port_update_check.c")
add_files("port/port_asset_loader.cpp")
add_files("port/port_asset_pipeline.cpp")
add_files("port/port_asset_log.cpp")
add_files("port/port_asset_pak.cpp")
add_files("port/port_asset_pak_loader.cpp")
add_files("port/port_exe_path.cpp") -- shared executable-directory query (C++)
add_files("port/port_debug_verbose.c") -- per-frame log gate, env-controlled
add_files("port/port_rom_picker.c") -- SDL3 file picker when no ROM is found
-- In-process randomizer (port/rando/), derived from the GPL-3.0 Minish Cap
-- randomizer (minishmaker/randomizer); GPL-3.0, see THIRD-PARTY-LICENSES.md.
add_files("port/rando/rando.cpp")
add_files("port/rando/rando_logic.cpp")
add_files("port/rando/rando_file_menu.c")
add_files("port/rando/rando_save.c")
add_files("port/rando/rando_runtime.c") -- eventdefine-driven runtime features (C: needs player.h/save.h layouts)
add_files("port/rando/rando_newfile.c") -- new-file randomizer baseline flag/figurine tables
add_files("port/rando/rando_entrance.cpp") -- coupled dungeon-entrance shuffle
add_files("port/rando/rando_cosmetic.cpp") -- tunic / heart color eventdefines
add_files("port/rando/rando_music.c") -- MUSIC_RANDO area-BGM remap
add_files("port/rando/rando_keymap.c") -- curated ground-item location keys (area-room-flag)
-- Minish Cap Reborn parity toggles, ported from Admentus64/The-Minish-Cap-
-- Reborn (GPL-3.0); GPL-3.0, see THIRD-PARTY-LICENSES.md.
add_files("port/port_reborn.cpp")
-- Env-gated auto-repro / capture harnesses (no-op when off).
add_files("port/port_repro_perfcap.c")
add_files("port/port_repro_rando.c")
add_files("port/port_repro_a11y.c")
add_files("port/port_repro_roomcap.c") -- generic in-game room capture (TMC_ROOMCAP)
add_files("port/port_repro_roll_macro.c") -- roll-attack macro e2e test (TMC_REPRO_ROLL_MACRO)
add_files("port/port_repro_npc_talk.c") -- NPC-talk e2e test (TMC_REPRO_NPC_TALK)
add_files("port/port_repro_itemget.c") -- item-get perf repro (TMC_REPRO_ITEMGET)
-- Link the asset extractor implementation directly so tmc_pc can
-- run extraction in-process at startup (no shell-out) and share
-- the engine's already-loaded ROM buffer.
add_files("tools/src/assets_extractor/assets_extractor_api.cpp")
add_files("port/port_m4a_backend.cpp")
add_files("port/generated_sounds_embed.cpp") -- compile-time sounds.json fallback
add_files("port/port_ppu.cpp") -- PPU bridge (C++ → ViruaPPU)
add_files("port/port_gpu_renderer.cpp") -- SDL_GPU presentation (Stage 1: scaffold; gated on --gpu_renderer=y)
add_files("port/port_glslp_parser.cpp") -- libretro .glslp parser — steps 1-4 of the runtime scaffold (Stage 5+C)
add_files("port/port_glslp_runtime.cpp") -- libretro .glslp runtime — step 5 (load + shader-build; present pending)
-- SDL_GPU shader blobs. Compiled offline via port/shaders/build.sh
-- (run when *.vert / *.frag change); the .spv files are committed
-- so the build doesn't depend on glslangValidator on every host.
-- Only embedded when the gpu_renderer option is enabled — keeps
-- the default build identical in size for users who don't opt in.
if has_config("gpu_renderer") then
add_defines("TMC_GPU_RENDERER=1")
-- The extensions filter on the rule auto-matches add_files
-- entries with .spv suffix — re-specifying `rule = "utils.bin2c"`
-- on the add_files line was registering them twice and
-- triggered xmake's "job has already been added" warning.
add_rules("utils.bin2c", {extensions = {".spv"}, nozeroend = true})
add_files("port/shaders/build/passthrough.vert.spv")
add_files("port/shaders/build/passthrough.frag.spv")
add_files("port/shaders/build/lcd_grid.frag.spv")
add_files("port/shaders/build/scanline.frag.spv")
add_files("port/shaders/build/handheld.frag.spv")
add_files("port/shaders/build/vignette.frag.spv")
add_files("port/shaders/build/crt_composite.frag.spv")
add_files("port/shaders/build/crt_rf.frag.spv")
add_files("port/shaders/build/blur5h.frag.spv")
add_files("port/shaders/build/crt_rf_p2.frag.spv")
end
add_files("port/port_icon.cpp") -- SDL window icon (placeholder, ROM-extracted in future)
add_files("port/port_mods.cpp") -- Tier 1 mod loader: asset overrides from <exe>/mods/
add_files("port/port_rom.c") -- ROM loading & symbol resolution
-- PC port stubs for undefined symbols
add_files("port/port_stubs.c")
add_files("port/stubs_autogen.c")
add_files("port/data_stubs_autogen.c")
add_files("port/data_const_stubs.c") -- Const ROM data (generated by tools/generate_const_data.py)
add_files("port/flag_remap_generated.c") -- Per-region flag-ordinal remap (generated by tools/generate_flag_remap.py)
add_files("port/port_rom_tables.c") -- Compile-time ROM offset tables (generated by tools/generate_rom_tables.py)
add_files("port/port_bios.c")
add_files("port/port_bugreport.cpp") -- F9 bug-report capture (screenshot + save + state dump)
add_files("port/port_bugreport_state.c") -- Crash-handler state snapshot
add_files("port/port_linked_stubs.c")
add_files("port/port_figurines.c") -- gFigurines[] resolved from ROM (#57)
add_files("port/port_draw.c")
add_files("port/port_gba_mem.c")
add_files("port/port_hdma.c") -- HBlank-DMA simulation (iris/circle WIN0H)
add_files("port/port_upscale.c") -- xBRZ-style pixel-art upscaler
add_files("port/port_save.c") -- EEPROM save emulation
add_files("port/port_softslots.c") -- Extra item-equip buttons (X/Y/L2/R2)
add_files("port/port_roll_attack_macro.c") -- One-button roll attack (default: D)
add_files("port/port_touch_controls.cpp")
add_files("port/port_filter.c") -- CRT/LCD post-process filters
add_files("port/port_animation.c") -- Animation system (ported from ASM)
add_files("port/port_math.c") -- Math functions (CalcDistance, direction, Sqrt, Div)
add_files("port/port_text_render.c") -- Text rendering (UnpackTextNibbles, glyph pixel writers)
add_files("port/port_gameplay_stubs.c") -- Ported gameplay helpers from ASM (tile interaction, ice movement, SFX queue)
add_files("port/port_m4a_stubs.c") -- Ported m4a API stubs with typed behavior for PC
add_files("port/port_room_funcs.c") -- Room function pointer lookup table (generated)
add_files("port/port_script_funcs.c") -- Script Call/CallWithArg function lookup (generated)
add_files("port/port_analog_movement.c") -- 360° left-stick movement bridge (REBORN_FEAT_ANALOG_360_MOVEMENT)
add_files("port/port_audio_mute.cpp") -- per-category SFX mute toggles (F8 → Audio)
add_files("port/port_discord_rpc.c") -- Discord Rich Presence (Unix IPC, F8 → Display toggle)
add_files("port/ppu/src/*.c") -- vendored software GBA PPU (was libs/ViruaPPU)
add_files("libs/VirtuaAPU/src/*.c")
add_files("libs/agbplay_core/*.cpp")
-- Game source files - Main game code
add_files("src/main.c")
add_files("src/common.c")
add_files("src/interrupts.c")
add_files("src/game.c")
add_files("src/title.c")
add_files("src/fileselect.c")
add_files("src/flags.c")
add_files("src/save.c")
add_files("src/fade.c")
add_files("src/color.c")
add_files("src/vram.c")
add_files("src/screen*.c")
add_files("src/message.c")
add_files("src/text.c")
add_files("src/sound.c")
add_files("src/script.c")
add_files("src/scroll.c")
add_files("src/room.c")
add_files("src/roomInit.c")
add_files("src/entity.c")
add_files("src/physics.c")
add_files("src/collision.c")
add_files("src/movement.c")
add_files("src/affine.c")
add_files("src/sineTable.c")
add_files("src/ui.c")
-- Player
add_files("src/player.c")
add_files("src/playerUtils.c")
add_files("src/playerHitbox.c")
add_files("src/playerItem.c")
add_files("src/playerItemUtils.c")
add_files("src/playerItemDefinitions.c")
add_files("src/playerItem/*.c")
-- Entities
add_files("src/enemy.c")
add_files("src/enemyUtils.c")
add_files("src/enemy/*.c")
add_files("src/npc.c")
add_files("src/npcUtils.c")
add_files("src/npcFunctions.c")
add_files("src/npcDefinitions.c")
add_files("src/npc/*.c")
add_files("src/object.c")
add_files("src/objectUtils.c")
add_files("src/objectDefinitions.c")
add_files("src/object/*.c")
add_files("src/enemyUpdate.c")
add_files("src/projectile.c")
add_files("src/projectileUtils.c")
add_files("src/projectileUpdate.c")
add_files("src/projectile/*.c")
add_files("src/manager.c")
add_files("src/manager/*.c")
add_files("src/item.c")
add_files("src/itemUtils.c")
add_files("src/itemDefinitions.c")
add_files("src/itemMetaData.c")
add_files("src/item/*.c")
-- Other game systems
add_files("src/subtask.c")
add_files("src/subtask/*.c")
add_files("src/cutscene.c") -- re-enabled for PC port
add_files("src/backgroundAnimations.c")
add_files("src/beanstalkSubtask.c")
add_files("src/enterPortalSubtask.c")
add_files("src/gameOverTask.c")
add_files("src/gameUtils.c")
add_files("src/gameData.c")
add_files("src/kinstone.c")
add_files("src/droptables.c")
add_files("src/demo.c")
add_files("src/debug.c")
add_files("src/flagDebug.c")
add_files("src/staffroll.c")
add_files("src/menu/*.c")
add_files("src/data/figurineMenuData.c")
add_files("src/data/hitbox.c")
add_files("src/data/areaMetadata.c")
add_files("src/data/caveBorderMapData.c")
add_files("src/data/data_080046A4.c")
add_files("src/data/mapActTileToSurfaceType.c")
add_files("src/data/objPalettes.c")
add_files("src/data/screenTransitions.c")
add_files("src/data/transitions.c")
add_files("src/worldEvent/*.c")
-- Code stubs (functions that need decompilation)
add_files("src/code_08049CD4.c")
add_files("src/code_08049DF4.c")
add_files("src/code_0805EC04.c")
-- GBA library (m4a sound) - skipped for PC, using stubs
-- libpng + zlib are needed by port_bugreport.cpp for F9 screenshot
-- PNG encoding. imgui drives the F8/ribbon menus (HEAD).
-- guilite is matheo's mobile/touch UI overlay.
-- Keep all of them so both UI stacks build cleanly.
add_packages("libsdl3", "nlohmann_json", "fmt", "libpng", "zlib", "imgui", "guilite")
-- Build a standalone Windows binary with MinGW (static SDL + runtimes).
-- x86 uses the GCC -static-libgcc/-static-libstdc++ spellings; aarch64
-- llvm-mingw gets -static alone (statically links libc++/libunwind/
-- compiler-rt/winpthreads), since clang may reject -static-libstdc++.
if is_plat("windows", "mingw") then
add_ldflags("-static", {force = true})
if is_x86_target() then
add_ldflags("-static-libgcc", "-static-libstdc++", {force = true})
end
-- dbghelp: SymInitialize / SymFromAddr used by port_bugreport.cpp's
-- WriteBacktraceWindows() for symbol resolution in the crash handler.
add_syslinks("winhttp", "winpthread", "dbghelp")
end
-- Math library
if is_plat("linux", "macosx") then
add_links("m")
end
-- Compiler flags
add_cflags("-Wall", "-Wextra", "-Wno-unused-parameter", "-Wno-missing-field-initializers",
"-fno-strict-aliasing", "-fwrapv", "-fno-strict-overflow", "-O3", "-g",
"-fvisibility=default", "-funsigned-char")
add_cxxflags("-Wall", "-Wextra", "-Wno-unused-parameter",
"-fno-strict-aliasing", "-fwrapv", "-fno-strict-overflow", "-O3", "-g", "-funsigned-char")
add_cflags("/J", {tools = {"cl"}})
add_cxxflags("/J", {tools = {"cl"}})
-- OpenMP scanline parallelism for the vendored PPU mode1.
--
-- port/ppu/src/mode1.c contains `#pragma omp parallel for
-- schedule(static)` over the 160-row render loop. The .c files are
-- pulled into this target directly via add_files(), so -fopenmp must
-- be wired explicitly here or the pragmas compile as silent no-ops.
-- Wire -fopenmp explicitly so
-- the render actually runs on every core. The HDMA pre-line
-- callback still runs serially (with per-line IO snapshot) so
-- water-FX / BLDY fades stay correct; only the BG+OBJ+composite
-- inner pass parallelises.
--
-- Platform notes:
-- - Linux: gcc/clang both accept -fopenmp directly.
-- - MinGW (Windows x86 cross): libgomp ships with the toolchain and
-- is linked statically via the existing -static-libgcc.
-- - macOS: Apple Clang doesn't accept bare -fopenmp (would need
-- `brew install libomp` + `-Xpreprocessor -fopenmp -lomp`).
-- The mode1 #pragma simply degrades to a serial loop on macOS
-- when the flag isn't set — render is slower but visually
-- identical. v0.3.0-experimental release CI hit this; skip the
-- flag on macOS so the build succeeds.
-- - Windows ARM64 (llvm-mingw): ships libomp (not libgomp); static
-- linking of it under -static is unverified, so degrade to the
-- same serial mode1 path as macOS to guarantee the build links.
-- Re-enable once a CI run confirms libomp links cleanly.
local openmp_ok = not is_plat("macosx")
if is_plat("windows", "mingw") and not is_x86_target() then
openmp_ok = false
end
if openmp_ok then
add_cflags("-fopenmp")
add_cxxflags("-fopenmp")
add_ldflags("-fopenmp", {force = true})
if is_plat("android") then
-- Shared-lib link (libmain.so) uses shflags, and the NDK's
-- libomp must be linked STATICALLY (-static-openmp) — devices
-- don't ship a system libomp.so.
add_shflags("-fopenmp", "-static-openmp", {force = true})
add_ldflags("-static-openmp", {force = true})
end
end
-- Optional sanitizer build (xmake f -y --pc_sanitize=y). Catches NULL
-- deref, OOB reads/writes, signed-overflow UB, use-after-free with a
-- precise stack trace at the moment of the violation.
if has_config("pc_sanitize") then
add_cflags ("-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-fno-sanitize-recover=all")
add_cxxflags("-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-fno-sanitize-recover=all")
add_ldflags ("-fsanitize=address,undefined", {force = true})
add_shflags ("-fsanitize=address,undefined", {force = true})
print("[tmc_pc] sanitizer: AddressSanitizer + UndefinedBehaviorSanitizer enabled")
end
-- Optional gprof profiling build (xmake f -y --pc_profile=y). Adds -pg
-- instrumentation so a headless repro run drops gmon.out for
-- `gprof ./tmc_pc gmon.out`. Run with OMP_NUM_THREADS=1 so the parallel
-- scanline render attributes to the profiled main thread. Off by default.
if has_config("pc_profile") then
add_cflags ("-pg", "-fno-omit-frame-pointer")
add_cxxflags("-pg", "-fno-omit-frame-pointer")
add_ldflags ("-pg", {force = true})
print("[tmc_pc] gprof profiling: -pg enabled (run with OMP_NUM_THREADS=1; gmon.out -> gprof)")
end
-- Keep symbols even in release mode so SIGSEGV traces are useful
-- locally (CI release tarballs may strip later). The xmake mode.release
-- rule adds -s/--strip-all by default which makes addr2line useless.
set_strip("none")
target_end()