forked from ikskuh/SDL.zig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.zig
633 lines (540 loc) · 22.7 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
//! SDL2 Zig SDK
//! ============
//! This file provides a build api that allows you to link and use
//! SDL2 from zig.
//!
const std = @import("std");
const builtin = @import("builtin");
pub fn build(b: *std.Build) !void {
const sdk = Sdk.init(b, null);
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const sdl_linkage = b.option(std.builtin.LinkMode, "link", "Defines how to link SDL2 when building with mingw32") orelse .dynamic;
const skip_tests = b.option(bool, "skip-test", "When set, skips the test suite to be run. This is required for cross-builds") orelse false;
if (!skip_tests) {
const lib_test = b.addTest(.{
.root_source_file = .{ .cwd_relative = "src/wrapper/sdl.zig" },
.target = if (target.result.os.tag == .windows)
b.resolveTargetQuery(.{ .abi = target.result.abi })
else
null,
});
lib_test.root_module.addImport("sdl-native", sdk.getNativeModule());
lib_test.linkSystemLibrary("sdl2_image");
lib_test.linkSystemLibrary("sdl2_ttf");
if (lib_test.rootModuleTarget().isDarwin()) {
// SDL_TTF
lib_test.linkSystemLibrary("freetype");
lib_test.linkSystemLibrary("harfbuzz");
lib_test.linkSystemLibrary("bz2");
lib_test.linkSystemLibrary("zlib");
lib_test.linkSystemLibrary("graphite2");
// SDL_IMAGE
lib_test.linkSystemLibrary("jpeg");
lib_test.linkSystemLibrary("libpng");
lib_test.linkSystemLibrary("tiff");
lib_test.linkSystemLibrary("sdl2");
lib_test.linkSystemLibrary("webp");
}
sdk.link(lib_test, .dynamic);
const test_lib_step = b.step("test", "Runs the library tests.");
test_lib_step.dependOn(&lib_test.step);
}
const demo_wrapper = b.addExecutable(.{
.name = "demo-wrapper",
.root_source_file = .{ .cwd_relative = "examples/wrapper.zig" },
.target = target,
.optimize = optimize,
});
sdk.link(demo_wrapper, sdl_linkage);
demo_wrapper.root_module.addImport("sdl2", sdk.getWrapperModule());
b.installArtifact(demo_wrapper);
const demo_wrapper_image = b.addExecutable(.{
.name = "demo-wrapper-image",
.root_source_file = .{ .cwd_relative = "examples/wrapper-image.zig" },
.target = target,
.optimize = optimize,
});
sdk.link(demo_wrapper_image, sdl_linkage);
demo_wrapper_image.root_module.addImport("sdl2", sdk.getWrapperModule());
demo_wrapper_image.linkSystemLibrary("sdl2_image");
demo_wrapper_image.linkSystemLibrary("jpeg");
demo_wrapper_image.linkSystemLibrary("libpng");
demo_wrapper_image.linkSystemLibrary("tiff");
demo_wrapper_image.linkSystemLibrary("webp");
if (target.query.isNative() and target.result.os.tag == .linux) {
b.installArtifact(demo_wrapper_image);
}
const demo_native = b.addExecutable(.{
.name = "demo-native",
.root_source_file = .{ .cwd_relative = "examples/native.zig" },
.target = target,
.optimize = optimize,
});
sdk.link(demo_native, sdl_linkage);
demo_native.root_module.addImport("sdl2", sdk.getNativeModule());
b.installArtifact(demo_native);
const run_demo_wrappr = b.addRunArtifact(demo_wrapper);
const run_demo_wrappr_image = b.addRunArtifact(demo_wrapper_image);
const run_demo_native = b.addRunArtifact(demo_native);
const run_demo_wrapper_step = b.step("run-wrapper", "Runs the demo for the SDL2 wrapper library");
run_demo_wrapper_step.dependOn(&run_demo_wrappr.step);
const run_demo_wrapper_image_step = b.step("run-wrapper-image", "Runs the demo for the SDL2 wrapper library");
run_demo_wrapper_image_step.dependOn(&run_demo_wrappr_image.step);
const run_demo_native_step = b.step("run-native", "Runs the demo for the SDL2 native library");
run_demo_native_step.dependOn(&run_demo_native.step);
}
const host_system = @import("builtin").target;
const Build = std.Build;
const Step = Build.Step;
const LazyPath = Build.LazyPath;
const GeneratedFile = Build.GeneratedFile;
const Compile = Build.Step.Compile;
const Sdk = @This();
fn sdkPath(comptime suffix: []const u8) []const u8 {
if (suffix[0] != '/') @compileError("relToPath requires an absolute path!");
return comptime blk: {
const root_dir = std.fs.path.dirname(@src().file) orelse ".";
break :blk root_dir ++ suffix;
};
}
const sdl2_symbol_definitions = @embedFile("stubs/libSDL2.def");
build: *Build,
config_path: []const u8,
prepare_sources: *PrepareStubSourceStep,
/// Creates a instance of the Sdk and initializes internal steps.
/// Initialize once, use everywhere (in your `build` function).
pub fn init(b: *Build, maybe_config_path: ?[]const u8) *Sdk {
const sdk = b.allocator.create(Sdk) catch @panic("out of memory");
const config_path = maybe_config_path orelse std.fs.path.join(
b.allocator,
&[_][]const u8{
b.pathFromRoot(".build_config"),
"sdl.json",
},
) catch @panic("out of memory");
sdk.* = .{
.build = b,
.config_path = config_path,
.prepare_sources = undefined,
};
sdk.prepare_sources = PrepareStubSourceStep.create(sdk);
return sdk;
}
/// Returns a module with the raw SDL api with proper argument types, but no functional/logical changes
/// for a more *ziggy* feeling.
/// This is similar to the *C import* result.
pub fn getNativeModule(sdk: *Sdk) *Build.Module {
const build_options = sdk.build.addOptions();
build_options.addOption(bool, "vulkan", false);
return sdk.build.createModule(.{
.root_source_file = .{ .cwd_relative = sdkPath("/src/binding/sdl.zig") },
.imports = &.{
.{
.name = sdk.build.dupe("build_options"),
.module = build_options.createModule(),
},
},
});
}
/// Returns a module with the raw SDL api with proper argument types, but no functional/logical changes
/// for a more *ziggy* feeling, with Vulkan support! The Vulkan module provided by `vulkan-zig` must be
/// provided as an argument.
/// This is similar to the *C import* result.
pub fn getNativeModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module {
const build_options = sdk.build.addOptions();
build_options.addOption(bool, "vulkan", true);
return sdk.build.createModule(.{
.root_source_file = .{ .cwd_relative = sdkPath("/src/binding/sdl.zig") },
.imports = &.{
.{
.name = sdk.build.dupe("build_options"),
.module = build_options.createModule(),
},
.{
.name = sdk.build.dupe("vulkan"),
.module = vulkan,
},
},
});
}
/// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on.
pub fn getWrapperModule(sdk: *Sdk) *Build.Module {
return sdk.build.createModule(.{
.root_source_file = .{ .cwd_relative = sdkPath("/src/wrapper/sdl.zig") },
.imports = &.{
.{
.name = sdk.build.dupe("sdl-native"),
.module = sdk.getNativeModule(),
},
},
});
}
/// Returns the smart wrapper with Vulkan support. The Vulkan module provided by `vulkan-zig` must be
/// provided as an argument.
pub fn getWrapperModuleVulkan(sdk: *Sdk, vulkan: *Build.Module) *Build.Module {
return sdk.build.createModule(.{
.root_source_file = .{ .cwd_relative = sdkPath("/src/wrapper/sdl.zig") },
.imports = &.{
.{
.name = sdk.build.dupe("sdl-native"),
.module = sdk.getNativeModuleVulkan(vulkan),
},
.{
.name = sdk.build.dupe("vulkan"),
.module = vulkan,
},
},
});
}
/// Links SDL2 TTF to the given exe.
/// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing!
pub fn linkTtf(sdk: *Sdk, exe: *Compile) void {
const b = sdk.build;
const target = exe.root_module.resolved_target.?;
const is_native = target.query.isNativeOs();
if (target.result.os.tag == .linux) {
if (!is_native) {
@panic("Cannot cross-compile with TTF to linux yet.");
}
// on linux with compilation for native target,
// we should rely on the system libraries to "just work"
exe.linkSystemLibrary("sdl2_ttf");
} else if (target.result.os.tag == .windows) {
@panic("Cannot link TTF on windows yet.");
} else if (target.result.isDarwin()) {
if (!host_system.os.tag.isDarwin())
@panic("Cannot cross-compile with TTF to macOS yet.");
exe.linkSystemLibrary("sdl2_ttf");
exe.linkSystemLibrary("freetype");
exe.linkSystemLibrary("harfbuzz");
exe.linkSystemLibrary("bz2");
exe.linkSystemLibrary("zlib");
exe.linkSystemLibrary("graphite2");
} else {
const triple_string = target.query.zigTriple(b.allocator) catch "unkown-unkown-unkown";
std.log.warn("Linking SDL2_TTF for {s} is not tested, linking might fail!", .{triple_string});
// on all other platforms, just try the system way:
exe.linkSystemLibrary("sdl2_ttf");
}
}
/// Links SDL2 to the given exe and adds required installs if necessary.
/// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing!
pub fn link(sdk: *Sdk, exe: *Compile, linkage: std.builtin.LinkMode) void {
// TODO: Implement
const b = sdk.build;
const target = exe.root_module.resolved_target.?;
const is_native = target.query.isNativeOs();
// This is required on all platforms
exe.linkLibC();
if (target.result.os.tag == .linux and !is_native) {
// for cross-compilation to Linux, we use a magic trick:
// we compile a stub .so file we will link against an SDL2.so even if that file
// doesn't exist on our system
const build_linux_sdl_stub = b.addSharedLibrary(.{
.name = "SDL2",
.target = exe.root_module.resolved_target.?,
.optimize = exe.root_module.optimize.?,
});
build_linux_sdl_stub.addAssemblyFile(sdk.prepare_sources.getStubFile());
// We need to link against libc
exe.linkLibC();
// link against the output of our stub
exe.linkLibrary(build_linux_sdl_stub);
} else if (target.result.os.tag == .linux) {
// on linux with compilation for native target,
// we should rely on the system libraries to "just work"
exe.linkSystemLibrary("sdl2");
} else if (target.result.os.tag == .windows) {
const sdk_paths = sdk.getPaths(target) catch |err| {
const writer = std.io.getStdErr().writer();
const target_name = tripleName(sdk.build.allocator, target) catch @panic("out of memory");
switch (err) {
error.FileNotFound => {
writer.print("Could not auto-detect SDL2 sdk configuration. Please provide {s} with the following contents filled out:\n", .{
sdk.config_path,
}) catch @panic("io error");
writer.print("{{\n \"{s}\": {{\n", .{target_name}) catch @panic("io error");
writer.writeAll(
\\ "include": "<path to sdl2 sdk>/include",
\\ "libs": "<path to sdl2 sdk>/lib",
\\ "bin": "<path to sdl2 sdk>/bin"
\\ }
\\}
\\
) catch @panic("io error");
writer.writeAll(
\\
\\You can obtain a SDL2 sdk for windows from https://www.libsdl.org/download-2.0.php
\\
) catch @panic("io error");
},
error.MissingTarget => {
writer.print("{s} is missing a SDK definition for {s}. Please add the following section to the file and fill the paths:\n", .{
sdk.config_path,
target_name,
}) catch @panic("io error");
writer.print(" \"{s}\": {{\n", .{target_name}) catch @panic("io error");
writer.writeAll(
\\ "include": "<path to sdl2 sdk>/include",
\\ "libs": "<path to sdl2 sdk>/lib",
\\ "bin": "<path to sdl2 sdk>/bin"
\\}
) catch @panic("io error");
writer.writeAll(
\\
\\You can obtain a SDL2 sdk for windows from https://www.libsdl.org/download-2.0.php
\\
) catch @panic("io error");
},
error.InvalidJson => {
writer.print("{s} contains invalid JSON. Please fix that file!\n", .{
sdk.config_path,
}) catch @panic("io error");
},
error.InvalidTarget => {
writer.print("{s} contains a invalid zig triple. Please fix that file!\n", .{
sdk.config_path,
}) catch @panic("io error");
},
}
std.process.exit(1);
};
// linking on windows is sadly not as trivial as on linux:
// we have to respect 6 different configurations {x86,x64}-{msvc,mingw}-{dynamic,static}
if (target.result.abi == .msvc and linkage != .dynamic)
@panic("SDL cannot be linked statically for MSVC");
// These will be added for C-Imports or C files.
if (target.result.abi != .msvc) {
// SDL2 (mingw) ships the SDL include files under `include/SDL2/` which is very inconsitent with
// all other platforms, so we just remove this prefix here
const include_path = std.fs.path.join(b.allocator, &[_][]const u8{
sdk_paths.include,
"SDL2",
}) catch @panic("out of memory");
exe.addIncludePath(.{ .cwd_relative = include_path });
} else {
exe.addIncludePath(.{ .cwd_relative = sdk_paths.include });
}
// link the right libraries
if (target.result.abi == .msvc) {
// and links those as normal libraries
exe.addLibraryPath(.{ .cwd_relative = sdk_paths.libs });
exe.linkSystemLibrary2("SDL2", .{ .use_pkg_config = .no });
} else {
const file_name = switch (linkage) {
.static => "libSDL2.a",
.dynamic => "libSDL2.dll.a",
};
const lib_path = std.fs.path.join(b.allocator, &[_][]const u8{
sdk_paths.libs,
file_name,
}) catch @panic("out of memory");
exe.addObjectFile(.{ .cwd_relative = lib_path });
if (linkage == .static) {
// link all system libraries required for SDL2:
const static_libs = [_][]const u8{
"setupapi",
"user32",
"gdi32",
"winmm",
"imm32",
"ole32",
"oleaut32",
"shell32",
"version",
"uuid",
};
for (static_libs) |lib|
exe.linkSystemLibrary(lib);
}
}
if (linkage == .dynamic and exe.kind == .exe) {
// On window, we need to copy SDL2.dll to the bin directory
// for executables
const sdl2_dll_path = std.fs.path.join(sdk.build.allocator, &[_][]const u8{
sdk_paths.bin,
"SDL2.dll",
}) catch @panic("out of memory");
sdk.build.installBinFile(sdl2_dll_path, "SDL2.dll");
}
} else if (target.result.isDarwin()) {
// TODO: Implement cross-compilaton to macOS via system root provisioning
if (!host_system.os.tag.isDarwin())
@panic("Cannot cross-compile to macOS yet.");
// on MacOS, we require a brew install
// requires sdl2 and sdl2_image to be installed via brew
exe.linkSystemLibrary("sdl2");
exe.linkFramework("IOKit");
exe.linkFramework("Cocoa");
exe.linkFramework("CoreAudio");
exe.linkFramework("Carbon");
exe.linkFramework("Metal");
exe.linkFramework("QuartzCore");
exe.linkFramework("AudioToolbox");
exe.linkFramework("ForceFeedback");
exe.linkFramework("GameController");
exe.linkFramework("CoreHaptics");
exe.linkSystemLibrary("iconv");
} else {
const triple_string = target.query.zigTriple(b.allocator) catch "unkown-unkown-unkown";
std.log.warn("Linking SDL2 for {s} is not tested, linking might fail!", .{triple_string});
// on all other platforms, just try the system way:
exe.linkSystemLibrary("sdl2");
}
}
const Paths = struct {
include: []const u8,
libs: []const u8,
bin: []const u8,
};
fn getPaths(sdk: *Sdk, target_local: std.Build.ResolvedTarget) error{ MissingTarget, FileNotFound, InvalidJson, InvalidTarget }!Paths {
const json_data = std.fs.cwd().readFileAlloc(sdk.build.allocator, sdk.config_path, 1 << 20) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
else => |e| @panic(@errorName(e)),
};
const parsed = std.json.parseFromSlice(std.json.Value, sdk.build.allocator, json_data, .{}) catch return error.InvalidJson;
var root_node = parsed.value.object;
var config_iterator = root_node.iterator();
while (config_iterator.next()) |entry| {
const config_target = sdk.build.resolveTargetQuery(
std.Target.Query.parse(.{ .arch_os_abi = entry.key_ptr.* }) catch return error.InvalidTarget,
);
if (target_local.result.cpu.arch != config_target.result.cpu.arch)
continue;
if (target_local.result.os.tag != config_target.result.os.tag)
continue;
if (target_local.result.abi != config_target.result.abi)
continue;
// load paths
const node = entry.value_ptr.*.object;
return Paths{
.include = node.get("include").?.string,
.libs = node.get("libs").?.string,
.bin = node.get("bin").?.string,
};
}
return error.MissingTarget;
}
const PrepareStubSourceStep = struct {
const Self = @This();
step: Step,
sdk: *Sdk,
assembly_source: GeneratedFile,
pub fn create(sdk: *Sdk) *PrepareStubSourceStep {
const psss = sdk.build.allocator.create(Self) catch @panic("out of memory");
psss.* = .{
.step = Step.init(
.{
.id = .custom,
.name = "Prepare SDL2 stub sources",
.owner = sdk.build,
.makeFn = make,
},
),
.sdk = sdk,
.assembly_source = .{ .step = &psss.step },
};
return psss;
}
pub fn getStubFile(self: *Self) LazyPath {
return .{ .generated = .{ .file = &self.assembly_source } };
}
fn make(step: *Step, prog_node: std.Progress.Node) !void {
_ = prog_node;
const self: *Self = @fieldParentPtr("step", step);
var cache = CacheBuilder.init(self.sdk.build, "sdl");
cache.addBytes(sdl2_symbol_definitions);
var dirpath = try cache.createAndGetDir();
defer dirpath.dir.close();
var file = try dirpath.dir.createFile("sdl.S", .{});
defer file.close();
var writer = file.writer();
try writer.writeAll(".text\n");
var iter = std.mem.splitScalar(u8, sdl2_symbol_definitions, '\n');
while (iter.next()) |line| {
const sym = std.mem.trim(u8, line, " \r\n\t");
if (sym.len == 0)
continue;
try writer.print(".global {s}\n", .{sym});
try writer.writeAll(".align 4\n");
try writer.print("{s}:\n", .{sym});
try writer.writeAll(" .byte 0\n");
}
self.assembly_source.path = try std.fs.path.join(self.sdk.build.allocator, &[_][]const u8{
dirpath.path,
"sdl.S",
});
}
};
fn tripleName(allocator: std.mem.Allocator, target_local: std.Build.ResolvedTarget) ![]u8 {
const arch_name = @tagName(target_local.result.cpu.arch);
const os_name = @tagName(target_local.result.os.tag);
const abi_name = @tagName(target_local.result.abi);
return std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{ arch_name, os_name, abi_name });
}
const CacheBuilder = struct {
const Self = @This();
build: *std.Build,
hasher: std.crypto.hash.Sha1,
subdir: ?[]const u8,
pub fn init(builder: *std.Build, subdir: ?[]const u8) Self {
return Self{
.build = builder,
.hasher = std.crypto.hash.Sha1.init(.{}),
.subdir = if (subdir) |s|
builder.dupe(s)
else
null,
};
}
pub fn addBytes(self: *Self, bytes: []const u8) void {
self.hasher.update(bytes);
}
pub fn addFile(self: *Self, file: LazyPath) !void {
const path = file.getPath(self.build);
const data = try std.fs.cwd().readFileAlloc(self.build.allocator, path, 1 << 32); // 4 GB
defer self.build.allocator.free(data);
self.addBytes(data);
}
fn createPath(self: *Self) ![]const u8 {
var hash: [20]u8 = undefined;
self.hasher.final(&hash);
const path = if (self.subdir) |subdir|
try std.fmt.allocPrint(
self.build.allocator,
"{s}/{s}/o/{}",
.{
self.build.cache_root.path.?,
subdir,
std.fmt.fmtSliceHexLower(&hash),
},
)
else
try std.fmt.allocPrint(
self.build.allocator,
"{s}/o/{}",
.{
self.build.cache_root.path.?,
std.fmt.fmtSliceHexLower(&hash),
},
);
return path;
}
pub const DirAndPath = struct {
dir: std.fs.Dir,
path: []const u8,
};
pub fn createAndGetDir(self: *Self) !DirAndPath {
const path = try self.createPath();
return DirAndPath{
.path = path,
.dir = try std.fs.cwd().makeOpenPath(path, .{}),
};
}
pub fn createAndGetPath(self: *Self) ![]const u8 {
const path = try self.createPath();
try std.fs.cwd().makePath(path);
return path;
}
};