CMake continues to prove itself the worst possible build system except for every other one I’ve tried. One of the things that I’ve never quite been satisfied with is handling of non code/object files. It’s obvious all the tools are there somewhere inside cmake to create an asset pipeline, but I always tripped over the details. Some commands create explicit targets, others don’t, and some dependency commands work on explicit targets and other don’t. I get the feeling I’m not the only one judging by the number of starter templates that outsource asset management to shell scripts or traditional make.

There are examples out there that solve this problem, but ether they’re really old, or they do so much that I never quite grokked the core concept. Anyway I think I’ve finally got the basics dialed in. The following snippet transforms .blend files to glb using blender. It only does this if cmake detects the glb file is out of date and it only adds the named meta target to the targets list. There is obviously a lot more that could be added, like detecting blender’s location, etc – but the point of this post is to offer the minimum you (I) can understand and build on.

# The function (put in a cmake header somewhere appropriate)
function(add_models target)
    set(files ${ARGN})

    foreach (src_file ${files})
        set( out_file ${src_file} )
        cmake_path( REPLACE_EXTENSION out_file ".glb" )
        cmake_path(SET src_path "${CMAKE_CURRENT_SOURCE_DIR}/${src_file}")
        cmake_path(SET out_path "${CMAKE_CURRENT_BINARY_DIR}/${out_file}")

        set( python_exp "import bpy\\; bpy.ops.export_scene.gltf\\(filepath=\\'${out_file}\\'\\)\\;" )

        add_custom_command(
                OUTPUT ${out_file}
                DEPENDS ${src_file}

                COMMAND /usr/bin/blender -b ${src_path} --python-expr "${python_exp}"
        )

        list(APPEND out_files ${out_file})
    endforeach ()

    add_custom_target(${target} DEPENDS ${out_files})
endfunction()

# Create the target "models"  (put in a cmake file where your source assets live)
add_models(models
        bulkhead.blend
        floor.blend)

By Rachael

Professional software developer and amateur musician. I play trumpet mainly, with just about any group that will have me.

Leave a Reply

Only people in my network can comment.