Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Emscripten support: wasm & webgpu in browser #309

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
51 changes: 39 additions & 12 deletions build.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const builtin = @import("builtin");
const std = @import("std");
pub const zems = @import("libs/zems/build.zig");

pub const min_zig_version = std.SemanticVersion{ .major = 0, .minor = 11, .patch = 0, .pre = "dev.4332" };

Expand All @@ -23,7 +24,7 @@ pub fn build(b: *std.Build) void {
) orelse false,
.zpix_enable = b.option(bool, "zpix-enable", "Enable PIX for Windows profiler") orelse false,
};
ensureTarget(options.target) catch return;
ensureTarget(options) catch return;
ensureGit(b.allocator) catch return;
ensureGitLfs(b.allocator, "install") catch return;
ensureGitLfs(b.allocator, "pull") catch return;
Expand All @@ -47,7 +48,8 @@ pub fn build(b: *std.Build) void {
//
// Sample applications
//
samplesCrossPlatform(b, options);
if (options.target.getOsTag() == .emscripten) samplesEmscripten(b, options)
else samplesCrossPlatform(b, options);

if (options.target.isWindows() and
(builtin.target.os.tag == .windows or builtin.target.os.tag == .linux))
Expand Down Expand Up @@ -81,28 +83,32 @@ fn packagesCrossPlatform(b: *std.Build, options: Options) void {
const target = options.target;
const optimize = options.optimize;

zopengl_pkg = zopengl.package(b, target, optimize, .{});
zmath_pkg = zmath.package(b, target, optimize, .{});
zpool_pkg = zpool.package(b, target, optimize, .{});
zglfw_pkg = zglfw.package(b, target, optimize, .{});
zsdl_pkg = zsdl.package(b, target, optimize, .{});
zmesh_pkg = zmesh.package(b, target, optimize, .{});
znoise_pkg = znoise.package(b, target, optimize, .{});
zstbi_pkg = zstbi.package(b, target, optimize, .{});
zbullet_pkg = zbullet.package(b, target, optimize, .{});
zgui_pkg = zgui.package(b, target, optimize, .{
.options = .{ .backend = .glfw_wgpu },
});
zgpu_pkg = zgpu.package(b, target, optimize, .{
.options = .{ .uniforms_buffer_size = 4 * 1024 * 1024 },
.deps = .{ .zpool = zpool_pkg.zpool, .zglfw = zglfw_pkg.zglfw },
});
zems_pkg = zems.package(b, target, optimize, .{});
ztracy_pkg = ztracy.package(b, target, optimize, .{
.options = .{
.enable_ztracy = !target.isDarwin(), // TODO: ztracy fails to compile on macOS.
.enable_fibers = !target.isDarwin(),
.enable_ztracy = !target.isDarwin() and options.target.getOsTag() != .emscripten, // TODO: ztracy fails to compile on macOS.
Copy link
Member

@hazeycode hazeycode Jun 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@michal-z is this TODO comment still valid? I think we fixed it here: #262?

.enable_fibers = !target.isDarwin() and options.target.getOsTag() != .emscripten,
},
});
zstbi_pkg = zstbi.package(b, target, optimize, .{});

if (options.target.getOsTag() == .emscripten) return;

zopengl_pkg = zopengl.package(b, target, optimize, .{});
zsdl_pkg = zsdl.package(b, target, optimize, .{});
zmesh_pkg = zmesh.package(b, target, optimize, .{});
znoise_pkg = znoise.package(b, target, optimize, .{});
zbullet_pkg = zbullet.package(b, target, optimize, .{});
zphysics_pkg = zphysics.package(b, target, optimize, .{});
zaudio_pkg = zaudio.package(b, target, optimize, .{});
zflecs_pkg = zflecs.package(b, target, optimize, .{});
Expand Down Expand Up @@ -165,6 +171,7 @@ fn samplesCrossPlatform(b: *std.Build, options: Options) void {
const gamepad_wgpu = @import("samples/gamepad_wgpu/build.zig");
const physics_test_wgpu = @import("samples/physics_test_wgpu/build.zig");
const monolith = @import("samples/monolith/build.zig");
const triangle_wgpu_emscripten = @import("samples/triangle_wgpu_emscripten/build.zig");

install(b, minimal_gl.build(b, options), "minimal_gl");
install(b, triangle_wgpu.build(b, options), "triangle_wgpu");
Expand All @@ -179,6 +186,17 @@ fn samplesCrossPlatform(b: *std.Build, options: Options) void {
install(b, physics_test_wgpu.build(b, options), "physics_test_wgpu");
install(b, monolith.build(b, options), "monolith");
install(b, audio_experiments_wgpu.build(b, options), "audio_experiments_wgpu");
install(b, triangle_wgpu_emscripten.build(b, options), "triangle_wgpu_emscripten");
}

fn samplesEmscripten(b: *std.Build, options: Options) void {
const triangle_wgpu_emscripten = @import("samples/triangle_wgpu_emscripten/build.zig");
const gui_test_wgpu = @import("samples/gui_test_wgpu/build.zig");
const instanced_pills_wgpu = @import("samples/instanced_pills_wgpu/build.zig");

installEmscripten(b, triangle_wgpu_emscripten.buildEmscripten(b, options), "triangle_wgpu_emscripten");
installEmscripten(b, gui_test_wgpu.buildEmscripten(b, options), "gui_test_wgpu");
installEmscripten(b, instanced_pills_wgpu.buildEmscripten(b, options), "instanced_pills_wgpu");
}

fn samplesWindowsLinux(b: *std.Build, options: Options) void {
Expand Down Expand Up @@ -247,6 +265,7 @@ pub var ztracy_pkg: ztracy.Package = undefined;
pub var zphysics_pkg: zphysics.Package = undefined;
pub var zaudio_pkg: zaudio.Package = undefined;
pub var zflecs_pkg: zflecs.Package = undefined;
pub var zems_pkg : zems.Package = undefined;

pub var zwin32_pkg: zwin32.Package = undefined;
pub var zd3d12_pkg: zd3d12.Package = undefined;
Expand Down Expand Up @@ -291,7 +310,7 @@ pub const Options = struct {
fn install(b: *std.Build, exe: *std.Build.CompileStep, comptime name: []const u8) void {
// TODO: Problems with LTO on Windows.
exe.want_lto = false;
if (exe.optimize == .ReleaseFast)
if (exe.optimize == .ReleaseFast or exe.optimize == .ReleaseSmall)
exe.strip = true;

//comptime var desc_name: [256]u8 = [_]u8{0} ** 256;
Expand All @@ -309,6 +328,12 @@ fn install(b: *std.Build, exe: *std.Build.CompileStep, comptime name: []const u8
b.getInstallStep().dependOn(install_step);
}

fn installEmscripten(b: *std.Build, exe: *zems.EmscriptenStep, comptime name: []const u8) void {
const install_step = b.step(name, "Build '" ++ name ++ "' demo");
install_step.dependOn(&exe.link_step.?.step);
b.getInstallStep().dependOn(install_step);
}

fn ensureZigVersion() !void {
var installed_ver = @import("builtin").zig_version;
installed_ver.build = null;
Expand All @@ -332,7 +357,8 @@ fn ensureZigVersion() !void {
}
}

fn ensureTarget(cross: std.zig.CrossTarget) !void {
fn ensureTarget(options: Options) !void {
const cross = options.target;
const target = (std.zig.system.NativeTargetInfo.detect(cross) catch unreachable).target;

const supported = switch (target.os.tag) {
Expand All @@ -348,6 +374,7 @@ fn ensureTarget(cross: std.zig.CrossTarget) !void {
) == .lt) break :blk false;
break :blk true;
},
.emscripten => target.cpu.arch == .wasm32,
else => false,
};
if (!supported) {
Expand Down
1 change: 1 addition & 0 deletions libs/zems/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# zems - emscripten binding helpers and utilities
179 changes: 179 additions & 0 deletions libs/zems/build.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
const std = @import("std");

pub const Package = struct {
module: *std.Build.Module,
emscripten: bool,

pub fn link(pkg: Package, exe: *std.Build.CompileStep) void {
exe.addModule("zems", pkg.module);
}
};

pub fn package(
b: *std.Build,
target: std.zig.CrossTarget,
optimize: std.builtin.Mode,
args: struct {},
) Package {
_ = optimize;
_ = args;
const emscripten = target.getOsTag() == .emscripten;
const src_root = if (emscripten) "zems.zig" else "dummy.zig";
var module = b.createModule(.{
.source_file = .{ .path = b.pathJoin(&.{ thisDir(), src_root }) },
});
return .{
.module = module,
.emscripten = emscripten,
};
}

//
// Build utils
//

pub const EmscriptenStep = struct {
b: *std.Build.Builder,
args: EmscriptenArgs,
out_path: ?[]const u8 = null, // zig-out/web/<exe-name> if unset
lib_exe: ?*std.Build.CompileStep = null,
link_step: ?*std.Build.Step.Run = null,
emsdk_path: []const u8,
emsdk_include_path: []const u8,

pub fn init(b: *std.Build.Builder) *@This() {
const emsdk_path = b.env_map.get("EMSDK") orelse @panic("Failed to get emscripten SDK path, have you installed & sourced the SDK?");
var r = b.allocator.create(EmscriptenStep) catch unreachable;
r.* = .{
.b = b,
.args = EmscriptenArgs.init(b.allocator),
.emsdk_path = emsdk_path,
.emsdk_include_path = b.pathJoin(&.{ emsdk_path, "upstream", "emscripten", "cache", "sysroot", "include" }),
};
return r;
}

pub fn link(self: *@This(), exe: *std.Build.CompileStep) void {
std.debug.assert(self.lib_exe == null);
std.debug.assert(self.link_step == null);
const b = self.b;

exe.addSystemIncludePath(.{ .path = self.emsdk_include_path });
exe.stack_protector = false;
exe.disable_stack_probing = true;
exe.linkLibC();

const emlink = b.addSystemCommand(&.{"emcc"});
emlink.addArtifactArg(exe);
for (exe.link_objects.items) |link_dependency| {
switch (link_dependency) {
.other_step => |o| emlink.addArtifactArg(o),
// .c_source_file => |f| emlink.addFileSourceArg(f.source), // f.args?
// .c_source_files => |fs| for (fs.files) |f| emlink.addArg(f), // fs.flags?
else => {},
}
}
const out_path: []const u8 = self.out_path orelse b.pathJoin(&.{ b.pathFromRoot("."), "zig-out", "web", exe.name });
std.fs.cwd().makePath(out_path) catch unreachable;
const out_file = std.mem.concat(b.allocator, u8, &.{ out_path, std.fs.path.sep_str ++ "index.html" }) catch unreachable;
emlink.addArgs(&.{ "-o", out_file });

if (self.args.exported_functions.items.len > 0) {
var s = std.mem.join(self.b.allocator, "','", self.args.exported_functions.items) catch unreachable;
var ss = std.fmt.allocPrint(self.b.allocator, "-sEXPORTED_FUNCTIONS=['{s}']", .{s}) catch unreachable;
emlink.addArg(ss);
}

var op_it = self.args.options.iterator();
while (op_it.next()) |opt| {
if (opt.value_ptr.*.len > 0) {
emlink.addArg(std.mem.join(b.allocator, "", &.{ "-s", opt.key_ptr.*, "=", opt.value_ptr.* }) catch unreachable);
} else {
emlink.addArg(std.mem.join(b.allocator, "", &.{ "-s", opt.key_ptr.* }) catch unreachable);
}
}

emlink.addArgs(self.args.other_args.items);

if (self.args.shell_file) |sf| emlink.addArgs(&.{ "--shell-file", sf });

emlink.step.dependOn(&exe.step);
self.link_step = emlink;
self.lib_exe = exe;
}
};

pub const EmscriptenArgs = struct {
source_map_base: []const u8 = "./",
shell_file: ?[]const u8 = null,

exported_functions: std.ArrayList([]const u8),
options: std.StringHashMap([]const u8), // in args formated as -sKEY=VALUE
other_args: std.ArrayList([]const u8),

pub fn init(alloc: std.mem.Allocator) @This() {
return .{
.exported_functions = std.ArrayList([]const u8).init(alloc),
.options = std.StringHashMap([]const u8).init(alloc),
.other_args = std.ArrayList([]const u8).init(alloc),
};
}

/// set common args
/// param max_optimize - use maximum optimizations which are much slower to compile
pub fn setDefault(self: *@This(), build_mode: std.builtin.Mode, max_optimizations: bool) void {
//_ = r.options.fetchPut("FILESYSTEM", "0") catch unreachable;
_ = self.options.getOrPutValue("ASYNCIFY", "") catch unreachable;
_ = self.options.getOrPutValue("EXIT_RUNTIME", "0") catch unreachable;
_ = self.options.getOrPutValue("WASM_BIGINT", "") catch unreachable;
_ = self.options.getOrPutValue("MALLOC", "emmalloc") catch unreachable;
_ = self.options.getOrPutValue("ABORTING_MALLOC", "0") catch unreachable;
_ = self.options.getOrPutValue("INITIAL_MEMORY", "64MB") catch unreachable;
_ = self.options.getOrPutValue("ALLOW_MEMORY_GROWTH", "1") catch unreachable;

self.shell_file = thisDir() ++ std.fs.path.sep_str ++ "shell_minimal.html";
self.exported_functions.appendSlice(&.{ "_main", "_malloc", "_free" }) catch unreachable;

self.other_args.append("-fno-rtti") catch unreachable;
self.other_args.append("-fno-exceptions") catch unreachable;
switch (build_mode) {
.Debug => {
self.other_args.append("-g") catch unreachable;
self.other_args.appendSlice(&.{ "--closure", "0" }) catch unreachable;
const source_map_base: []const u8 = "./";
self.other_args.appendSlice(&.{ "-gsource-map", "--source-map-base", source_map_base }) catch unreachable;
},
.ReleaseSmall => {
if (max_optimizations) self.other_args.append("-Oz") catch unreachable else self.other_args.append("-Os") catch unreachable;
},
.ReleaseSafe, .ReleaseFast => {
if (max_optimizations) {
self.other_args.append("-O3") catch unreachable;
self.other_args.append("-flto") catch unreachable;
} else {
self.other_args.append("-O2") catch unreachable;
}
},
}
}

/// sets option argument to specific value if its not set or assert if value differs
pub fn setOrAssertOption(self: *@This(), key: []const u8, value: []const u8) void {
var v = self.options.getOrPut(key) catch unreachable;
if (v.found_existing) {
if (!std.ascii.eqlIgnoreCase(v.value_ptr.*, value)) {
std.debug.panic("Emscripten argument conflict: want `{s}` to be `{s}` but `{s}` was already set", .{ key, value, v.key_ptr.* });
}
} else {
v.value_ptr.* = value;
}
}

pub fn overwriteOption(self: *@This(), key: []const u8, value: []const u8) void {
_ = self.options.fetchPut(key, value);
}
};

inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
2 changes: 2 additions & 0 deletions libs/zems/dummy.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// dummy interface for non emscripten builds
pub const is_emscripten = false;
Loading