singe/cmake/shaderHeader.cmake

38 lines
2.3 KiB
CMake

# Compiles src/shaders/scene.hlsl into a C header of SPIR-V, DXIL and MSL blobs with
# SDL_shadercross. Run by the build as
# cmake -DSHADERCROSS=<tool> -DSOURCE=<scene.hlsl> -DOUTPUT=<sceneShaders.h> -P shaderHeader.cmake
# so the header is generated into the build tree like the icon and the other embedded files.
set(entries vertexStatic:vertex vertexSkinned:vertex fragmentMain:fragment depthMain:fragment)
set(formats SPIRV DXIL MSL)
get_filename_component(sourceDir ${SOURCE} DIRECTORY)
get_filename_component(outputDir ${OUTPUT} DIRECTORY)
set(work ${outputDir}/work)
file(MAKE_DIRECTORY ${work})
set(header "// Generated from scene.hlsl by cmake/shaderHeader.cmake with SDL_shadercross; do not edit.\n")
string(APPEND header "// SPIR-V for Vulkan, DXIL for Direct3D 12, MSL for Metal, one set per entry point.\n\n")
string(APPEND header "#ifndef SCENE_SHADERS_H\n#define SCENE_SHADERS_H\n\n#include <stddef.h>\n\n")
string(APPEND header "typedef struct SceneShaderS {\n\tconst char *entryPoint;\n\tconst unsigned char *spirv;\n\tsize_t spirvSize;\n\tconst unsigned char *dxil;\n\tsize_t dxilSize;\n\tconst unsigned char *msl;\n\tsize_t mslSize;\n} SceneShaderT;\n\n")
foreach(entry IN LISTS entries)
string(REPLACE ":" ";" parts ${entry})
list(GET parts 0 name)
list(GET parts 1 stage)
foreach(format IN LISTS formats)
string(TOLOWER ${format} extension)
set(blob ${work}/${name}.${extension})
execute_process(COMMAND ${SHADERCROSS} ${SOURCE} -s HLSL -d ${format} -t ${stage} -e ${name} -o ${blob} RESULT_VARIABLE code OUTPUT_VARIABLE out ERROR_VARIABLE err)
if(NOT code EQUAL 0)
message(FATAL_ERROR "Shader ${name} (${format}) failed to compile:\n${out}\n${err}")
endif()
file(READ ${blob} hex HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," bytes "${hex}")
string(APPEND header "static const unsigned char _${name}${format}[] = {\n\t${bytes}\n};\n\n")
endforeach()
string(SUBSTRING ${name} 0 1 initial)
string(SUBSTRING ${name} 1 -1 rest)
string(TOUPPER ${initial} initial)
string(APPEND header "static const SceneShaderT sceneShader${initial}${rest} = { \"${name}\", _${name}SPIRV, sizeof(_${name}SPIRV), _${name}DXIL, sizeof(_${name}DXIL), _${name}MSL, sizeof(_${name}MSL) };\n\n")
endforeach()
string(APPEND header "#endif\n")
file(WRITE ${OUTPUT} "${header}")