Backlog/buildgen/generateEmbeddedShaders.zig

83 lines
2.9 KiB
Zig

const std = @import("std");
// this file creates auto generated static resource installers for
// embedded shaders.
//
// when building with -Dstatic_build shaders are instead not loaded from the file system
// but instead embedded into the binary
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
// Get output filename from build system
const args = try std.process.argsAlloc(allocator);
if (args.len < 3) @panic("Missing output filename");
const out_path = args[1];
// Generate a startup module function that invokes
// startup module for each zig function
// and generates an api
var writer = std.ArrayList(u8){};
// const content_path = args[2];
// std.debug.print("content path: {s}\n", .{content_path});
// check the content directory and search for all _spv files
var dir = try std.fs.cwd().openDir("content/_shaders", .{ .iterate = true });
defer dir.close();
_ = try writer.appendSlice(allocator,
\\ pub const core = @import("core").module;
\\
\\ pub fn installStaticResources() !void {
\\
);
var shaderFileEmbeds = std.ArrayList([]const u8){};
var walker = dir.iterate();
while (try walker.next()) |shaderType| {
// std.debug.print("Walk: {s}\n", .{shaderType.name});
if (shaderType.kind == .directory) {
var d2 = try dir.openDir(shaderType.name, .{ .iterate = true });
defer d2.close();
var w2 = d2.iterate();
while (try w2.next()) |shaderName| {
const shaderPath = try std.fmt.allocPrint(allocator, "_shaders/{s}/{s}", .{ shaderType.name, shaderName.name });
// std.debug.print("mounted path: {s} => {s}\n", .{ shaderPath, shaderName.name });
try writer.print(
allocator,
"{{ const embedded align(8) = @embedFile(\"{s}\").*;\n_ = try core.fs().installFileBytesMount(\"{s}\", @constCast(&embedded), true);}}\n",
.{ shaderName.name, shaderPath },
);
try shaderFileEmbeds.append(allocator, shaderName.name);
}
}
}
_ = try writer.appendSlice(allocator,
\\ }
);
try writer.print(allocator, "const std = @import(\"std\");", .{});
// Write to specified output file
// Open or create the file for writing (overwrites if it exists)
const file = try std.fs.cwd().createFile(out_path, .{});
defer file.close();
try writer.append(allocator, 0);
var ast = try std.zig.Ast.parse(allocator, @as([:0]const u8, @ptrCast(writer.items[0 .. writer.items.len - 1])), .zig);
// std.debug.print("output=\n{s}", .{content.items[0 .. content.items.len - 1]});
defer ast.deinit(allocator);
const out = try ast.renderAlloc(allocator);
// Write the content to the file
try file.writeAll(out);
}