diff --git a/specs/c-abi/optiona.md b/specs/c-abi/optiona.md new file mode 100644 index 0000000..f2b67b7 --- /dev/null +++ b/specs/c-abi/optiona.md @@ -0,0 +1,275 @@ +# Option A: Compile Time Sampler Selection + +Detail for Option A of the [C ABI specification](spec.md). This design exposes +the generic C API defined in the specification, with the sampler +implementation chosen once, when the implementation is compiled. One sampler +exists per build. + +The implementation lives in `oqmc_c.h` itself, after the declarations, behind +an `OQMC_IMPLEMENTATION` guard. OpenQMC compiles it into `liboqmc` and +distributes that. An integrator who prefers to can compile it into their own +build instead; see *Opt-in self compilation* under *Building*. + +Note that the illustrative code below needs correction before use; it has not +been compiled. + +## Selection + +The implementation is a single translation unit. A preprocessor definition +selects the sampler it wraps; with no definition it defaults to PmjBn, the +recommended sampler. Each branch is three lines: an include, an alias, and a +name. The chain sits inside the implementation region of the header: + +```cpp +#ifdef OQMC_IMPLEMENTATION +#ifndef __cplusplus +#error "OQMC_IMPLEMENTATION must be compiled as C++17." +#endif + +#if defined(OQMC_CABI_SAMPLER_PMJ) + #include +using Sampler = oqmc::PmjSampler; +constexpr const char* samplerName = "pmj"; +#elif defined(OQMC_CABI_SAMPLER_SOBOL) + #include +using Sampler = oqmc::SobolSampler; +constexpr const char* samplerName = "sobol"; +// Remaining samplers follow the same pattern. +#else + #include +using Sampler = oqmc::PmjBnSampler; +constexpr const char* samplerName = "pmjbn"; +#endif + +// ... implementation, below ... + +#endif // OQMC_IMPLEMENTATION +``` + +Because only the selected header is included, only that sampler's +implementation and data tables are compiled and linked. A build wrapping +Sobol carries no blue noise tables. + +The include guard of `oqmc_c.h` covers the declarations only. The +implementation region is guarded by `OQMC_IMPLEMENTATION` alone, so the header +can be included for declarations in any number of files and for the +implementation in exactly one. Included without the define it is a pure C11 +header. + +## Implementation + +The marshalling between the opaque value and the C++ type is written once, +against the `Sampler` alias. Copies go through `memcpy`, which the compiler +removes for small trivially copyable types, and two static assertions make an +oversized or non-trivial sampler a compile error. + +```cpp +static_assert(sizeof(Sampler) <= sizeof(oqmc_sampler), + "Sampler must fit within the value storage."); +static_assert(std::is_trivially_copyable::value, + "Sampler must be trivially copyable."); + +static Sampler load(const oqmc_sampler* sampler) +{ + Sampler out; + std::memcpy(&out, sampler, sizeof(out)); + + return out; +} + +static oqmc_sampler store(const Sampler& sampler) +{ + oqmc_sampler out{}; + std::memcpy(&out, &sampler, sizeof(sampler)); + + return out; +} + +template +static void draw(const Sampler& sampler, int size, T* out) +{ + switch(size) + { + case 1: sampler.template drawSample<1>(out); break; + case 2: sampler.template drawSample<2>(out); break; + case 3: sampler.template drawSample<3>(out); break; + case 4: sampler.template drawSample<4>(out); break; + default: assert(size >= 1 && size <= 4); break; + } +} +``` + +The entry points are then direct, one line each. Definitions carry the same +`OQMC_API` linkage macro as their declarations (see *Linkage*): + +```cpp +extern "C" +{ + +OQMC_API const char* oqmc_sampler_name(void) +{ + return samplerName; +} + +OQMC_API size_t oqmc_sampler_cache_size(void) +{ + return Sampler::cacheSize; +} + +OQMC_API void oqmc_sampler_initialise_cache(void* cache) +{ + Sampler::initialiseCache(cache); +} + +OQMC_API oqmc_sampler oqmc_sampler_create(int x, int y, int frame, int index, + const void* cache) +{ + return store(Sampler(x, y, frame, index, cache)); +} + +OQMC_API oqmc_sampler oqmc_sampler_new_domain(const oqmc_sampler* sampler, + int key) +{ + return store(load(sampler).newDomain(key)); +} + +OQMC_API void oqmc_sampler_draw_sample_f(const oqmc_sampler* sampler, int size, + float* sample) +{ + draw(load(sampler), size, sample); +} + +// Remaining functions follow the same pattern. + +} // extern "C" +``` + +## Linkage + +Every declaration and definition carries `OQMC_API`, defined at the top of +the header: + +```c +#ifndef OQMC_API +# ifdef OQMC_STATIC +# define OQMC_API static +# else +# define OQMC_API extern +# endif +#endif +``` + +The default, `extern`, is what `liboqmc` needs: symbols are exported so +consumers can link against it. Defining `OQMC_STATIC` before including the +header gives every function internal linkage instead. That exists for the +opt-in case: if two plugins loaded into one host process each compile the +implementation with different samplers, both export `oqmc_sampler_create`, +and on Linux the dynamic linker binds every call in the process to whichever +loaded first, so the second plugin silently runs the first plugin's sampler. +With `OQMC_STATIC` the two copies are invisible to each other. Because the +default is wrapped in `#ifndef`, an integrator may also define `OQMC_API` to +something else, such as a DLL export attribute, without editing the header. + +## Building + +`src/oqmc_impl.cpp` is two lines: + +```cpp +#define OQMC_IMPLEMENTATION +#include +``` + +Under CMake, a cache variable selects the sampler and maps to the compile +definition on that translation unit: + +```cmake +set(OPENQMC_CABI_SAMPLER "pmjbn" CACHE STRING + "Sampler implementation wrapped by the C ABI library.") +``` + +This produces `liboqmc`, which OpenQMC distributes. Consumers link it with a +C toolchain. Once the `stochastic.h` allocation moves to `malloc` (see +*Runtime Dependencies* in the specification), the link step needs no C++ +runtime. + +### Opt-in self compilation + +An integrator who would rather not depend on an installed `liboqmc` writes +the same two lines in their own project and compiles them as C++17, choosing +the sampler themselves: + +```sh +c++ -std=c++17 -O2 -I include -DOQMC_CABI_SAMPLER_SOBOL -c oqmc_impl.cpp +cc main.c oqmc_impl.o -o main +``` + +Nothing from OpenQMC's build system is involved, the sampler is chosen per +binary, and the translation unit cross compiles with whatever builds the rest +of the project. A plugin taking this route should also define `OQMC_STATIC`, +per *Linkage*. The integrator's build needs a C++17 compiler for this one +file; consumers with no C++ toolchain link the distributed `liboqmc`. + +## Contributor Workflow + +Adding a new sampler requires the existing C++ header, plus one branch in the +selection chain: + +```cpp +#elif defined(OQMC_CABI_SAMPLER_MY) + #include +using Sampler = oqmc::MySampler; +constexpr const char* samplerName = "my"; +``` + +The public header does not change. + +## Usage Example + +```c +#include + +#include + +int main(void) +{ + void* cache = malloc(oqmc_sampler_cache_size()); + oqmc_sampler_initialise_cache(cache); + + const oqmc_sampler pixel = oqmc_sampler_create(x, y, frame, index, cache); + const oqmc_sampler camera = oqmc_sampler_new_domain(&pixel, 0); + + float sample[2]; + oqmc_sampler_draw_sample_f(&camera, 2, sample); + + free(cache); + return 0; +} +``` + +An application that depends on a particular sampler can verify the build it +linked against with `oqmc_sampler_name()`, since the choice is otherwise +invisible in the ABI. + +## Testing + +In addition to the common tests in the specification: + +- CI builds the library once per sampler definition, so every branch of the + selection chain keeps compiling, and runs the equivalence tests against + each build. + +## Key Properties + +- **Simplest possible implementation** — one translation unit, no dispatch, + no global state, no macros beyond the selection chain. +- **Direct calls** — no indirection anywhere. +- **Minimal binary** — only the selected sampler's code and data tables are + linked. +- **Fixed public header** — spelled out declarations with Doxygen comments; + adding a sampler never changes it. +- **Self compilable** — the implementation is in the header, so an integrator + can compile it with a single compiler command, no build system required. +- **The trade** — changing sampler requires recompiling one translation unit, + and a prebuilt package bakes the choice in for all of its consumers. + Integrators who need a different choice compile the implementation + themselves. diff --git a/specs/c-abi/optionb.md b/specs/c-abi/optionb.md new file mode 100644 index 0000000..120120e --- /dev/null +++ b/specs/c-abi/optionb.md @@ -0,0 +1,250 @@ +# Option B: Runtime Sampler Selection + +**Status: future extension, not part of the initial implementation.** Option +A is being implemented first. This document is retained because Option B is a +strict superset of Option A's API, and decisions made in Option A must keep it +possible to add later without breaking the ABI. + +Detail for Option B of the [C ABI specification](spec.md). This design exposes +the generic C API defined in the specification, with all samplers compiled +into the library and one selected at startup, defaulting to PmjBn if no +selection is made. Every call dispatches through a single global pointer to a +table of function pointers held in read-only data. + +Note that the illustrative code below needs correction before use; it has not +been compiled. + +## Selection API + +The public header adds one enumeration and one function to the generic API. + +```c +/// Sampler implementation. +typedef enum oqmc_sampler_type +{ + OQMC_SAMPLER_TYPE_PMJ, ///< Low discrepancy pmj sequence. + OQMC_SAMPLER_TYPE_PMJBN, ///< Blue noise pmj variant. + OQMC_SAMPLER_TYPE_SOBOL, ///< Owen scrambled Sobol sequence. + OQMC_SAMPLER_TYPE_SOBOLBN, ///< Blue noise Sobol variant. + OQMC_SAMPLER_TYPE_LATTICE, ///< Rank one lattice sequence. + OQMC_SAMPLER_TYPE_LATTICEBN, ///< Blue noise lattice variant. +} oqmc_sampler_type; + +/// Select the sampler implementation for this process. +/// +/// Optional; the default is pmjbn. Call at most once, at startup, before any +/// other API function and before starting any thread that uses the API. +/// Calling it later is undefined. +/// +/// @param [in] type Implementation to select. +/// @return Zero on success, non-zero if the type is invalid. +int oqmc_sampler_select(oqmc_sampler_type type); +``` + +The enumerator values are the indices into the internal registry, so +reordering either is an ABI break; new samplers are appended. A consumer +selecting by name, from a command line or a configuration file, maps the +string to an enumerator itself; `oqmc_sampler_select` validates the result +either way. + +**Selection is a startup operation**: sampler values carry no type +information, so changing the implementation while values are live would +reinterpret them under a different layout, and a select after other API use +is therefore undefined. This is a precondition in the same style as the rest +of the library, not something the implementation detects. Components sharing +one central library, such as plugins in a host process, must agree on the +sampler, which `oqmc_sampler_name` can check. One sampler per process is a +permanent commitment of this design. + +## Implementation + +Templates generate the per-sampler code. A `Vtable` holds one slot per API +function, a `Thunks` template translates between the opaque value and a +concrete C++ sampler, and a `constexpr` registry maps enumerators to tables. +Two static assertions per sampler make an oversized or non-trivial sampler a +compile error. + +```cpp +struct Vtable +{ + const char* name; + size_t cacheSize; + void (*initialiseCache)(void* cache); + void (*create)(int x, int y, int frame, int index, const void* cache, + oqmc_sampler* out); + void (*newDomain)(const oqmc_sampler* self, int key, oqmc_sampler* out); + // One slot per remaining API function. +}; + +template struct Thunks +{ + static_assert(sizeof(Sampler) <= sizeof(oqmc_sampler), + "Sampler must fit within the value storage."); + static_assert(std::is_trivially_copyable::value, + "Sampler must be trivially copyable."); + + static Sampler load(const oqmc_sampler* sampler) + { + Sampler out; + std::memcpy(&out, sampler, sizeof(out)); + + return out; + } + + static void store(oqmc_sampler* out, const Sampler& sampler) + { + std::memcpy(out, &sampler, sizeof(sampler)); + } + + static void newDomain(const oqmc_sampler* self, int key, oqmc_sampler* out) + { + store(out, load(self).newDomain(key)); + } + + template + static void draw(const Sampler& sampler, int size, T* out) + { + switch(size) + { + case 1: sampler.template drawSample<1>(out); break; + case 2: sampler.template drawSample<2>(out); break; + case 3: sampler.template drawSample<3>(out); break; + case 4: sampler.template drawSample<4>(out); break; + default: assert(size >= 1 && size <= 4); break; + } + } + + // Remaining members follow the same pattern. +}; +``` + +The registry is a compile time constant, so the tables live in read-only data +with no runtime initialisation, and a static assertion keeps it aligned with +the public enumeration: + +```cpp +template constexpr Vtable makeVtable(const char* name) +{ + return Vtable{name, + Sampler::cacheSize, + &Thunks::initialiseCache, + &Thunks::create, + &Thunks::newDomain, + // Remaining slots follow the same pattern. + }; +} + +constexpr Vtable registry[] = { + makeVtable("pmj"), + makeVtable("pmjbn"), + makeVtable("sobol"), + makeVtable("sobolbn"), + makeVtable("lattice"), + makeVtable("latticebn"), +}; + +constexpr int registryCount = int(std::size(registry)); +static_assert(registryCount == OQMC_SAMPLER_TYPE_LATTICEBN + 1, + "Registry and enumeration must match."); +``` + +The selection is one pointer, statically initialised to the default table. +It is written at most once, at startup, and only read after that, so there is +no data race and a plain pointer is sufficient. Every call pays one load and +an indirect call. + +```cpp +const Vtable* active = ®istry[OQMC_SAMPLER_TYPE_PMJBN]; + +int oqmc_sampler_select(oqmc_sampler_type type) +{ + if(type < 0 || type >= registryCount) + { + return 1; + } + + active = ®istry[type]; + + return 0; +} +``` + +Every entry point then follows one shape: + +```cpp +oqmc_sampler oqmc_sampler_new_domain(const oqmc_sampler* sampler, int key) +{ + oqmc_sampler out{}; + active->newDomain(sampler, key, &out); + + return out; +} +``` + +## Contributor Workflow + +Adding a new sampler requires the existing C++ header, plus two appended +lines: an enumerator in `oqmc_c.h` and a registry entry in the implementation region of `oqmc_c.h`. + +```cpp +makeVtable("my"), +``` + +The static assertion ties the two together, so forgetting one of them is a +compile error rather than a drift. + +## Usage Example + +```c +#include + +#include + +int main(void) +{ + /* Override the pmjbn default for this process. */ + if(oqmc_sampler_select(OQMC_SAMPLER_TYPE_SOBOL) != 0) + { + return 1; + } + + void* cache = malloc(oqmc_sampler_cache_size()); + oqmc_sampler_initialise_cache(cache); + + const oqmc_sampler pixel = oqmc_sampler_create(x, y, frame, index, cache); + const oqmc_sampler camera = oqmc_sampler_new_domain(&pixel, 0); + + float sample[2]; + oqmc_sampler_draw_sample_f(&camera, 2, sample); + + free(cache); + return 0; +} +``` + +## Testing + +In addition to the common tests in the specification: + +- **Selection** — an invalid type is rejected; with no select call the API + draws values matching the C++ PmjBn sampler; after a select it matches the + selected sampler. +- Because selection happens once per process, equivalence tests covering + more than one sampler must run each sampler in its own process, for + example by invoking the test binary once per sampler name. + +## Key Properties + +- **One prebuilt binary** — a single package serves every consumer, with the + sampler chosen from configuration at startup, no rebuild. +- **Same value type as Option A** — 16 bytes, register return; the type + information lives in one global rather than in every value. +- **Works with zero configuration** — with no select call the library is the + recommended pmjbn sampler; select exists to override it at startup. +- **Dispatch within noise** — one load and an indirect call, measured + indistinguishable from direct calls at the library boundary. +- **Two edit sites per new sampler** — one enumerator, one registry entry, + tied together by a static assertion. +- **The trade** — every build links all samplers and their data tables, one + process-wide global exists, and one sampler per process is a permanent + commitment. diff --git a/specs/c-abi/spec.md b/specs/c-abi/spec.md new file mode 100644 index 0000000..4cb9986 --- /dev/null +++ b/specs/c-abi/spec.md @@ -0,0 +1,335 @@ +# OQMC Sampler C ABI Specification + +## Goal + +Provide a stable C ABI for the OpenQMC sampler library that: + +1. Preserves header-only, fully-inlined C++ usage for HPC. +2. Exposes a clean C API for cross-language FFI. +3. Minimises contributor boilerplate. +4. Supports easy sampler selection. + +Two designs are described. Both expose the **same generic C API**, defined +below; they differ only in when the sampler implementation is selected. +Option A selects when the implementation is compiled and is the plan. Option B +selects once at startup and is a possible future extension; it is a strict +superset of Option A's API and is documented so that decisions made now keep +it possible. Full detail lives in [optiona.md](optiona.md) and +[optionb.md](optionb.md). + +## Prerequisites + +The C++14 to C++17 migration and the removal of the `OPENQMC_ENABLE_BINARY` +CMake option are complete. This spec introduces a new `OPENQMC_ENABLE_C_ABI` +CMake option for the C ABI library build. + +## Design Constraints + +Both designs share these constraints. + +- **Samplers are small value types** (8 or 16 bytes), trivially copyable, and + frequently copied in HPC hot paths. The C wrapper must store the sampler + **by value** (no heap allocation) so copies remain cheap. +- **Each sampler has a static `cacheSize`** and `initialiseCache()`. The cache + is allocated externally, owned by the caller, and passed into the + constructor. +- **The C API wraps the real `SamplerInterface`**: the parametrised + constructor, the four domain derivation functions, and the draw functions + templated on size with `uint32_t` and `float` outputs. +- **C++17** minimum standard for the implementation, **C11** for the public + header. +- **CPU only**: the C ABI carries no GPU annotations. + +## Existing Samplers + +| Header | Impl Type | C++ Alias | Size (bytes) | Alignment | +|----------------|-----------------|--------------------|--------------|-----------| +| `pmj.h` | `PmjImpl` | `PmjSampler` | 16 | 8 | +| `pmjbn.h` | `PmjBnImpl` | `PmjBnSampler` | 16 | 8 | +| `sobol.h` | `SobolImpl` | `SobolSampler` | 8 | 4 | +| `sobolbn.h` | `SobolBnImpl` | `SobolBnSampler` | 16 | 8 | +| `lattice.h` | `LatticeImpl` | `LatticeSampler` | 8 | 4 | +| `latticebn.h` | `LatticeBnImpl` | `LatticeBnSampler` | 16 | 8 | + +Samplers without a cache pointer (Sobol, Lattice) are 8 bytes. Samplers with a +cache pointer (Pmj, and all blue noise variants) are 16 bytes. + +## Naming Conventions + +| Domain | Convention | Example | +|------------------|-------------------------------------|---------------------------------------| +| C++ types | `UpperCamelCase` | `PmjBnSampler` | +| C++ member funcs | `lowerCamelCase` | `drawSample()`, `cacheSize` | +| C structs/funcs | `lower_snake_case` + `oqmc_` prefix | `oqmc_sampler`, `oqmc_sampler_create` | +| Macros | `ALL_CAPS` + `OQMC_` prefix | `OQMC_CABI_SAMPLER_PMJBN` | + +## File Structure + +Both options use the same files. The existing per-sampler headers remain +unchanged and remain the primary interface for C++ users. + +| File | Purpose | +|-------------------------------|---------------------------------------------| +| `include/oqmc/*.h` (existing) | C++ header-only library, unchanged | +| `include/oqmc/oqmc_c.h` (new) | C11 declarations, then the C++17 implementation behind `OQMC_IMPLEMENTATION` | +| `src/oqmc_impl.cpp` (new) | Two lines: defines `OQMC_IMPLEMENTATION` and includes the header | + +Included normally, `oqmc_c.h` is a pure C11 header. Included with +`OQMC_IMPLEMENTATION` defined, in exactly one C++17 translation unit, it also +emits the implementation. `src/oqmc_impl.cpp` is that translation unit for the +`liboqmc` build, and an integrator who wants to compile the implementation +themselves writes the same two lines in their own project. + +## The C API + +One opaque value type and one set of symbols, identical under both options. + +```c +/// Sampler value. +/// +/// A trivially copyable value type. Copy it by assignment, pass it by +/// pointer, store it in arrays. There is no destroy function; a sampler owns +/// no resources. +typedef struct oqmc_sampler +{ + uint64_t storage[2]; +} oqmc_sampler; +``` + +Storage is **16 bytes**, the size of the largest sampler. Declaring it as an +array of `uint64_t` gives 8 byte alignment without ``; the size is +a multiple of the alignment, so every element of an array is itself aligned, +and 16 divides a cache line. A 16 byte struct is returned in two registers +under the System V AMD64 and AArch64 conventions (Windows x64 returns any +struct over 8 bytes through a hidden pointer regardless). + +There is deliberately no growth headroom. A sampler larger than 16 bytes is an +ABI break, but the library's own design doctrine (see *Passing and packing +samplers* in `sampler.h`) already commits to samplers of at most 16 bytes, and +a static assertion in the implementation makes an oversized sampler a compile +error. Reserving space would give up register return to hold bytes the C++ +library has promised never to need. + +### Functions + +Samplers are taken by pointer and returned by value. Self assignment is safe, +so a caller may walk a chain with `s = oqmc_sampler_new_domain(&s, key)`. The +`size` parameter of the draw functions is the number of dimensions, valid +range 1 to 4, and the caller provides an output array of at least `size` +elements. The ranged integer overloads of the C++ API can be added later. + +| Symbol | Signature | +|---|---| +| `oqmc_sampler_name` | `const char* oqmc_sampler_name(void)` | +| `oqmc_sampler_cache_size` | `size_t oqmc_sampler_cache_size(void)` | +| `oqmc_sampler_initialise_cache` | `void oqmc_sampler_initialise_cache(void* cache)` | +| `oqmc_sampler_create` | `oqmc_sampler oqmc_sampler_create(int x, int y, int frame, int index, const void* cache)` | +| `oqmc_sampler_new_domain` | `oqmc_sampler oqmc_sampler_new_domain(const oqmc_sampler* sampler, int key)` | +| `oqmc_sampler_new_domain_split` | `oqmc_sampler oqmc_sampler_new_domain_split(const oqmc_sampler* sampler, int key, int size, int index)` | +| `oqmc_sampler_new_domain_distrib` | `oqmc_sampler oqmc_sampler_new_domain_distrib(const oqmc_sampler* sampler, int key, int index)` | +| `oqmc_sampler_new_domain_chain` | `oqmc_sampler oqmc_sampler_new_domain_chain(const oqmc_sampler* sampler, int key, int index)` | +| `oqmc_sampler_draw_sample_u` | `void oqmc_sampler_draw_sample_u(const oqmc_sampler* sampler, int size, uint32_t* sample)` | +| `oqmc_sampler_draw_sample_f` | `void oqmc_sampler_draw_sample_f(const oqmc_sampler* sampler, int size, float* sample)` | +| `oqmc_sampler_draw_rnd_u` | `void oqmc_sampler_draw_rnd_u(const oqmc_sampler* sampler, int size, uint32_t* rnd)` | +| `oqmc_sampler_draw_rnd_f` | `void oqmc_sampler_draw_rnd_f(const oqmc_sampler* sampler, int size, float* rnd)` | + +`oqmc_sampler_name` returns the name of the implementation behind the API, +which Option A fixes at compile time and Option B at select time, so an +application can verify it is running the sampler it expects. + +### Guarantees + +These are the properties a foreign-language binding may rely on. Static +assertions in the implementation enforce them. + +- `sizeof(oqmc_sampler) == 16` and `alignof(oqmc_sampler) == 8`. +- The value is trivially copyable and has no invariants beyond its bytes. A + binding may treat it as a plain `Copy` type (Rust) or `extern struct` + (Zig) and pass it by value. +- No initialisation or finalisation is needed for sampler values. +- No function touches global state. Any number of threads may call the API + concurrently on distinct or shared sampler values. +- Sample output is identical across the scalar, SSE, AVX and ARM builds of + the implementation for a given sampler. A change that alters output is a + version change of the library, not a build configuration. + +## Option A: Compile Time Selection + +Full detail in [optiona.md](optiona.md). + +The implementation is chosen by a preprocessor definition when the +translation unit defining `OQMC_IMPLEMENTATION` is compiled. One sampler +exists per build; only its code and data tables are linked; every call is +direct. + +```c +/* Sampler chosen when the implementation was compiled. */ +oqmc_sampler s = oqmc_sampler_create(x, y, frame, index, cache); +``` + +OpenQMC compiles that translation unit into `liboqmc` and distributes it. +Changing sampler means recompiling one translation unit with a different +definition. Because the implementation is in the header, an integrator can +opt in to compiling it within their own build instead, choosing the sampler +per binary. + +## Option B: Runtime Selection (future extension) + +Full detail in [optionb.md](optionb.md). Not part of the initial +implementation. + +All samplers are compiled into the library. The application selects one at +startup, defaulting to PmjBn if no selection is made. Every call then +dispatches through a single global table pointer. + +```c +/* Sampler chosen once at startup. */ +oqmc_sampler_select(OQMC_SAMPLER_TYPE_SOBOL); + +oqmc_sampler s = oqmc_sampler_create(x, y, frame, index, cache); +``` + +One prebuilt binary serves every consumer, and the sampler can come from a +configuration file without a rebuild. + +## Measurements + +The cost of the C boundary and of dispatch was measured against the inlined +C++ library. The workload is 4.19 million units, each unit being one `create`, +two `newDomain` calls, and two `drawSample<2>` calls, with all calls crossing +a real shared library boundary. Figures are the ratio to the inlined C++ time, +and the range is the spread over repeated passes. + +| Design | Sobol (8 bytes, compute bound) | PmjBn (16 bytes, table lookups) | +|---|---|---| +| Inlined C++ (header-only) | 1.00x | 1.00x | +| Monomorphic symbols (Option A) | 1.82x to 1.93x | 2.01x to 2.04x | +| Batched, 64 indices per call | 1.23x to 1.32x | 1.13x to 1.16x | + +Three dispatch strategies for Option B were also measured: a table pointer in +the value, a tag with a `switch`, and a tag with a table lookup. All differed +from the monomorphic build by less than the pass-to-pass spread, so their +rows are omitted. + +Three conclusions: + +1. **The boundary is the cost, dispatch is not.** A call site in a render loop + is monomorphic, so the indirect branch predicts correctly after the first + iteration. C consumers have no header-only fallback, so the roughly 2x + boundary is the defining performance characteristic of the C path under + either option. +2. **The options do not differ on performance.** The direct call Option A + retains measures as noise against Option B's dispatch. +3. **Batching is the real leverage**, an order of magnitude more than any + dispatch choice. Batch entry points can be added later without breaking the + ABI under either option. + +Caveats: figures come from a single machine using GCC at `-O2` on x86-64 +Linux, with cross library calls resolved through the PLT. Absolute timings +drifted between sessions, so only same-pass comparisons are meaningful, and +the batched row was measured in a separate binary from the others, which +gives it an unearned instruction cache advantage. Re-measure before relying +on the absolute penalties. A static library build, or hidden +visibility with direct binding, would reduce the boundary cost equally for +both options. + +## Comparison + +| Concern | Option A | Option B | +|---|---|---| +| Sampler selection | When the library is built | At startup | +| Selection from configuration | Requires a rebuild | Yes | +| Public header | Generic API only | Generic API plus type enum and select | +| Value size | 16 bytes, register return | 16 bytes, register return | +| Dispatch | Direct calls | One global table pointer, within noise | +| Code linked | Selected sampler only | All samplers and their data tables | +| Global state | None | One pointer, written at startup | +| Samplers per process | One, fixed at build | One, chosen at startup | +| Prebuilt packaging | One package per sampler | One package | +| Edit sites per new sampler | One selection branch | One enum entry, one registry entry | + +Both options present the same sampler API, so the choice does not affect +calling code, only how a deployment selects the implementation. Consumers that +link the distributed `liboqmc`, or compile the implementation into their own +build, are served by Option A: no global state, no ordering rules, and only the selected +sampler is linked. Deployments that ship one prebuilt binary to many +consumers, such as system packages and central studio installs, are better +served by Option B: one artifact, with the sampler chosen from configuration. +Under either option a process holds exactly one sampler implementation, which +matches the intended use. + +## Suggested Roadmap + +Option B is a strict superset of Option A's surface: the value layout and +every symbol are identical, and B adds only the type enumeration and select. +Option A can therefore ship first, with Option B added later as a +compile time feature, and the addition is API only, so already compiled +binaries are unaffected. Two things keep that door open: a non-default +Option A build replaced by an Option B build reverts to the pmjbn default +until it selects, which `oqmc_sampler_name` can check; and Option A's direct +calls and absence of global state must remain documented as properties of +the build, not guarantees of the API. + +## Runtime Dependencies + +A C consumer should be able to link the C ABI library with a C toolchain +alone. Linking it today leaves two unresolved symbols, `operator new[]` and +`operator delete[]` (`_Znam`, `_ZdaPv`), with a single source: `stochastic.h` +allocates a scratch buffer with `new std::uint32_t[nsamples][2]`, reached +through PMJ cache initialisation. + +Replacing that allocation with `std::malloc` and `std::free` removes the last +C++ runtime dependency. The buffer needs no construction, and allocation +failure changing from a thrown exception to a null pointer suits the assertion +based precondition style used throughout the library. This was verified: with +that single change, a C executable linked against the C ABI library depends on +`libc.so.6` alone, with no `libstdc++` and no `libgcc_s`, and sampler output +is unchanged. The change should land alongside the C ABI so that C consumers +never acquire a transitive C++ runtime. + +Removing the remaining libc use (`memcpy`, `assert`, and the `malloc` above), +so the implementation could be compiled freestanding, is a possible future +effort and out of scope here. + +## Build Integration + +```cmake +option(OPENQMC_ENABLE_C_ABI "Build the C ABI shared/static library.") +``` + +When enabled, `src/oqmc_impl.cpp` is compiled into a shared or static library, +selected by the `OPENQMC_SHARED_LIB` and `OPENQMC_FORCE_PIC` options that were +removed with the C++17 migration and need to be reinstated. The `oqmc_c.h` +header installs with the other public headers regardless of the option. The +compiled target is exported as a separate CMake target that does not propagate +`cxx_std_17`, so a C only downstream project can consume it without a C++ +toolchain requirement. + +## Testing + +Two test targets are needed under either option, because they check different +things: + +- **A C compiled target** — a small program built by the C compiler with + `-std=c11 -Wall -Wextra -pedantic`, linked against the C ABI library and + nothing else. This is the only test that proves the header is valid C and + that the symbols link from C. +- **`src/tests/oqmc_impl.cpp`** — a GoogleTest target that includes both + `oqmc/oqmc_c.h` and the C++ headers, verifying the C results bit for bit + against the equivalent `SamplerInterface` calls: `create`, all four domain + derivations, and all draw functions at every size in 1 to 4, plus value + semantics and self assignment. + +Each option document adds the tests specific to its selection mechanism. + +## Planned Language Support + +The C ABI is part of a broader strategy to expose OpenQMC to multiple +languages: + +- **C++** — header-only (existing library, unchanged). +- **C** — via the C ABI defined in this spec. +- **Zig** — via the C ABI (first-class C interop via `@cImport`). +- **Rust** — via the C ABI (`bindgen` on the C header, plus link). +- **Python** — via nanobind, binding directly to the C++ API (separate effort, + not through the C ABI).