aorii/cmake/compile_shaders.cmake
2024-10-16 20:15:25 +08:00

88 lines
4.0 KiB
CMake

function(compile_slang_shaders input_shaders shader_stages)
# Ensure the output directory exists
set(output_dir ${SHADER_OUTPUT_DIR})
file(MAKE_DIRECTORY ${output_dir})
foreach(input_file IN LISTS input_shaders)
# Get the base name for the output file
get_filename_component(filename ${input_file} NAME_WE)
# Initialize a list to hold all the output files for this shader
set(output_files)
# Use a set to track processed stages to avoid duplication
set(processed_stages)
foreach(stage IN LISTS ${shader_stages})
# Check if the stage has already been processed
if(NOT stage IN_LIST processed_stages)
list(APPEND processed_stages ${stage})
# Define the entry point based on the stage
if(stage STREQUAL "vertex")
set(entry_point "vertex_main")
set(profile "vs_5_0")
elseif(stage STREQUAL "pixel")
set(entry_point "pixel_main")
set(profile "ps_5_0")
elseif (stage STREQUAL "comp")
set(entry_point "compute_main")
set(profile "cs_5_0")
else()
message(FATAL_ERROR "Unsupported shader stage: ${stage}")
endif()
# Check and compile for each backend
if(GL_BACKEND)
list(APPEND output_files ${output_dir}/${filename}_${stage}.glsl)
add_custom_command(
OUTPUT ${output_dir}/${filename}_${stage}.glsl
COMMAND slangc -target glsl -entry ${entry_point} -stage ${stage} -o ${output_dir}/${filename}_${stage}.glsl ${input_file}
DEPENDS ${input_file}
COMMENT "Compiling ${input_file} to GLSL (${stage})"
)
endif()
if(DX_BACKEND)
list(APPEND output_files ${output_dir}/${filename}_${stage}.dxbc)
add_custom_command(
OUTPUT ${output_dir}/${filename}_${stage}.dxbc
COMMAND slangc -target dxbc -profile ${profile} -entry ${entry_point} -stage ${stage} -o ${output_dir}/${filename}_${stage}.dxbc ${input_file}
DEPENDS ${input_file}
COMMENT "Compiling ${input_file} to DXBC (${stage})"
)
endif()
if(VK_BACKEND)
list(APPEND output_files ${output_dir}/${filename}_${stage}.spirv)
add_custom_command(
OUTPUT ${output_dir}/${filename}_${stage}.spirv
COMMAND slangc -target spirv -entry ${entry_point} -stage ${stage} -o ${output_dir}/${filename}_${stage}.spirv ${input_file}
DEPENDS ${input_file}
COMMENT "Compiling ${input_file} to SPIR-V (${stage})"
)
endif()
if(METAL_BACKEND)
list(APPEND output_files ${output_dir}/${filename}_${stage}.metal)
add_custom_command(
OUTPUT ${output_dir}/${filename}_${stage}.metal
COMMAND slangc -target msl -entry ${entry_point} -stage ${stage} -o ${output_dir}/${filename}_${stage}.metal ${input_file}
DEPENDS ${input_file}
COMMENT "Compiling ${input_file} to Metal Shading Language (${stage})"
)
endif()
else()
message(WARNING "The stage '${stage}' has already been processed for entry point '${entry_point}'. Skipping duplicate.")
endif()
endforeach()
# Add the custom command outputs to the compile_shader target
add_custom_target(
compile_shader
DEPENDS ${output_files}
)
endforeach()
endfunction()