Skip to content

Instantly share code, notes, and snippets.

@kooparse
Created April 2, 2023 09:56
Show Gist options
  • Save kooparse/c59c9054c6221e10647ddda8c2d427b2 to your computer and use it in GitHub Desktop.
Save kooparse/c59c9054c6221e10647ddda8c2d427b2 to your computer and use it in GitHub Desktop.
This snippet shows you how to make a Library.metallib from all your .metal files
// You could use this snippet generally before compiling your program.
#run {
build_metal_shaders("./path-to-your-shaders-folder");
}
/*
Build all shaders for our metal backend.
In 3 steps:
1) For all .metal files, we create an 'air' file.
2) For all .air files, we pack them into one archive file.
3) Finally, we make a metallib from this archive file.
*/
build_metal_shaders :: (shaders_directory: string) {
print("\n[BUILDING METAL SHADERS]\n\n");
args: [..]string;
metalar_path := join(shaders_directory, "Library.metalar");
array_add(*args, tprint("xcrun -sdk macosx metal-ar r %", metalar_path));
files := file_list(shaders_directory);
// Step 1: making air files.
for files {
if !ends_with(it, ".metal") continue;
path, basename := path_decomp(it);
print("Shader '%' building...\t", basename);
source_file := it;
output_file := tprint("%.air", join(path, basename));
cmd := break_command_into_strings(tprint("xcrun -sdk macosx metal -c -frecord-sources % -o %", source_file, output_file));
result, _, error := run_command(..cmd, capture_and_return_output=true, timeout_ms = 3200);
if result.exit_code != 0 {
error_message := tprint("Shader '%' failed to build. %\n", basename, error);
compiler_report(error_message);
}
array_add(*args, output_file);
print("SUCCESS!\n");
}
// Step 2: making the archive files from all air files.
{
print("\nBuilding Metal archive file...\t");
merged_cmd: string;
for args merged_cmd = join(merged_cmd, it, " ");
cmd := break_command_into_strings(merged_cmd);
result := run_command(..cmd, capture_and_return_output=true, timeout_ms = 3200);
if result.exit_code != 0 {
error_message := tprint("Archive file for Metal shaders failed to build.\n");
compiler_report(error_message);
}
print("SUCCESS!\n");
}
// Step 3: making the metalib file.
{
print("Building Metalib file...\t");
metalar_filepath := join(shaders_directory, "Library.metalar");
metallib_filepath := join(shaders_directory, "Library.metallib");
cmd := tprint("xcrun -sdk macosx metallib % -o %", metalar_filepath, metallib_filepath);
result, _, error := run_command(..break_command_into_strings(cmd), capture_and_return_output=true, timeout_ms = 3200);
if result.exit_code != 0 {
error_message := tprint("Metallib file failed to build. % \n", error);
compiler_report(error_message);
}
print("SUCCESS!\n");
}
print("\nAll shaders have been built!\n\n\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment