-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbuild.zig
1279 lines (1194 loc) · 46.2 KB
/
build.zig
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
//! based on sokol-zig
const std = @import("std");
const builtin = @import("builtin");
const Build = std.Build;
const CompileStep = Build.Step.Compile;
const RunStep = Build.Step.Run;
pub const SokolBackend = enum {
auto, // Windows: D3D11, macOS/iOS: Metal, otherwise: GL
d3d11,
metal,
gl,
gles3,
wgpu,
};
pub const LibSokolOptions = struct {
target: Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
backend: SokolBackend = .auto,
use_egl: bool = false,
use_x11: bool = true,
use_wayland: bool = false,
emsdk: ?*Build.Dependency = null,
use_ubsan: bool = false,
use_tsan: bool = false,
with_sokol_imgui: bool = false,
imgui_version: ?[]const u8 = null,
sokol_imgui_cprefix: ?[]const u8 = null,
cimgui_header_path: ?[]const u8 = null,
};
// helper function to resolve .auto backend based on target platform
fn resolveSokolBackend(backend: SokolBackend, target: std.Target) SokolBackend {
if (backend != .auto) {
return backend;
} else if (target.isDarwin()) {
return .metal;
} else if (target.os.tag == .windows) {
return .d3d11;
} else if (target.isWasm()) {
return .gles3;
} else if (target.isAndroid()) {
return .gles3;
} else {
return .gl;
}
}
fn rootPath() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
// build sokol into a static library
pub fn buildLibSokol(b: *Build, options: LibSokolOptions) !*CompileStep {
const sharedlib = b.option(bool, "shared", "Build sokol dynamic library (default: static)") orelse false;
const lib = if (sharedlib) b.addSharedLibrary(.{
.name = "sokol",
.target = options.target,
.optimize = options.optimize,
.link_libc = true,
}) else b.addStaticLibrary(.{
.name = "sokol",
.target = options.target,
.optimize = options.optimize,
.link_libc = true,
});
lib.root_module.sanitize_c = options.use_ubsan;
lib.root_module.sanitize_thread = options.use_tsan;
switch (options.optimize) {
.Debug, .ReleaseSafe => lib.bundle_compiler_rt = true,
else => lib.root_module.strip = true,
}
if (options.target.result.isWasm()) {
lib.root_module.root_source_file = b.path("src/handmade/math.zig");
if (options.optimize != .Debug)
lib.want_lto = true;
// make sure we're building for the wasm32-emscripten target, not wasm32-freestanding
if (lib.rootModuleTarget().os.tag != .emscripten) {
std.log.err("Please build with 'zig build -Dtarget=wasm32-emscripten", .{});
return error.Wasm32EmscriptenExpected;
}
// one-time setup of Emscripten SDK
if (options.emsdk) |emsdk| {
if (try emSdkSetupStep(b, emsdk)) |emsdk_setup| {
lib.step.dependOn(&emsdk_setup.step);
}
// add the Emscripten system include seach path
lib.addSystemIncludePath(emSdkLazyPath(b, emsdk, &.{ "upstream", "emscripten", "cache", "sysroot", "include" }));
}
}
// resolve .auto backend into specific backend by platform
var cflags = try std.BoundedArray([]const u8, 64).init(0);
try cflags.append("-DIMPL");
if (options.optimize != .Debug) {
try cflags.append("-DNDEBUG");
}
const backend = resolveSokolBackend(options.backend, lib.rootModuleTarget());
switch (backend) {
.d3d11 => try cflags.append("-DSOKOL_D3D11"),
.metal => try cflags.append("-DSOKOL_METAL"),
.gl => try cflags.append("-DSOKOL_GLCORE"),
.gles3 => try cflags.append("-DSOKOL_GLES3"),
.wgpu => try cflags.append("-DSOKOL_WGPU"),
else => @panic("unknown sokol backend"),
}
// platform specific compile and link options
if (lib.rootModuleTarget().isDarwin()) {
try cflags.append("-ObjC");
lib.linkFramework("Foundation");
lib.linkFramework("AudioToolbox");
if (.metal == backend) {
lib.linkFramework("MetalKit");
lib.linkFramework("Metal");
}
if (lib.rootModuleTarget().os.tag == .ios) {
lib.linkFramework("UIKit");
lib.linkFramework("AVFoundation");
if (.gl == backend) {
lib.linkFramework("OpenGLES");
lib.linkFramework("GLKit");
}
} else if (lib.rootModuleTarget().os.tag == .macos) {
lib.linkFramework("Cocoa");
lib.linkFramework("QuartzCore");
if (.gl == backend) {
lib.linkFramework("OpenGL");
}
}
} else if (lib.rootModuleTarget().isAndroid()) {
if (.gles3 != backend) {
@panic("For android targets, you must have backend set to GLES3");
}
lib.linkSystemLibrary("GLESv3");
lib.linkSystemLibrary("EGL");
lib.linkSystemLibrary("android");
lib.linkSystemLibrary("log");
} else if (lib.rootModuleTarget().os.tag == .linux) {
if (options.use_egl) try cflags.append("-DSOKOL_FORCE_EGL");
if (!options.use_x11) try cflags.append("-DSOKOL_DISABLE_X11");
if (!options.use_wayland) try cflags.append("-DSOKOL_DISABLE_WAYLAND");
const link_egl = options.use_egl or options.use_wayland;
lib.linkSystemLibrary("asound");
lib.linkSystemLibrary("GL");
if (options.use_x11) {
lib.linkSystemLibrary("X11");
lib.linkSystemLibrary("Xi");
lib.linkSystemLibrary("Xcursor");
}
if (options.use_wayland) {
lib.linkSystemLibrary("wayland-client");
lib.linkSystemLibrary("wayland-cursor");
lib.linkSystemLibrary("wayland-egl");
lib.linkSystemLibrary("xkbcommon");
}
if (link_egl) {
lib.linkSystemLibrary("EGL");
}
} else if (lib.rootModuleTarget().os.tag == .windows) {
lib.linkSystemLibrary("kernel32");
lib.linkSystemLibrary("user32");
lib.linkSystemLibrary("gdi32");
lib.linkSystemLibrary("ole32");
if (.d3d11 == backend) {
lib.linkSystemLibrary("d3d11");
lib.linkSystemLibrary("dxgi");
}
}
const csrc_root = "src/sokol/c/";
const csources = [_][]const u8{
"sokol_log.c",
"sokol_app.c",
"sokol_gfx.c",
"sokol_time.c",
"sokol_audio.c",
"sokol_gl.c",
"sokol_debugtext.c",
"sokol_shape.c",
"sokol_glue.c",
"sokol_fetch.c",
"sokol_memtrack.c",
};
// finally add the C source files
inline for (csources) |csrc| {
lib.addCSourceFile(.{
.file = b.path(csrc_root ++ csrc),
.flags = cflags.slice(),
});
}
if (options.with_sokol_imgui) {
if (b.lazyDependency("imgui", .{})) |dep| {
if (options.imgui_version) |imgui_version| {
const imgui = dep.path(imgui_version);
lib.addIncludePath(imgui);
}
}
if (options.sokol_imgui_cprefix) |cprefix| {
try cflags.append(b.fmt("-DSOKOL_IMGUI_CPREFIX={s}", .{cprefix}));
}
if (options.cimgui_header_path) |cimgui_header_path| {
try cflags.append(b.fmt("-DCIMGUI_HEADER_PATH=\"{s}\"", .{cimgui_header_path}));
}
lib.addCSourceFile(.{
.file = b.path(csrc_root ++ "sokol_imgui.c"),
.flags = cflags.slice(),
});
}
return lib;
}
pub fn build(b: *Build) !void {
const opt_use_gl = b.option(bool, "gl", "Force OpenGL (default: false)") orelse false;
const opt_use_gles3 = b.option(bool, "gles3", "Force OpenGL ES3 (default: false)") orelse false;
const opt_use_wgpu = b.option(bool, "wgpu", "Force WebGPU (default: false, web only)") orelse false;
const opt_use_x11 = b.option(bool, "x11", "Force X11 (default: true, Linux only)") orelse true;
const opt_use_wayland = b.option(bool, "wayland", "Force Wayland (default: false, Linux only, not supported in main-line headers)") orelse false;
const opt_use_egl = b.option(bool, "egl", "Force EGL (default: false, Linux only)") orelse false;
const opt_with_sokol_imgui = b.option(bool, "imgui", "Add support for sokol_imgui.h bindings") orelse false;
const opt_sokol_imgui_cprefix = b.option([]const u8, "sokol_imgui_cprefix", "Override Dear ImGui C bindings prefix for sokol_imgui.h (see SOKOL_IMGUI_CPREFIX)");
const opt_cimgui_header_path = b.option([]const u8, "cimgui_header_path", "Override the Dear ImGui C bindings header name (default: cimgui.h)");
const sokol_backend: SokolBackend = if (opt_use_gl) .gl else if (opt_use_gles3) .gles3 else if (opt_use_wgpu) .wgpu else .auto;
const imguiver_path = switch (b.option(
imguiVersion,
"imgui-version",
"Select ImGui version to use",
) orelse imguiVersion.default) {
.default => "src",
.docking => "src-docking",
};
// For debug
const sanitize_c = b.option(bool, "ubsan", "Enable undefined behavior sanitizer") orelse false;
const sanitize_thread = b.option(bool, "tsan", "Enable thread sanitizer") orelse false;
// LDC-options options
const dub_artifact = b.option(bool, "artifact", "Build artifacts (default: false)") orelse false;
const opt_betterC = b.option(bool, "betterC", "Omit generating some runtime information and helper functions (default: false)") orelse false;
const opt_zigcc = b.option(bool, "zigCC", "Use zig cc as compiler and linker (default: false)") orelse false;
// Build Shaders
const opt_shaders = b.option(bool, "shaders", "Build shaders (default: false)") orelse false;
// ldc2 w/ druntime + phobos2 works on MSVC
const target = b.standardTargetOptions(.{ .default_target = if (builtin.os.tag == .windows) try std.Target.Query.parse(.{ .arch_os_abi = "native-windows-msvc" }) else .{} });
const optimize = b.standardOptimizeOption(.{});
// Get emsdk dependency if targeting WebAssembly, otherwise null
const emsdk = enableWasm(b, target);
const lib_sokol = try buildLibSokol(b, .{
.target = target,
.optimize = optimize,
.backend = sokol_backend,
.use_wayland = opt_use_wayland,
.use_x11 = opt_use_x11,
.use_egl = opt_use_egl,
.with_sokol_imgui = opt_with_sokol_imgui,
.sokol_imgui_cprefix = opt_sokol_imgui_cprefix,
.cimgui_header_path = opt_cimgui_header_path,
.imgui_version = imguiver_path,
.emsdk = emsdk,
.use_ubsan = sanitize_c,
.use_tsan = sanitize_thread,
});
var lib_imgui: ?*CompileStep = null;
if (opt_with_sokol_imgui) {
const imgui = try buildImgui(b, .{
.target = target,
.optimize = optimize,
.version = imguiver_path,
.use_ubsan = sanitize_c,
.use_tsan = sanitize_thread,
});
imgui.step.dependOn(&lib_sokol.step);
lib_imgui = imgui;
}
if (opt_shaders)
buildShaders(b, target);
if (dub_artifact) {
if (opt_with_sokol_imgui)
b.installArtifact(lib_imgui.?);
b.installArtifact(lib_sokol);
} else {
// build examples
const examples = .{
"blend",
"bufferoffsets",
"clear",
"cube",
"debugtext",
"instancing",
"mrt",
"noninterleaved",
"offscreen",
"quad",
"saudio",
"sgl_context",
"sgl_points",
"shapes",
"texcube",
"triangle",
"user_data", // Need GC for user data [associative array]
"vertexpull",
"droptest",
"imgui",
};
inline for (examples) |example| {
if (std.mem.eql(u8, example, "imgui") or std.mem.eql(u8, example, "droptest"))
if (!opt_with_sokol_imgui)
break;
const ldc = try ldcBuildStep(b, .{
.name = example,
.artifact = lib_sokol,
.imgui = lib_imgui,
.sources = &[_][]const u8{
b.fmt("{s}/src/examples/{s}.d", .{ rootPath(), example }),
},
.betterC = if (std.mem.eql(u8, example, "user-data")) false else opt_betterC,
.dflags = &.{
"-w",
"-preview=all",
},
// fixme: https://github.com/kassane/sokol-d/issues/1 - betterC works on darwin
.zig_cc = if (target.result.isDarwin() and !opt_betterC) false else opt_zigcc,
.target = target,
.optimize = optimize,
// send ldc2-obj (wasm artifact) to emcc
.kind = if (target.result.isWasm()) .obj else .exe,
.emsdk = emsdk,
.backend = sokol_backend,
.with_sokol_imgui = opt_with_sokol_imgui,
});
b.getInstallStep().dependOn(&ldc.step);
}
}
// build tests
// fixme: not building on Windows libsokol w/ kind test (missing cc [??])
_ = try ldcBuildStep(b, .{
.name = "test-math",
.kind = .@"test",
.target = b.graph.host,
.sources = &.{b.fmt("{s}/src/handmade/math.d", .{rootPath()})},
.dflags = &.{},
});
}
// Use LDC2 (https://github.com/ldc-developers/ldc) to compile the D examples
pub fn ldcBuildStep(b: *Build, options: DCompileStep) !*Build.Step.InstallDir {
// ldmd2: ldc2 wrapped w/ dmd flags
const ldc = try b.findProgram(&.{"ldmd2"}, &.{});
// D compiler
var ldc_exec = b.addSystemCommand(&.{ldc});
ldc_exec.setName(options.name);
// set kind of build
switch (options.kind) {
.@"test" => {
ldc_exec.addArgs(&.{
"-unittest",
"-main",
});
},
.obj => ldc_exec.addArg("-c"),
else => {},
}
if (options.kind == .lib) {
if (options.linkage == .dynamic) {
ldc_exec.addArg("-shared");
if (options.target.result.os.tag == .windows) {
ldc_exec.addArg("-fvisibility=public");
ldc_exec.addArg("--dllimport=all");
}
} else {
ldc_exec.addArg("-lib");
if (options.target.result.os.tag == .windows)
ldc_exec.addArg("--dllimport=defaultLibsOnly");
ldc_exec.addArg("-fvisibility=hidden");
}
}
for (options.dflags) |dflag| {
ldc_exec.addArg(dflag);
}
if (options.includePaths) |includePath| {
for (includePath) |dir| {
if (dir[0] == '-') {
@panic("add includepath only!");
}
ldc_exec.addArg(b.fmt("-I{s}", .{dir}));
}
}
if (options.ldflags) |ldflags| {
for (ldflags) |ldflag| {
if (ldflag[0] == '-') {
@panic("ldflags: add library name only!");
}
ldc_exec.addArg(b.fmt("-L-l{s}", .{ldflag}));
}
}
// betterC disable druntime and phobos
if (options.betterC)
ldc_exec.addArg("-betterC");
// verbose error messages
ldc_exec.addArg("-verrors=context");
switch (options.optimize) {
.Debug => {
ldc_exec.addArgs(&.{
"-debug",
"-d-debug",
"--gc",
"-g",
"-gf",
"-gs",
"-vgc",
"-vtls",
"-boundscheck=on",
"--link-debuglib",
});
},
.ReleaseSafe => {
ldc_exec.addArgs(&.{
"-O",
"-boundscheck=safeonly",
});
},
.ReleaseFast => {
ldc_exec.addArgs(&.{
"-O",
"-boundscheck=off",
"--enable-asserts=false",
"--strip-debug",
});
},
.ReleaseSmall => {
ldc_exec.addArgs(&.{
"-Oz",
"-boundscheck=off",
"--enable-asserts=false",
"--strip-debug",
});
},
}
// Print character (column) numbers in diagnostics
ldc_exec.addArg("-vcolumns");
const extFile = switch (options.kind) {
.exe, .@"test" => options.target.result.exeFileExt(),
.lib => if (options.linkage == .static) options.target.result.staticLibSuffix() else options.target.result.dynamicLibSuffix(),
.obj => if (options.target.result.os.tag == .windows) ".obj" else ".o",
};
// object file output (zig-cache/o/{hash_id}/*.o)
const objpath = ldc_exec.addPrefixedOutputFileArg("-of=", try std.mem.concat(b.allocator, u8, &.{ options.name, extFile }));
if (b.cache_root.path) |dir| {
// mutable state hash (ldc2 cache - llvm-ir2obj)
ldc_exec.addArg(b.fmt("-cache={s}", .{b.pathJoin(&.{
dir,
"o",
&b.graph.cache.hash.final(),
})}));
}
// disable LLVM-IR verifier
// https://llvm.org/docs/Passes.html#verify-module-verifier
ldc_exec.addArg("-disable-verify");
// keep all function bodies in .di files
ldc_exec.addArg("-Hkeep-all-bodies");
// automatically finds needed modules
ldc_exec.addArgs(&.{
"-i=sokol",
"-i=shaders",
"-i=handmade",
"-i=imgui",
});
// sokol include path
ldc_exec.addArg(b.fmt("-I{s}", .{b.pathJoin(&.{ rootPath(), "src" })}));
// D-packages include path
if (options.d_packages) |d_packages| {
for (d_packages) |pkg| {
ldc_exec.addArg(b.fmt("-I{s}", .{pkg}));
}
}
// D Source files
for (options.sources) |src| {
ldc_exec.addFileArg(path(b, src));
}
// linker flags
// GNU LD
if (options.target.result.os.tag == .linux and !options.zig_cc) {
ldc_exec.addArg("-L--no-as-needed");
}
// LLD (not working in zld)
if (options.target.result.isDarwin() and !options.zig_cc) {
// https://github.com/ldc-developers/ldc/issues/4501
ldc_exec.addArg("-L-w"); // hide linker warnings
}
if (options.target.result.isWasm()) {
ldc_exec.addArg("-L-allow-undefined");
// Create a temporary D file for wasm assert function
const tmp = b.addWriteFiles();
ldc_exec.addFileArg(
tmp.add(
"assert.d",
\\ module emscripten;
\\
\\ extern (C):
\\
\\ version (Emscripten)
\\ {
\\ union fpos_t
\\ {
\\ char[16] __opaque = 0;
\\ long __lldata;
\\ double __align;
\\ }
\\
\\ struct _IO_FILE;
\\ alias _IO_FILE _iobuf; // for phobos2 compat
\\ alias shared(_IO_FILE) FILE;
\\
\\ extern __gshared FILE* stdin;
\\ extern __gshared FILE* stdout;
\\ extern __gshared FILE* stderr;
\\ enum
\\ {
\\ _IOFBF = 0,
\\ _IOLBF = 1,
\\ _IONBF = 2,
\\ }
\\
\\ void __assert(scope const(char)* msg, scope const(char)* file, uint line) @nogc nothrow
\\ {
\\ fprintf(stderr, "Assertion failed in %s:%u: %s\n", file, line, msg);
\\ abort();
\\ }
\\
\\ void _d_assert(string file, uint line) @nogc nothrow
\\ {
\\ fprintf(stderr, "Assertion failed in %s:%u\n", file.ptr, line);
\\ abort();
\\ }
\\
\\ void _d_assert_msg(string msg, string file, uint line) @nogc nothrow
\\ {
\\ __assert(msg.ptr, file.ptr, line);
\\ }
\\
\\ void abort() @nogc nothrow;
\\
\\ pragma(printf)
\\ int fprintf(FILE* __restrict, scope const(char)* __restrict, scope...) @nogc nothrow;
\\
\\ // boundchecking
\\ void _d_arraybounds_index(string file, uint line, size_t index, size_t length) @nogc nothrow
\\ {
\\ if (index >= length)
\\ __assert("Array index out of bounds".ptr, file.ptr, line);
\\ }
\\ }
,
),
);
}
if (b.verbose) {
ldc_exec.addArg("-vdmd");
ldc_exec.addArg("-Xcc=-v");
}
if (options.artifact) |lib_sokol| {
if (lib_sokol.linkage == .dynamic or options.linkage == .dynamic) {
// linking the druntime/Phobos as dynamic libraries
ldc_exec.addArg("-link-defaultlib-shared");
}
// C include path
for (lib_sokol.root_module.include_dirs.items) |include_dir| {
if (include_dir == .other_step) continue;
const dir = if (include_dir == .path)
include_dir.path.getPath(b)
else if (include_dir == .path_system)
include_dir.path_system.getPath(b)
else
include_dir.path_after.getPath(b);
ldc_exec.addArg(b.fmt("-P-I{s}", .{dir}));
}
// library paths
for (lib_sokol.root_module.lib_paths.items) |libpath| {
if (libpath.getPath(b).len > 0) // skip empty paths
ldc_exec.addArg(b.fmt("-L-L{s}", .{libpath.getPath(b)}));
}
// link system libs
for (lib_sokol.root_module.link_objects.items) |link_object| {
if (link_object != .system_lib) continue;
const system_lib = link_object.system_lib;
ldc_exec.addArg(b.fmt("-L-l{s}", .{system_lib.name}));
}
// C flags
for (lib_sokol.root_module.link_objects.items) |link_object| {
if (link_object != .c_source_file) continue;
const c_source_file = link_object.c_source_file;
for (c_source_file.flags) |flag|
if (flag.len > 0) // skip empty flags
ldc_exec.addArg(b.fmt("-Xcc={s}", .{flag}));
break;
}
// C defines
for (lib_sokol.root_module.c_macros.items) |cdefine| {
if (cdefine.len > 0) // skip empty cdefines
ldc_exec.addArg(b.fmt("-P-D{s}", .{cdefine}));
break;
}
if (lib_sokol.dead_strip_dylibs) {
ldc_exec.addArg("-L=-dead_strip");
}
// Darwin frameworks
if (options.target.result.isDarwin()) {
var it = lib_sokol.root_module.frameworks.iterator();
while (it.next()) |framework| {
ldc_exec.addArg(b.fmt("-L-framework", .{}));
ldc_exec.addArg(b.fmt("-L{s}", .{framework.key_ptr.*}));
}
}
if (lib_sokol.root_module.sanitize_thread) |tsan| {
if (tsan)
ldc_exec.addArg("--fsanitize=thread");
}
if (lib_sokol.root_module.omit_frame_pointer) |enabled| {
if (enabled)
ldc_exec.addArg("--frame-pointer=none")
else
ldc_exec.addArg("--frame-pointer=all");
}
// link-time optimization
if (lib_sokol.want_lto) |enabled|
if (enabled) ldc_exec.addArg("--flto=full");
}
// ldc2 doesn't support zig native (a.k.a: native-native or native)
const mtriple = if (options.target.result.isDarwin())
b.fmt("{s}-apple-{s}", .{ if (options.target.result.cpu.arch.isAARCH64()) "arm64" else @tagName(options.target.result.cpu.arch), @tagName(options.target.result.os.tag) })
else if (options.target.result.isWasm() and options.target.result.os.tag == .freestanding)
b.fmt("{s}-unknown-unknown-wasm", .{@tagName(options.target.result.cpu.arch)})
else if (options.target.result.isWasm())
b.fmt("{s}-unknown-{s}", .{ @tagName(options.target.result.cpu.arch), @tagName(options.target.result.os.tag) })
else
b.fmt("{s}-{s}-{s}", .{ @tagName(options.target.result.cpu.arch), @tagName(options.target.result.os.tag), @tagName(options.target.result.abi) });
ldc_exec.addArg(b.fmt("-mtriple={s}", .{mtriple}));
const cpu_model = options.target.result.cpu.model.llvm_name orelse "generic";
ldc_exec.addArg(b.fmt("-mcpu={s}", .{cpu_model}));
const outputDir = switch (options.kind) {
.lib => "lib",
.exe => "bin",
.@"test" => "test",
.obj => "obj",
};
// output file
const installdir = b.addInstallDirectory(.{
.install_dir = .prefix,
.source_dir = objpath.dirname(),
.install_subdir = outputDir,
.exclude_extensions = &.{
"o",
"obj",
},
});
installdir.step.dependOn(&ldc_exec.step);
if (options.zig_cc) {
const target_options = try buildOptions(b, options.target);
const zcc = buildZigCC(b, target_options);
ldc_exec.addPrefixedFileArg("--gcc=", zcc.getEmittedBin());
ldc_exec.addPrefixedFileArg("--linker=", zcc.getEmittedBin());
}
const example_run = b.addSystemCommand(&.{b.pathJoin(&.{ b.install_path, outputDir, options.name })});
example_run.step.dependOn(&installdir.step);
const run = if (options.kind != .@"test")
b.step(b.fmt("run-{s}", .{options.name}), b.fmt("Run {s} example", .{options.name}))
else
b.step("test", "Run all tests");
if (options.target.result.isWasm()) {
ldc_exec.step.dependOn(&options.artifact.?.step);
// get D object file and put it in the wasm artifact
const artifact = addArtifact(b, options);
artifact.addObjectFile(objpath);
if (options.artifact) |lib_sokol| {
if (options.with_sokol_imgui) {
if (options.imgui) |lib_imgui| {
for (lib_sokol.root_module.include_dirs.items) |include_dir| {
try lib_imgui.root_module.include_dirs.append(b.allocator, include_dir);
}
artifact.linkLibrary(lib_imgui);
}
}
artifact.linkLibrary(lib_sokol);
}
artifact.step.dependOn(&ldc_exec.step);
const backend = resolveSokolBackend(options.backend, options.target.result);
const link_step = try emLinkStep(b, .{
.lib_main = artifact,
.target = options.target,
.optimize = options.optimize,
.emsdk = options.emsdk orelse null,
.use_webgpu = backend == .wgpu,
.use_webgl2 = backend != .wgpu,
.use_emmalloc = true,
.use_filesystem = false,
.use_ubsan = options.artifact.?.root_module.sanitize_c orelse false,
.release_use_lto = options.artifact.?.want_lto orelse false,
.shell_file_path = b.path("src/sokol/web/shell.html"),
.extra_args = &.{"-sSTACK_SIZE=512KB"},
});
link_step.step.dependOn(&ldc_exec.step);
const emrun = emRunStep(b, .{ .name = options.name, .emsdk = options.emsdk orelse null });
emrun.step.dependOn(&link_step.step);
run.dependOn(&emrun.step);
} else {
if (options.artifact) |lib_sokol| {
if (lib_sokol.rootModuleTarget().os.tag == .windows and lib_sokol.isDynamicLibrary()) {
ldc_exec.addArg(b.pathJoin(&.{
b.install_path,
"lib",
b.fmt("{s}.lib", .{lib_sokol.name}),
}));
} else {
if (options.with_sokol_imgui) {
if (options.imgui) |lib_imgui| {
ldc_exec.addArtifactArg(lib_imgui);
}
}
ldc_exec.addArtifactArg(lib_sokol);
for (lib_sokol.getCompileDependencies(false)) |item| {
if (item.kind == .lib) {
ldc_exec.addArtifactArg(item);
}
}
}
}
run.dependOn(&example_run.step);
}
return installdir;
}
pub const DCompileStep = struct {
target: Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode = .Debug,
kind: CompileStep.Kind = .exe,
linkage: std.builtin.LinkMode = .static,
betterC: bool = false,
sources: []const []const u8,
dflags: []const []const u8,
includePaths: ?[]const []const u8 = null,
ldflags: ?[]const []const u8 = null,
name: []const u8,
zig_cc: bool = false,
d_packages: ?[]const []const u8 = null,
artifact: ?*Build.Step.Compile = null,
imgui: ?*Build.Step.Compile = null,
with_sokol_imgui: bool = false,
emsdk: ?*Build.Dependency = null,
backend: SokolBackend = .auto,
};
pub fn addArtifact(b: *Build, options: DCompileStep) *Build.Step.Compile {
return Build.Step.Compile.create(b, .{
.name = options.name,
.root_module = b.createModule(.{
.target = options.target,
.optimize = options.optimize,
}),
.linkage = options.linkage,
.kind = options.kind,
});
}
pub fn path(b: *Build, sub_path: []const u8) Build.LazyPath {
if (std.fs.path.isAbsolute(sub_path)) {
return .{
.cwd_relative = sub_path,
};
} else return .{
.src_path = .{
.owner = b,
.sub_path = sub_path,
},
};
}
// -------------------------- Others Configuration --------------------------
// zig-cc wrapper for ldc2
pub fn buildZigCC(b: *Build, options: *Build.Step.Options) *CompileStep {
const zigcc = b.addWriteFiles();
const exe = b.addExecutable(.{
.name = "zcc",
.target = b.graph.host,
.optimize = .ReleaseSafe,
.root_source_file = zigcc.add("zcc.zig", generated_zcc),
});
exe.root_module.addOptions("build_options", options);
return exe;
}
pub fn buildOptions(b: *Build, target: Build.ResolvedTarget) !*Build.Step.Options {
const zigcc_options = b.addOptions();
// Native target, zig can read 'zig libc' contents and also link system libraries.
const native = if (target.query.isNative()) switch (target.result.abi) {
.msvc => "native-native-msvc",
else => "native-native",
} else try target.result.zigTriple(b.allocator);
zigcc_options.addOption(
?[]const u8,
"triple",
native,
);
zigcc_options.addOption(
?[]const u8,
"cpu",
target.result.cpu.model.name,
);
return zigcc_options;
}
const generated_zcc =
\\ const std = @import("std");
\\ const builtin = @import("builtin");
\\ const build_options = @import("build_options");
\\ // [NOT CHANGE!!] => skip flag
\\ // replace system-provider resources to zig provider resources
\\
\\ pub fn main() !void {
\\ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
\\ defer _ = std.debug.assert(gpa.deinit() == .ok); // ok or leak
\\ const allocator = gpa.allocator();
\\
\\ var args = try std.process.argsWithAllocator(allocator);
\\ defer args.deinit();
\\
\\ _ = args.skip(); // skip arg[0]
\\
\\ var cmds = std.ArrayList([]const u8).init(allocator);
\\ defer cmds.deinit();
\\
\\ try cmds.append("zig");
\\ try cmds.append("cc");
\\
\\ while (args.next()) |arg| {
\\ // HACK: ldmd2 emit '-target' flag for Darwin, but zigcc already have it
\\ if (std.mem.startsWith(u8, arg, "arm64-apple-") or
\\ std.mem.startsWith(u8, arg, "x86_64-apple-"))
\\ {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "-target")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "-group")) {
\\ try cmds.appendSlice(&.{
\\ "-Wl,--start-group",
\\ "-Wl,--end-group",
\\ });
\\ } else if (std.mem.endsWith(u8, arg, "-dynamic")) {
\\ try cmds.append("-Wl,--export-dynamic");
\\ } else if (std.mem.eql(u8, arg, "--exclude-libs") or std.mem.eql(u8, arg, "ALL")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "rv64gc") or
\\ std.mem.endsWith(u8, arg, "rv32i_zicsr_zifencei"))
\\ {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "--hash-style")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "--build-id")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "whole-archive")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "--eh-frame-hdr")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "as-needed")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "gcc") or
\\ std.mem.endsWith(u8, arg, "gcc_s"))
\\ {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "-lFortran")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "linkonceodr-outlining")) {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "aarch64linux") or
\\ std.mem.startsWith(u8, arg, "elf"))
\\ {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "/lib/ld-") or
\\ std.mem.startsWith(u8, arg, "-dynamic-linker"))
\\ {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "crtendS.o") or
\\ std.mem.endsWith(u8, arg, "crtn.o"))
\\ {
\\ // NOT CHANGE!!
\\ } else if (std.mem.endsWith(u8, arg, "crtbeginS.o") or
\\ std.mem.endsWith(u8, arg, "crti.o") or
\\ std.mem.endsWith(u8, arg, "Scrt1.o"))
\\ {
\\ // NOT CHANGE!!
\\ } else if (std.mem.startsWith(u8, arg, "-m") or
\\ std.mem.startsWith(u8, arg, "elf_"))
\\ {
\\ // NOT CHANGE!!
\\ } else {
\\ try cmds.append(arg);
\\ }
\\ }
\\
\\ if (build_options.triple) |triple_target| {
\\ try cmds.append("-target");
\\ try cmds.append(triple_target);
\\ }
\\ if (build_options.cpu) |cpu| {
\\ try cmds.append(std.fmt.comptimePrint("-mcpu={s}", .{cpu}));
\\ }
\\
\\ if (builtin.os.tag != .windows) {
\\ try cmds.append("-lunwind");
\\ }
\\
\\ var proc = std.process.Child.init(cmds.items, allocator);
\\
\\ try std.io.getStdOut().writer().print("[zig cc] flags: \"", .{});
\\ for (cmds.items) |cmd| {
\\ if (std.mem.startsWith(u8, cmd, "zig")) continue;
\\ if (std.mem.startsWith(u8, cmd, "cc")) continue;
\\ try std.io.getStdOut().writer().print("{s} ", .{cmd});
\\ }
\\ try std.io.getStdOut().writer().print("\"\n", .{});
\\
\\ _ = try proc.spawnAndWait();
\\ }
;
// -------------------------- Build Steps --------------------------
// a separate step to compile shaders, expects the shader compiler in ../sokol-tools-bin/
fn buildShaders(b: *Build, target: Build.ResolvedTarget) void {
if (b.lazyDependency("shdc", .{})) |dep| {
const shdc_dep = dep.path("").getPath(b);
const sokol_tools_bin_dir = b.pathJoin(&.{ shdc_dep, "bin" });
const shaders_dir = "src/examples/shaders/";
const shaders = .{
"triangle.glsl",
"bufferoffsets.glsl",
"cube.glsl",
"instancing.glsl",
"mrt.glsl",
"noninterleaved.glsl",
"offscreen.glsl",
"quad.glsl",
"shapes.glsl",
"texcube.glsl",
"blend.glsl",
"vertexpull.glsl",
};
const optional_shdc: ?[:0]const u8 = comptime switch (builtin.os.tag) {
.windows => "win32/sokol-shdc.exe",
.linux => if (builtin.cpu.arch.isX86()) "linux/sokol-shdc" else "linux_arm64/sokol-shdc",