Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit c9425892e8c81c55e636179e2af6ad6795c66f14
Author: sentomk <sentomk@proton.me>
Date:   Sat,  3 Oct 2026 21:52:03 +0800

wip: add self-hosting build script skeleton

Diffstat:
A.clang-format | 1+
A.clangd | 2++
Akumo_builder.cpp | 216+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 219 insertions(+), 0 deletions(-)

diff --git a/.clang-format b/.clang-format @@ -0,0 +1 @@ +BasedOnStyle: Google diff --git a/.clangd b/.clangd @@ -0,0 +1,2 @@ +CompileFlags: + Add: [-std=c++20] diff --git a/kumo_builder.cpp b/kumo_builder.cpp @@ -0,0 +1,216 @@ +/// @file kumo_builder.cpp +/// @brief The Kumo builder: the build script is itself a C++ program. +/// +/// @code +/// clang++ -std=c++20 kumo_builder.cpp -o kumoko +/// @endcode +/// +/// Usage (always from the project root): +/// @code +/// ./kumoko # incremental build +/// ./kumoko run # incremental build, then run the executable +/// ./kumoko clean # delete all build output +/// @endcode +/// +/// @note There is no need to bootstrap again after editing this file: on the +/// next run the builder notices it is out of date and recompiles itself. + +#include <spawn.h> +#include <sys/wait.h> + +#include <cstdio> +#include <cstdlib> +#include <filesystem> +#include <fstream> +#include <string> +#include <vector> + +/// @brief The environment of the current process, provided by libc. +/// +/// Passed unchanged to every child process. +extern char** environ; + +namespace fs = std::filesystem; + +using Cmd = std::vector<std::string>; + +/// @name Configuration +/// Every build setting of the project lives here. +/// @{ + +static const char* const CXX = "clang++"; +static const fs::path SELF_SRC = "kumo_builder.cpp"; +static const fs::path SRC_DIR = "src"; + +/// @brief Output root. +/// +/// Layout: +/// @code +/// build/obj/src/foo/bar.cpp.o object file (mirrors the source tree) +/// build/obj/src/foo/bar.cpp.d list of headers that file depends on +/// build/kumo final executable +/// @endcode +static const fs::path OUT_DIR = "build"; +static const fs::path EXE = OUT_DIR / "kumo"; + +/// @brief Flags passed to every compile command. +static const Cmd CXX_FLAGS = { + "-std=c++20", "-g", "-O0", "-Wall", "-Wextra", + "-fno-exceptions", "-fno-rtti", + "-Isrc", // allows includes relative to src/, e.g. #include "core/math.h" +}; + +/// @brief Flags passed to the link command. +static const Cmd LINK_FLAGS = { + "-framework", "Cocoa", "-framework", "Metal", "-framework", "QuartzCore", +}; + +/// @} + +/// @name Processes +/// Spawning children and limiting how many run at once. +/// @{ + +/// @brief Start a child process without waiting for it. +/// +/// Exits the builder if the process cannot be started. +/// +/// @param cmd Command to run; `cmd[0]` is looked up in `PATH`. +/// @return Process id of the child. +static pid_t spawn(const Cmd& cmd) { + // posix_spawnp wants a C-style argv: an array of char* ending in nullptr. + std::vector<char*> argv; + + for (const std::string& arg : cmd) { + argv.push_back(const_cast<char*>(arg.c_str())); + } + argv.push_back(nullptr); + + // The trailing "p" means the program is looked up in PATH, so "clang++" + // does not have to be an absolute path. + pid_t pid = 0; + if (posix_spawnp(&pid, argv[0], nullptr, nullptr, argv.data(), environ) != + 0) { + std::fprintf(stderr, "failed to spawn %s\n", argv[0]); + std::exit(EXIT_FAILURE); + } + return pid; +} + +/// @brief Blocks until any one child process exits. +/// +/// @return `true` if that child exited normally with status 0. +static bool wait_one() { + int status = 0; + waitpid(-1, &status, 0); // -1 means "any child" + return WIFEXITED(status) && WEXITSTATUS(status) == 0; +} + +/// @brief Runs a batch of commands with bounded parallelism. +/// +/// No threads are needed: the parallelism comes from the child processes, and +/// this is just a scheduling loop. Each iteration does one of two things: +/// - commands remain and we are below the limit: start one more; +/// - otherwise: wait for one to finish. +/// +/// After the first failure no new commands are started, but the ones already +/// running are still waited for so that no orphan processes are left behind. +/// +/// @param cmds Commands to run, started in order. +/// @param max_jobs Maximum number of commands running at the same time. +/// @return `true` only if every command succeeded. +static bool run_all(const std::vector<Cmd>& cmds, unsigned max_jobs) { + size_t next = 0; // index of the next command to start + unsigned running = 0; // number of children currently running + bool ok = true; + while ((ok && next < cmds.size()) || running > 0) { + if (ok && next < cmds.size() && running < max_jobs) { + spawn(cmds[next++]); + running++; + } else { + if (!wait_one()) ok = false; + running--; + } + } + return ok; +} + +/// @brief Runs a single command and waits for it. +/// +/// @param cmd Command to run. +/// @return `true` if the command succeeded. +static bool run(const Cmd& cmd) { return run_all({cmd}, 1); } + +/// @} + +/// @name Incremental compilation +/// Deciding whether a source file must be recompiled. +/// @{ + +/// @brief Reads a dependency file written by the compiler's `-MD` flag. +/// +/// The file uses Makefile syntax: `obj: dep dep dep`, where a backslash at the +/// end of a line continues the list on the next line. Only three rules matter: +/// - the dependency list starts after the first `": "`; +/// - dependencies are separated by whitespace or a line continuation; +/// - a space inside a path is escaped with a backslash. +/// +/// @param path Path of the `.d` file. +/// @return Every dependency listed in the file; empty if it cannot be parsed. +static std::vector<fs::path> read_depfile(const fs::path& path) { + // Read the whole file into one string. + std::ifstream file(path); + std::stringstream buffer; + buffer << file.rdbuf(); + std::string text = buffer.str(); + + std::vector<fs::path> deps; + size_t i = text.find(": "); + if (i == std::string::npos) return deps; + + std::string token; // the path currently being accumulated + // The loop deliberately runs one step past the end (i == size) and treats + // end-of file as a newline, so the last path is flushed as well. + for (i += 2; i <= text.size(); ++i) { + char c = i < text.size() ? text[i] : '\n'; + if (c == '\\' && i + 1 < text.size() && text[i + 1] == ' ') { + // An escaped space that belongs to the current path. + token += ' '; + ++i; + } else if (c == '\\' || c == ' ' || c == '\n' || c == '\r') { + // A separator: the current path ends here. + if (!token.empty()) deps.push_back(token); + token.clear(); + } else { + token += c; + } + } + return deps; +} + +/// @brief Tells whether an object file is out of date. +/// +/// Any one of these is enough: +/// -# @p obj or @p dep is missing (never built, or cleaned); +/// -# the builder is newer than @p obj (compile flags live in this file, so a +/// rebuilt builder may mean changed flags); +/// -# some dependency (the source itself or a header it includes) is newer +/// than @p obj, or has been deleted. +/// +/// @param obj Path of the object file. +/// @param dep Path of the dependency file written alongside it. +/// @param self_time Modification time of the builder binary. +/// @return `true` if the source must be recompiled. +static bool needs_compile(const fs::path& obj, const fs::path& dep, fs::file_time_type self_time) { + if (!fs::exists(obj) || !fs::exists(dep)) return true; + + fs::file_time_type obj_time = fs::last_write_time(obj); + if (self_time > obj_time) return true; + + for (const fs::path& d : read_depfile(dep)) { + if (!fs::exists(d) || fs::last_write_time(d) > obj_time) return true; + } + return false; +} + +/// @}