ovclash C/C++ Code Style#

This guide sets the formatting and coding conventions for all native C/C++ code of ovclash: the library sources, the public API headers, the native tests, the benchmarks and the samples. The shared engine sources under source/usdclash/ (the clash-detection engine that ovclash shares with the Kit extension and reads unchanged) and code adapted from the OpenUSD library keep their existing formatting and notices; match the surrounding file there.

Rule strength:

  • MUST marks a rule that new and touched code follows and reviewers enforce. An existing file that still deviates is normalized when that code is next touched, never in a wholesale reformat.

  • SHOULD marks a preference that yields to a local reason. MAY marks an admitted alternative.

  • Legacy marks a tolerated older form, normalized when the code is next touched.

  • A form “not used so far” is one the code has not needed yet. Use it where it fits the case better than the form in use, and the form in use everywhere else; the reviewer judges the fit.

Where this guide is silent, match the surrounding file. CI verifies legal headers only; reviewers apply the layout rules by hand (section 17).

The code blocks of this guide are layout excerpts, not programs. Each shows the rule of its section inside a .cpp or header under source/, include/, tests/native/, benchmarks/ or samples/, and uses illustrative names, such as Widget, computeTotal() and ovclash_widget_t, that ovclash does not define. Copy the form, not the names.

The guide also names the C ABI (C application binary interface) of the public headers, the Suite API layer, ovstage, PhysX and Carbonite. pxr is the C++ namespace and include prefix of OpenUSD, and Doxygen is the C/C++ documentation generator that renders the public headers. SPDX (Software Package Data Exchange) is the standard of the two machine-readable license lines that open every new file.

Quick reference#

Indentation and braces#

  • 4-space indent, no tabs. Namespace bodies and case labels are not indented. Lines stay within 120 columns.

  • Braces MUST be Allman ({ on its own line) except in lambdas.

  • Braces are the default for control bodies. A one-line guard if (!ptr) return false; MAY be unbraced. else MUST be braced, and the two forms never mix.

  • One blank line, never two, MUST separate function and method definitions, and method declarations.

Spacing#

  • *, & and && MUST bind to the type (Widget* widget).

  • Control keywords MUST take exactly one space before (.

  • Braced init pads non-empty braces with one space, Range{ lo, hi }; an empty list is tight, T x{};.

File header, includes and namespaces#

  • Preserve the applicable license and copyright notice when editing or moving an existing file. New project-owned files use this SPDX pair (creation year), followed by a blank line, then #pragma once in headers:

    // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
    // SPDX-License-Identifier: Apache-2.0
    
  • Include groups, a blank line apart: UsdPCH.h/own/project headers, third-party, std, <pxr/...>.

  • Namespaces MUST use the C++17 nested form with a tagged closer: } // namespace omni::ovclash.

Naming#

  • Names MUST follow these patterns:

    • Types WidgetCache; enumerators Kind::Solid; functions verb-first computeTotal().

    • Locals, parameters and plain-struct fields rowCount; class members mCount; constants kMaxItems.

    • C-ABI fields and parameters snake_case (nb_items, items_count), except the legacy camelCase names of ovclash/ovclash.h (section 16.3); C-ABI enumerators OVCLASH_WIDGET_MODE_FAST.

  • Macros MUST be OVCLASH_UPPER_SNAKE. Library code defines no constant, logic or helper macros beyond version macros (section 13.4; section 16.1 names one public exception).

Declarations and statements#

  • File-local helpers MUST live in one unnamed namespace, never static; using namespace MUST NOT appear at global scope.

  • Constants are plain constexpr kName variables, never macros; const goes west of the type.

  • One-argument constructors MUST be explicit; owners and guards delete the copy pair.

  • Casts are named, null is nullptr, and every standard name but the <cstdint> integers and size_t carries std::.

  • Counted loops read for (size_t index = 0u; index < n; ++index); directives sit at column 0 and test #if defined(X).

Comments and the C ABI#

  • Comments MUST be // lines above their code, full sentences saying why; trailing ones stay short.

  • Each public-header prototype MUST carry a /** */ block covering every parameter, and in ovclash/ headers also the return.

  • Every public header but the macro-only ovclash/ovclash_export.h MUST have exactly one #ifdef __cplusplus extern "C" fence, and every C entry point MUST carry OVCLASH_API from ovclash/ovclash_export.h.

  • An exported entry point MUST only forward to its private operation, whose fallible body runs in the result guard named after the public function and validates arguments first.

1. File layout and header#

1.1 Text format#

  • Files MUST use LF line endings and MUST end with exactly one newline.

  • Files MUST be space-indented, with no tabs and no trailing whitespace; lines MUST stay within 120 columns.

  • A .cpp SHOULD stay below 100,000 bytes. Split an oversized unit by responsibility behind a private header (section 1.4 names the pieces). Headers have no size limit.

  • The shared engine under source/usdclash/ is exempt from the size limit. It is never split or modified to meet it.

1.2 SPDX header and guard#

  • New project-owned .h and .cpp files use the two SPDX lines that this section’s example shows. Existing file licenses, third-party notices and inherited copyright years MUST be preserved; moving a file does not change its license.

  • For a new original file, the year is its creation year. Do not replace an existing notice or discard attribution when deriving a file from existing code.

  • One blank line MUST follow the pair. The legal check of section 17 reads a bare // line after the pair as the start of a license body, so a file comment never joins the pair.

  • #pragma once MUST be a header’s only guard and its first directive, followed by a blank line.

  • #pragma once MUST NOT appear in a .cpp.

  • #ifndef guards MUST NOT be used.

// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

#pragma once

1.3 File-level comment#

  • A file-level comment SHOULD be omitted; add one only for what the code cannot say:

    • why the file is a separate unit,

    • forbidden includes,

    • adapted-code origin.

  • Write it as a // paragraph, followed by one blank line; it MUST NOT be a banner.

  • In a header it follows #pragma once and a blank line; in a .cpp it follows the blank line after the SPDX pair.

1.4 File names#

  • File names MUST follow this table; snake_case is reserved for the C-ABI units.

Unit

Name

Example

C++ header or source

PascalCase after the main type or topic

WidgetCache.h, TaskQueue.cpp

Shim for a shadowed include

The exact path of the include it shadows

UsdPCH.h, extlib/geometry/simd.h

C-ABI forwarding unit of an API layer

ovclash_<layer>_api.cpp

ovclash_widget_api.cpp

Shipped C-ABI header

Stable snake_case public include name

ovclash.h, ovclash_suite_models.h

  • Implementation files and private headers use PascalCase, also when their operations implement a C API. The forwarding unit exposes the C symbols and delegates to those C++ operations.

  • An include shim, a generated header template and a file that the shared engine includes by exact name keep their established names.

  • The pieces of a split unit keep the original stem as a prefix, so the family sorts together: WidgetCache.cpp, WidgetCacheGeometry.cpp, WidgetCacheGeometryInstancing.cpp. They share a private header named after the stem (WidgetCacheInternal.h).

2. Includes and precompiled header#

2.1 Include block and precompiled header#

  • The prologue ends in one include block; there MUST NOT be an #include outside it, a second include block mid-file, or a header included twice. Legacy: a mid-file include block, hoisted when the unit is next restructured.

  • Native white-box tests are the exception: they MAY include the implementation units of a family and their *Cases.h case files where the cases need them.

  • One blank line MUST separate the include block, forward declarations and the rest of the file.

  • A .cpp MUST open with the header it implements, after "UsdPCH.h" when that leads (Widget.cpp includes "Widget.h"); a Suite unit opens with its layer’s internal aggregate header.

  • A unit that touches OpenUSD MUST include "UsdPCH.h" first; only a comment MAY precede it. The build compiles a unit that does not include it without the precompiled header.

  • "UsdPCH.h" MUST NOT be included from a header or from a unit that does not touch OpenUSD.

2.2 Include groups and order#

  • Include groups MUST follow this order, with one blank line between groups and none inside, and quoted includes before angle-bracket ones.

    1. "UsdPCH.h", then the own header, then other project headers alphabetically.

    2. Third-party: <carb/...>, <ovstage/...>, <ovx/...>, <omni/...>, PhysX.

    3. C++ standard headers, ASCII-sorted.

    4. <pxr/...>, in headers only; a unit that includes "UsdPCH.h" repeats none of them.

    5. Platform-only includes in a #if defined(_WIN32) / #else / #endif fence (section 13.2).

  • A feature-gated include sits in its group’s sorted slot inside a column-0 #if defined(OVCLASH_FEATURE) / #include / #endif with no blank line inside.

  • Legacy: run-together or unsorted groups, normalized when the group is touched.

2.3 Quoting and header spelling#

  • Quote in-repo headers. A public API header goes by its install path ("ovclash/ovclash.h"). A private header goes by bare file name when it sits beside the including file or directly in source/, otherwise by its path from source/ ("suite/widgets/WidgetStore.h"). Tests reach another test directory by a relative path ("../common/TestHelp.h").

  • Angle-bracket external headers by library-relative path (<carb/...>, PhysX, <Windows.h> with a capital W). Sources MUST NOT use <ovclash/...>. A C consumer test is the exception: it includes the public headers as a consumer does. Legacy: a native test that spells <ovclash/ovclash.h>, quoted when touched.

  • Spell C library headers the C++ way (<cstdint>, <cstring>) and std::-qualify their functions. C++ code spells a C header the C way only for a POSIX or Windows declaration: <locale.h> for the locale-object API (newlocale, uselocale, _create_locale), <limits.h> for PATH_MAX.

  • Shipped headers spell standard headers the C way (section 16.1).

  • C sources, such as the C consumer tests, and the C-compatible headers they share with the C++ tests follow C where the C++ form does not exist: C header spelling, unqualified C library calls, int, file-local static (static inline helpers in a shared header), C casts, /* */ comments, and constant and helper macros.

2.4 Self-sufficiency and forward declarations#

  • A header MUST include every standard header it uses (<cstdint> for uint32_t) rather than rely on a sibling.

  • A .cpp relies on its own header and adds standard headers only for what that header lacks.

  • Forward declarations follow the include block and repeat the type’s own keyword: struct X;, or class X; for a type defined as a class (class WidgetStore;).

  • Forward-declare a foreign C or Carbonite type held by pointer or reference (struct sqlite3;), or a same-project type used before its definition or held in a std::unique_ptr.

  • Include pxr, PhysX and ovstage headers in full; their types are not forward-declared so far.

3. Namespaces, anonymous namespaces and static#

3.1 Namespace form#

  • Namespaces MUST use the C++17 nested form: keyword at column 0, { alone on the next line, body not indented, closed at column 0 with } // namespace <name> (} // namespace when unnamed).

  • Nested namespaces MUST NOT be stacked as namespace omni { namespace ovclash {.

  • A body MUST NOT be padded with a blank line on the opening side only.

  • Legacy: a stacked opener, rewritten in the nested form when touched.

3.2 Namespace roles and the units that open them#

Names follow section 7. Each namespace has a fixed role:

Namespace

Role

omni::ovclash

The engine API and general header-only utilities.

omni::ovclash::detail

Other header-only helpers and internal types.

omni::ovclash::validation

Code of the engine validation observer, fenced by OVCLASH_ENGINE_VALIDATION_OBSERVER.

omni::ovclash::detail::ovstage

Private types and helpers shared by the ovstage backend units.

omni::ovclash::scene_reader_detail

Helpers shared by the scene-reader units, the OvstageSceneReader*.cpp units that read the scene through ovstage.

omni::ovclash::retained_source

The private adapter of the opt-in retained source snapshot experiment.

omni::ovclash::detail::ovclash_matrix_decomposition

The OVCLASH matrix-decomposition mode, ovclash’s own decomposition math.

omni::ovclash::test, omni::ovclash::sentinel and their sub-namespaces

Native test code, and the code of Sentinel, the correctness campaign.

A global inline namespace <name>test

Helpers shared by the units of one native test executable, which its global allocator replacement and main() still find unqualified.

A foreign namespace (carb::tasking)

Only to declare or define a stand-in for a foreign symbol.

Global scope

C entry points and ovclash_*_t handles.

  • Legacy: a camelCase test namespace, renamed when touched.

  • A library .cpp MUST reopen only omni::ovclash, or a foreign namespace for a stand-in, and write detail::x / validation::x inside it. A unit that defines declarations of detail::ovstage or scene_reader_detail MAY also open that namespace.

  • A header of internal helpers opens omni::ovclash::detail (or its private sub-namespace) directly.

  • C-ABI export and Suite units MUST NOT open a named namespace; omni::ovclash functions defined there are written fully qualified at global scope.

  • The export unit of the canonical API has no extern "C" block; its entry points take C linkage from the fences of the shipped ovclash/ headers. A private export that no shipped header declares carries extern "C" OVCLASH_API on its definition.

  • The Suite export unit holds includes followed by one extern "C" block of forwarding ovclash_suite_* entry points. Implementation helpers and operation bodies belong in the PascalCase Suite source files, outside C linkage.

3.3 File-local helpers instead of static#

  • File-local helpers, constants, aliases, types and globals of a .cpp MUST live in one unnamed namespace right after the includes and forward declarations (section 2.4). Namespace aliases follow section 3.4.

  • static MUST NOT mark a free function or file-scope object.

  • Headers MUST NOT contain an unnamed namespace.

  • A helper shared by several translation units is declared in an internal header with external linkage; a single-file helper MUST NOT be.

  • A shared helper MUST be defined exactly once: out of line in one unit, or inline in the internal header. Choose inline when the helper is small, or when it is called per row or element and must stay inlinable.

  • Never copy a file-local definition into a second unit. The native white-box tests include every unit of a family into one translation unit, where a duplicate fails to compile.

  • Legacy: units split from one large file may interleave several unnamed-namespace blocks with their sub-namespace definitions; consolidate them when the unit is next restructured.

3.4 Using-directives, using-declarations and aliases#

  • using namespace and PXR_NAMESPACE_USING_DIRECTIVE MUST NOT appear at global scope and SHOULD NOT at function scope.

  • Qualify every foreign name at each use (std::memcpy, physx::PxVec3).

  • PXR_NAMESPACE_OPEN_SCOPE MUST NOT appear in any file.

  • Using-declarations MUST go one per line, sorted, at the top of a sub-namespace or unnamed namespace; they MUST NOT appear at global scope.

  • A namespace alias is short and declared once, where its users see it:

    • at global scope in the shared internal header of a unit family;

    • inside a function;

    • at the top of a native test’s namespace (namespace wd = omni::ovclash::detail::widget;).

  • An alias for observer code sits inside the observer fence.

  • Legacy: unqualified PhysX names, qualified with physx:: when touched.

4. Braces and blocks#

Allman braces except in lambdas; control keywords MUST take exactly one space before ( (section 6).

4.1 Allman by default#

  • Functions, methods, constructors and operators MUST be Allman, also after a member-initializer list, never void f() {. A one-statement body MAY be one line: int count() const { return mCount; }.

  • Classes, structs, enums, namespaces and extern "C" blocks MUST be Allman, also when nested; namespace bodies are not indented, extern "C" bodies indent one level.

  • if, else, for, while, switch, try and catch MUST be Allman, even when the condition wraps; the one-line try { x; } catch (...) {} swallow of section 14 is the exception.

  • else and catch start a new line after }.

  • Lambdas are the one K&R construct: { ends the introducer line, the body indents one level and } returns to the indent of the line carrying [. Control statements inside keep Allman braces.

4.2 Control-statement bodies#

  • Braces are the default for control bodies; a one-line guard is acceptable: if (!ptr) return false;, if (done) break;, if (skip) continue;, a one-line throw or one short guarded statement.

  • Brace it once the condition or statement wraps, nests a control statement or gains an else.

  • else MUST be braced; a braced and an unbraced branch MUST NOT mix.

  • Legacy: an unbraced statement on the next line, normalized when touched.

4.3 Switch statements#

  • case and default labels sit at the switch column with bodies one level deeper; a case with locals braces its body at the label’s column.

  • Fallthrough labels stack one per line, no blank line between cases.

  • Every case SHOULD end in break; or return and every switch SHOULD have a default:; a switch without default: appears only in native tests so far.

switch (widget->kind())
{
case Kind::Solid:
    total += computeTotal(*widget);
    break;
default:
    break;
}

4.4 Braced lists and enums#

  • A multi-line braced list opens with = { on the declaration line and closes with }; at the declaration’s indent.

  • A multi-line braced list and a multi-line enum put one entry per line, every entry ending in a comma, the last included (C headers excepted, section 16.3). Legacy: a comma-less last enumerator.

4.5 Blank lines#

  • Exactly one blank line MUST separate consecutive function and method definitions, and member function declarations in a class.

  • Single blank lines separate phases inside a body.

  • Two consecutive blank lines MUST NOT appear, nor a blank line directly after an opening { or before a closing } / };.

5. Indentation, line length and wrapping#

5.1 Indentation and line length#

  • Indent 4 spaces per brace level; a namespace body adds none.

  • Access specifiers sit at the class column, case labels at the switch column, and preprocessor directives at column 0.

  • Hard limit 120 columns; a statement or signature that fits MUST NOT be wrapped (a C-ABI definition, section 5.4, and a braced list or enum body, section 4.4, excepted). Legacy: a longer line, rewrapped when next edited.

  • Full-line // prose wraps at 100 columns.

5.2 Breaking at operators#

  • Break after the operator: &&, ||, +, -, =, (, ,, ? and : end a line and MUST NOT start one. Legacy: a leading ? or :.

  • A wrapped condition aligns with its first operand.

  • A line ending in = puts its whole RHS at exactly +4.

  • Exceptions, where the operator leads the line: << in a stream chain, . or -> in a member-call chain, and the : of an initializer list.

  • A member-call chain past two calls SHOULD bind a named local.

  • A constructor initializer list that does not fit the signature line starts : a(x), b(y), at +4 on the next line, bin-packed, with overflow under a.

5.3 Parameters and arguments#

  • Wrapped parameters go one per line, aligned to the column after (, with ) attached to the last.

  • Break after ( and indent +4 instead when the name is long, the aligned form is too wide, or type name( plus the first parameter does not fit. The parameter list MAY then share one line.

  • The return type MUST NOT be split from the name. Legacy: a return type alone on its line.

  • The first parameter MUST NOT stay on the signature line with the rest hung at +4.

  • Call arguments go one per line or all on one continuation line; the two forms MUST NOT mix.

  • Wrapped arguments align under the first argument, or at +4 after a break at (.

  • A lambda argument follows the lambda layout of section 4.1.

#include <cstddef>
#include <vector>

void insertVisibleWidgetIntoSlot(const Widget& widget,
                                 size_t slot,
                                 const WidgetInsertOptions& insertOptions);

bool rebuildWidgetIndexForDirtySlots(
    const WidgetCache& cache, const std::vector<size_t>& dirtySlots, bool force);

5.4 C-ABI definitions#

  • A C-ABI definition SHOULD wrap its parameters and put its body on its own lines. Legacy: a one-line ABI body or a flat +4 hang after return.

  • Suite ABI exports forward to private implementation operations. An implementation body keeps return suiteGuard("<action>", [&]() -> ovclash_suite_result_t { whole and breaks after suiteGuard( only past 120 columns.

6. Spacing#

6.1 Statements and comments#

  • One statement per line; a = 1; b = 2; MUST NOT share a line.

  • A trailing comment sits one space after the code. Runs of spaces MUST NOT align code or comments; the \ of a multi-line macro (section 13.1) is the exception.

6.2 Parentheses, angle brackets and pointers#

  • Control keywords MUST take exactly one space before (: if (, for (, while (, switch (, catch (.

  • template < takes the same single space (placement: section 10.1).

  • Calls, declarations and casts take no space before ( or [ and none inside (), [] or <>: sizeof(x), std::vector<std::vector<int>>&.

  • *, & and && MUST bind to the type, not the name: const char* s, T& r, T** out; T *p MUST NOT appear.

  • A function pointer reads ret (*name)(args): one space before (*, none inside or after.

6.3 Operators and punctuation#

  • Binary, assignment, comparison, logical, bitwise, shift and ternary operators MUST have one space on each side; unary operators, ->, . and :: sit flush.

  • Increments SHOULD be prefix, ++index.

  • A comma or for semicolon takes one space after, none before; a list breaks after a comma.

  • Every colon but a label’s (case X:) has one space each side: class A : public B, ) : mX(x).

6.4 Braces, initializers and lambdas#

  • One space precedes an opening brace that shares a line ([&]() {, = {, return { x };, -> bool {), save a braced-init type, which is flush against its {.

  • A collapsed body is padded, { return x; }; catch (...) {} is tight.

  • A non-empty braced-init list has one space inside each brace and the type flush against {: Type{ a, b }, return { x };; {x} MUST NOT appear.

  • An empty braced-init list is tight, T x{};; { } MUST NOT appear.

  • Lambdas take no padding inside [].

  • Trailing qualifiers read ) const noexcept override.

#include <cstddef>
#include <vector>

const int* findFirstWidget(const std::vector<std::vector<int>>& groups, void (*onEmpty)(void*) noexcept)
{
    const auto isEmpty = [&](size_t index) { return index >= groups.size() || groups[index].empty(); };
    if (isEmpty(0u)) onEmpty(nullptr);
    return isEmpty(0u) ? nullptr : &groups[0u][0u];
}

7. Naming#

Casing follows the entity kind; every rule here is a MUST unless marked SHOULD.

Entity

Form

Example

Type, alias, enumerator, template parameter

PascalCase

Widget, Kind::Begin

Function, method, lambda, local, C++ parameter

lowerCamelCase

computeTotal, rowCount

Data member of a class with private:

m + PascalCase

mCount

Field of a plain aggregate that no other row covers; legacy engine field of ovclash/ovclash.h (section 16.3)

lowerCamelCase

rowCount, nbWidgets

Field of an ovclash_*_t handle, a Suite-layer record or a public C struct

lower_snake_case

file_path, nb_records

Constant at namespace or class scope; local constexpr

k + PascalCase

kMaxItems

File-scope global, thread_local included

g + PascalCase

gRegistry

RAII helper; hash functor

<X>Exit, <X>Cleanup, <X>Release, <X>Guard, Scoped<X>; <X>Hash

WidgetGuard, WidgetHash

Macro, preprocessor switch, env var, C-ABI enumerator

OVCLASH_UPPER_SNAKE

OVCLASH_WIDGET_READY

Namespace, namespace alias

lowercase word; lower_snake_case when it needs more than one word

detail, scene_reader_detail

Public-header C-ABI function, type and out-parameter

ovclash_<verb>_<noun>, ovclash_<name>_t, out_<noun>

ovclash_get_widget_count, ovclash_widget_t, out_count

7.1 Words and spelling#

  • Words are spelled out (Index, Count); counts are <noun>Count, never num*.

  • Acronyms are cased as words (Json, Utf8, Id); brand casing only for PhysX.

  • A 1:1 stand-in for an external API SHOULD keep the external spelling (npos, engine eValue).

7.2 Members, globals and aliases#

  • A member MUST NOT carry m_ or a trailing _.

  • A global MUST NOT be s, g_ or unprefixed.

  • Mutable process-wide state SHOULD live in a function-local static (lowerCamelCase) behind an accessor.

  • Aliases SHOULD use using rather than typedef.

  • Template parameters are role nouns (RowSink) or generic T.

7.3 Enums and C-ABI handles#

  • Internal enums are enum class with bare PascalCase enumerators (no e, k or ALL_CAPS) and a fixed-width base when stored or serialized.

  • A plain enum Name : uint32_t SHOULD be reserved for bit masks.

  • A C-ABI handle is a C++ struct named as the typedef, with snake_case data and camelCase methods. Legacy: a camelCase handle data member, renamed when touched.

  • Foreign ovstage_*_t types stay verbatim and MUST NOT be aliased.

7.4 Functions#

  • Functions are verb-first (collectWidgets); noun-first only for predicates and converters <thing>From<source>.

  • Accessors are bare nouns (bounds()); get* only on free lookups.

  • Predicates SHOULD read is/has/can/should + noun (isDigit).

  • Cross-cutting families SHOULD keep their prefix, verbs included (suite*, sqlite*).

7.5 Parameters and locals#

  • By-reference outputs are plain role nouns (record); nullable pointer outputs are out<Camel>, never out_<snake> on a camelCase helper.

  • error is the last parameter before defaulted ones.

  • A snake_case local only when forwarding a C-ABI argument or an ovclash_*_t member.

  • Role names (SHOULD): ok, exception, lhs/rhs, it, found, inserted, index or the counted noun; lookup maps <value>By<Key>; bools are bare adjectives (hidden), never Hungarian.

  • Pair halves are item0/item1.

  • Legacy: k on a runtime-initialized static const, a/b comparators, stmt, and i/j/k outside fixed-size math, normalized when touched.

8. Declarations, const, auto and literals#

8.1 Constants, const and inline#

  • Namespace-scope constants SHOULD be plain constexpr and MUST NOT be #defines.

  • Non-literal types such as std::string use plain const; class constants are static constexpr.

  • const MUST go west of the type (const std::string& s).

  • Make a local const when nothing mutates it after initialization; pointer locals, RAII guards and by-value parameters stay unqualified.

  • Headers hold prototypes, constexpr constants, templates and inline functions; a non-template free function defined in a header MUST be inline.

  • A header constant MAY be inline (inline constexpr or inline const). static on a namespace-scope constant is not used so far; static inline appears only in C-compatible code (section 2.3).

8.2 Declarations, auto and initialization#

  • Prefer spelled-out local types; auto is acceptable where the initializer names the type: lambdas, iterators, structured bindings, make_unique, clocks, opaque C-API results and range-for elements (section 11).

  • Each line MUST declare one initialized variable; declare at first use, in the narrowest scope.

  • A function SHOULD NOT open with a declaration block. A declaration inside an if condition tests a pointer or std::shared_ptr result (if (const auto cached = findCachedWidget(key))); if (init; cond) is not used so far.

  • Initialize by kind (the scalar forms also serve as default member initializers):

    • scalars, pointers, bools and enums: = 0u, = nullptr, = false, = Kind::None;

    • STL and PhysX objects: parentheses, std::vector<T> v(n);;

    • atomics and project aggregates: spaced braces, Range{ lo, hi };

    • C and ABI structs: T d{};.

  • Prefer T x{}; for zero-initialization; a zeroing memset is legacy, normalized when touched.

  • Class-type members stay bare; references, const and derived members go in the initializer list.

8.3 Types, literals and sentinels#

  • Count with size_t; a count crossing the C ABI takes the scalar section 16.3 assigns: uint32_t for a nb_<x> field or an index, size_t for an input-array <items>_count or a buffer size.

  • Cast with a named cast (section 14.4); a C-style cast MUST NOT appear, (void)param; (section 8.4) excepted.

  • Suffixes: u on unsigned values and flag tests (= 0u, 1u << N), f on floats (1.0e-12f); doubles carry a point and no suffix (0.0). Byte sizes derive from sizeof; a C array’s element count is std::size(table) (legacy: sizeof(a) / sizeof(a[0]), normalized when touched).

  • Sentinels SHOULD be spelled by name (std::string::npos, kNoSlot). A missing uint32_t index is 0xffffffffu, and a missing signed id is -1.

  • ABI booleans MUST be exactly 0u and 1u.

  • A single string constant SHOULD be constexpr const char* kName = "...";; the array form is acceptable when sizeof(kName) - 1u or indexing needs it.

  • Use a char literal for one character ('/').

  • Return an empty value as return {};.

  • Narrow literals are the form in use; wide literals appear only in Windows-only code that passes or compares wide-character text (GetModuleHandleW(L"widget.dll"), a wmain argument).

8.4 Parameters#

  • Prototypes MUST name every parameter; a no-argument C ABI function is (void), a C++ one ().

  • An unused parameter SHOULD be consumed by (void)param; as its first statement, or left unnamed only in a whole-function stub; /*name*/ and [[maybe_unused]] are not used.

  • Parameter order: handle, ordinal, paths and names, other inputs, outputs, std::string& error.

  • Defaults are spelled once, on the declaration.

  • Small trivially-copyable inputs go by value, aggregates as const T&, optional inputs as const T*; a Suite boolean MUST be uint32_t, not bool.

  • A string parameter SHOULD be const std::string& internally; std::string_view is the form for a non-owning lookup. Text crossing the C ABI MUST take the form section 16.3 defines.

9. Classes, structs and initializer lists#

9.1 Struct, class and header#

  • A type whose members are all public MUST be a struct; class only when a private: section hides state behind bare-noun const accessors.

  • Not used so far: friend and a field-mirroring getter/setter pair. protected: appears only where a native test overrides a protected standard-library hook.

  • A pimpl is acceptable for an exported C++ class (section 16.3) and for a class that hides a heavy implementation.

  • A header MUST hold one primary class plus its record structs and enums; a helper type sits inside the one function or type that uses it.

  • Prefer defining members in the class body; Class::method in a header, inline or not, is not used so far.

  • Only a class declared in a shared header defines Class::method() in its .cpp.

9.2 Body layout#

  • public: MUST follow { directly; at most one private: label follows after one blank line. Labels sit at the class column, members one level deeper.

  • Class order: aliases, nested types and k constants; the ctor/dtor/= delete group; methods; private: helpers and data.

  • Struct order: constants, data, special members, methods.

  • A C-ABI handle MUST be a struct ovclash_*_t matching its typedef: snake_case fields with defaults, then ctor/dtor, then methods.

  • Member function declarations are separated as section 4 requires; data members pack one per line, with no blank line between them (a trailing label follows section 12).

9.3 Constructors and initializer lists#

  • Every constructor callable with one argument MUST be explicit, defaulted parameters included.

  • Initializer lists SHOULD follow declaration order; an empty body stays Allman.

  • Widget() = default; SHOULD appear only when another constructor suppresses the default one.

  • Copy, move and destructor SHOULD stay implicit when their generated behavior suffices. Explicitly defaulted virtual destructors are used by abstract serializer interfaces.

9.4 Ownership and guards#

  • Owners and guards MUST delete the copy pair, one after the other.

  • A destructor MUST call the type’s reset() or release() path when it has one.

  • A non-owning collaborator SHOULD be a reference member bound once or a raw pointer = nullptr.

  • A shared immutable payload MUST be a std::shared_ptr<const T>; weak_ptr is not used so far.

  • A scope guard is an all-public struct named as section 7 prescribes (WidgetGuard), holding the retired reference, a bool keep flag or a disarming release(), and a destructor that never throws.

9.5 Members, virtuals and operators#

  • Every non-mutating member MUST be const; mutable only for a cache or a mutex.

  • static member functions SHOULD be limited to stateless helpers or factories; mutable static data SHOULD NOT be used.

  • virtual SHOULD be limited to callback and abstract collaborator interfaces, such as serializers.

  • An overrider MUST say override (legacy: bare virtual, normalized when touched).

  • In use:

    • final on concrete serializer, cursor and bulk-writer implementations;

    • [[nodiscard]] on a fallible internal helper whose result must be checked;

    • dynamic_cast only in white-box native tests that check a serializer’s concrete type.

  • Operators in use:

    • arithmetic operators as free functions;

    • [] and == as members;

    • < as a member of a sorted key struct;

    • () on functors only;

    • != only on a native test allocator.

  • Stream and conversion operators and std::hash specializations are not written so far.

10. Templates and lambdas#

10.1 Templates#

  • template <typename Body> MUST go on its own line; write typename, not class.

  • Templates are unconstrained (C++17 has no concepts); if constexpr, SFINAE, specializations and CTAD are acceptable where they fit.

  • static_assert SHOULD be reserved for invariants (ABI sizeof, enum-value equality).

  • Let template arguments deduce; spell them only when deduction fails (std::make_unique<Widget>) or std::min/std::max mix widths.

  • Return types are explicit; -> decltype(...), decltype(auto), auto f() are not used so far.

  • Hash keys in use:

    • strings and string views;

    • integers, including the uint64_t handles of the ovx headers and of ovstage;

    • pointers and pxr::SdfPath;

    • small key structs with a member == and a <X>Hash functor.

  • A std::hash specialization or a pair key is not used so far.

10.2 Callables, lambda placement and captures#

  • Prefer a callable as a template parameter (forwarding reference, called directly), last or before a trailing defaulted flag; std::function is acceptable when the callable is stored.

  • Pass a lambda inline as the last argument of a higher-order call; hoist it into const auto name = [&](...) { ... }; only when it is reused, a deleter, a sort key or one isolated step.

  • Name a lambda as a verb (flush), a predicate as a property (less).

  • Capture by lifetime: [&] for anything consumed in the enclosing scope, [] for a stateless helper or C trampoline, a named list when the lambda escapes, [this] only for an escaping member callback.

  • [&, x] appears only where native tests and benchmarks start threads; [=] and [*this] are not used so far. Prefer [&], [], a named list or [this], as the capture-by-lifetime rule assigns them.

  • Prefer a lambda over a functor struct; a functor struct is acceptable for a reusable deleter.

10.3 Lambda signatures, layout and comparators#

  • Prefer explicitly typed lambda parameters; const auto& is acceptable in a one-line predicate.

  • Unused lambda parameters are unnamed.

  • A lambda SHOULD carry a parameter list, []() {, even when empty.

  • A body passed to the ovstage backend’s capiResultGuard or a row-consumer template MUST spell -> bool. The OpenUSD backend’s capiResultGuard body spells -> ovclash_result_t and returns kSuccess or kError. A suiteGuard body MUST spell -> ovclash_suite_result_t (legacy: deduced, normalized when touched).

  • Elsewhere spell -> T only for a reference return, a fixed width or a named multi-statement bool step.

  • A multi-line lambda follows section 4.1 and is joined to what follows; no blank line frames a local lambda.

  • A same-type comparator names its parameters lhs/rhs and tests its keys in priority order, one guard per key, ending in an unconditional return; std::tie is not used so far.

#include <algorithm>

std::sort(items.begin(), items.end(), [](const Item& lhs, const Item& rhs) {
    if (lhs.slot != rhs.slot) return lhs.slot < rhs.slot;
    return lhs.id < rhs.id;
});

11. Control flow#

11.1 Guards and returns#

  • Open a function with returning guards so the happy path stays least indented and ends in return true;. A guard SHOULD NOT be followed by else.

  • Fold consecutive fallible calls into one condition with one failure body; when the chain is the whole function, write return a() && b();.

  • Return bools directly (return a && b;); ? true : false and == true SHOULD NOT be used.

  • Test pointers by truthiness, containers by .empty(), and find results against npos or .end().

if (mStopRequested) return false;
for (const auto& widget : mWidgets)
{
    if (!processWidget(widget)) return false;
}
return true;

11.2 Loops#

  • Use range-for whenever the index is not consumed: read through const auto&, mutate through auto&, take scalars by value. auto&& is not used so far.

  • A counted loop MUST read for (size_t index = 0u; index < n; ++index): < bound, prefix step, index type matching its bound; the variable is named as section 7.5 says. Legacy: a bare 0 initializer, normalized when touched.

  • Skip an item with a continue; guard at the top of the body and leave on a decisive state with break;. The rest of the body SHOULD NOT be wrapped in else instead.

  • Prefer for (;;) for an unbounded loop; while (true) is acceptable in the samples.

  • A do-while serves a loop whose body runs at least once, such as a list parser that continues after each ,.

  • A do { ... } while (false); block MAY leave a sequence of steps early with break;.

  • goto SHOULD NOT be used.

11.3 Ternaries and dispatch#

  • A ternary is a simple two-way value pick with side-effect-free branches in a return, initializer, assignment or argument.

  • A ternary SHOULD NOT be a statement or nested; use if/else or parenthesize.

  • Dispatch on an enumerator, char or small code with switch; layout and default: follow section 4.3.

  • Ranges and string tests use if/else if chains with the failure outcome last.

11.4 State guards and assertions#

  • Restore transiently mutated state with an RAII guard; lock shared state with std::lock_guard.

  • Prefer guards, exceptions or static_assert over runtime assert; assert is not used so far.

12. Comments#

12.1 Form#

  • Every comment in implementation code MUST be a // comment with one space after //, on its own line above its code at the same indent unless trailing (section 12.2 lists the trailing forms).

  • /* */ comments, commented-out code, #if 0 and banners MUST NOT appear.

  • Doxygen /** */ belongs to the shipped public headers alone (section 16.2); implementation code MUST NOT carry it.

  • Continuation lines MUST repeat // and wrap at 100 columns.

  • Paragraphs MUST be separated by a bare // line, never a blank line.

  • A comment and its code MUST NOT be separated by a blank line.

12.2 Wording and content#

  • Write complete English sentences in impersonal voice (capital first letter, terminal period, no we) with -- as the dash, never a Unicode dash.

  • Explain why, not what: the invariant protected, the quirk defended against, or the consequence of getting it wrong. A comment MUST NOT paraphrase the next line or add // Helpers labels.

  • A declaration comment SHOULD state preconditions, threading, ownership and lifetime, and return semantics.

  • Explain a behavioral oddity where it occurs; leave boilerplate such as (void)param uncommented.

  • Prefer stating open work as a sentence; tag markers (WARNING:, NOTE:, TODO, FIXME, HACK) are not used so far.

  • Author and date stamps MUST NOT appear.

  • A trailing comment SHOULD be one of these:

    • a short clause after return, break or a one-line statement;

    • a label on a constant or member;

    • the reason for a catch (...) {}.

  • A trailing comment MUST NOT be column-aligned.

12.3 Cross-references and tickets#

  • Cross-references and identifiers MUST stay bare, never backticked: functions as computeTotal(), members as Widget::mCount, ovclash_* entry points without ().

  • Backticks MAY wrap only a literal that reads as English (found, nan) or a short snippet; URLs and Jira keys are not used so far.

  • Bug-tracker ticket IDs and merge request, CI job or pipeline numbers MUST NOT appear; explain the behavior instead and put the identifier in the commit message and the merge request description.

#include <cstddef>
#include <string>

// Rejects the batch before any allocation, so a malformed request cannot leave a half-built
// Widget behind -- the retry path reuses the same Widget.
bool validateBatch(const Batch& batch, std::string& error);
constexpr size_t kMaxItems = 4096u; // Hard limit of the on-disk header.

13. Preprocessor#

13.1 Directive layout#

  • # MUST sit in column 0 with one space after the keyword and none before (. Nested directives indent 4 spaces per level after the hash.

  • No blank line after #if, around #else/#elif or before #endif, save the padded file-scope fence around whole functions; #else MUST NOT be annotated.

  • #endif is bare or tagged // MACRO, one style per file and always tagged on a feature fence.

  • Only a file-scope fence around whole functions is padded: a // line naming the macro and one blank line after #if and before #endif.

  • A multi-line macro indents its continuation lines +4 and aligns every \ at column 120.

13.2 Conditions and fallbacks#

  • Test platform, compiler and feature macros with #if defined(X), save the __cplusplus fence of section 16.1 and the #ifndef default fallback; legacy: #ifdef, normalized when touched.

  • Test 0/1 build flags by value: #if OVCLASH_FEATURE_ENABLED.

  • Spell platform conditions in full and identically at every site. A project alias for them is not used so far and SHOULD NOT be introduced.

  • #ifndef X / #    define X 0 / #endif serves default fallbacks only (version macros, NOMINMAX, WIN32_LEAN_AND_MEAN). Build-injected flags get no fallback; a header that needs one uses #error.

13.3 Platform and feature fences#

  • Fence only the lines that differ; fence a whole body only when both implementations differ end to end. The POSIX branch is a plain #else; elsewhere add #else only for a substitute.

  • Every artifact of an optional feature stays inside #if defined(OVCLASH_<FEATURE>). Fence only the hook lines between production statements; begin/end pairs use RAII.

  • A statement or signature MUST NOT be duplicated under #else.

  • To run a hook just before a statement, splice it in with the comma operator: hook(), alone on a fenced line, then the statement at +4 after #endif. The comma operator is not otherwise used so far.

  • Fence feature-only trailing parameters after the last unconditional item.

13.4 Macros, pragmas and guards#

  • Macros MUST NOT stand in for constants, logic, helpers, asserts, logging or loops: use constexpr variables, inline or template functions, anonymous namespaces and static_assert.

  • Project macros are upper-case OVCLASH_...; vendor macros appear only where an API demands them.

  • Library sources under source/ define only version macros, with their stringify helpers, and the workarounds that this section lists. OVCLASH_EXPORTS comes from the build and OVCLASH_API only from ovclash/ovclash_export.h.

  • Native white-box tests MAY #define a library, PhysX or ovstage symbol to a test double before they include the unit under test, and #undef it right after.

  • Tests MAY define test-local helper macros where a function cannot do the job. Examples are test registration, member-name expanders, a C test’s check macro and POSIX/Windows call aliases (dup to _dup in C). Each stays in the test unit or test header that uses it. Legacy: an unprefixed C++ test macro, prefixed OVCLASH_ when touched.

  • Workarounds live only in UsdPCH.h or around the include that needs them. These are the workarounds:

    • #pragma warning and #pragma GCC diagnostic, each with a matching pop;

    • #pragma comment(lib, ...) for a Windows import library;

    • #undef of a foreign macro;

    • unprefixed NOMINMAX and WIN32_LEAN_AND_MEAN.

  • Every other header carries only #pragma once; a .cpp carries no pragma beyond those workarounds.

  • A private-only header guards itself right after #pragma once: // lines stating the restriction, then #if !defined(OVCLASH_<FLAG>) / #    error <unquoted sentence> / #endif.

14. Modern C++ usage#

ovclash is C++17. Rule strength is marked as the introduction defines; an unmarked sentence states the form in use, and a legacy form is normalized when touched.

14.1 Language level and standard library#

  • C++17 idioms in use: structured bindings for map loops and emplace() results, std::exchange for handle release, std::optional for absent values and _v traits.

  • std:: prefixes every standard name, even C ones (std::memcpy), the bare <cstdint> integer names and size_t of section 14.2 excepted; using-directives follow section 3.4.

  • Bulk work SHOULD use the algorithms.

  • Paths are UTF-8 at the C ABI and in every store. A path MUST reach std::filesystem, a file stream or the operating system only through omni::ovclash::nativePathFromUtf8(), or through suitePathFromUtf8() in the Suite API. It returns to UTF-8 through path.u8string().

  • A public Suite entry point that takes a store or file path checks it with validateSuitePath() first.

  • The narrow std::filesystem::path and fstream constructors and path::string() MUST NOT touch such a path. On Windows they use the ANSI code page, so they name a different file for any non-ASCII path.

14.2 Enums, constants, integers and literals#

  • An enum is enum class with PascalCase enumerators, always qualified (Mode::Insert); its base type and the bit-mask enum : uint32_t form follow section 7.

  • A constant is a kName variable, constexpr or plain const as section 8.1 says; a macro MUST NOT stand in for it. A constexpr function is acceptable where a variable does not fit.

  • Integers are bare <cstdint> names, size_t for sizes and indices, uint64_t for IDs; a size SHOULD NOT be an int.

  • An unsigned literal takes a lowercase u (0u; a bare 0 is legacy).

  • A float literal is 0.0f and a double literal 0.0. Literals MUST NOT be written as 0.f or .5.

  • Null is nullptr; MUST NOT write NULL or 0. Prefer truthiness tests of pointers and handles (if (!p)); p != nullptr is the form when the result is used as a value.

14.3 Containers and loops#

  • Prefer std::vector and std::unordered_map/unordered_set; std::map only for ordered output. std::set is used for ordered directory entries; std::deque and std::list are acceptable where their access and allocation behavior fits.

  • A push_back loop of known size SHOULD be preceded by reserve(n).

  • emplace_back is the form for multi-argument construction; push_back otherwise.

  • Loops are range-for (section 11); filter with erase-remove and dedupe with std::unique.

14.4 Casts, ownership and class rules#

  • Casts are named: static_cast for numeric, enum and pointer conversions, reinterpret_cast only for bytes, const_cast only on a C-ABI handle. MUST NOT write (T)x, except (void)param;.

  • An owned heap object is a std::unique_ptr from std::make_unique; a shared immutable payload is a std::shared_ptr<const T>.

  • Raw new SHOULD appear only in:

    • a C-ABI factory, freed in the matching *_release or Suite *_destroy (section 16.3); where the body can still fail after the allocation, a std::unique_ptr holds the object until *out = p.release();;

    • a never-destroyed function-local static that must stay usable during static destruction;

    • a pimpl constructor;

    • an array that a std::unique_ptr<T[]> takes at once, where std::make_unique would value-initialize it first.

  • Native tests also use raw new for a facet that std::locale adopts and for a C handle or payload that the test hands to the code under test. Other code SHOULD NOT own a raw pointer. malloc and calloc appear only in tests so far.

  • std::move a local on its last use into a container, member or out-parameter; a callable is an F&& parameter, std::forwarded once. SHOULD NOT write return std::move(local).

  • Constructors, overriders and owners follow section 9. A custom move is noexcept (section 14.5). Otherwise follow the rule of zero (SHOULD).

14.5 Errors, cleanup and concurrency#

  • String parameter types follow section 8 and error channels section 15.

  • noexcept marks code running while unwinding or across a callback ABI (guards, deleters, moves), whose body wraps fallible calls in a one-line try { x; } catch (...) {} (section 4.1); MUST NOT mark an extern "C" entry.

  • Scope-exit cleanup is the RAII guard struct of section 9.4, declared Name guard{ args };; a ScopeGuard template is not used so far.

  • Cleanup SHOULD NOT be repeated on every early return, nor reached by goto (section 11.2).

  • std::atomic<T> is accessed via .load(), .store(), .fetch_add() and .exchange(), with an explicit memory order in threaded code: relaxed for stop flags and counters, release/acquire for publication, acq_rel for an RMW handoff.

  • A mutex is locked as std::lock_guard<std::mutex> lock(m); (section 11.4); std::unique_lock serves only a condition-variable wait or a deferred lock.

15. Error handling and the C ABI boundary#

15.1 Error channels#

  • Each layer uses one error channel:

    • engine and backend return bool and fill std::string& error instead of throwing;

    • a C API handle sets last_error via setError(why) or setCapiErrorAndFail;

    • the Suite calls setError(why) and returns false;

    • utilities and serializers throw to the guard.

  • Check each step immediately (if (!step(x, error)) return false;), third-party C status too.

  • The first failure stays primary: cleanup errors land in a scratch string, promoted if ok holds.

  • Cancellation drops partial state and returns false without setError; loops poll checkCancelled().

15.2 Exceptions#

  • Throw standard exception types:

    • std::invalid_argument for bad input;

    • std::logic_error or std::out_of_range for a broken invariant;

    • std::length_error or std::overflow_error for an exceeded size or numeric range;

    • std::system_error for an operating-system error code;

    • std::bad_alloc for a null C allocation;

    • std::runtime_error otherwise.

  • A local tag type serves only control flow, such as forcing a std::call_once retry. Native tests define their own exception types to inject failures.

  • Catch by const& or (...); SHOULD NOT catch by value.

  • Report an exception once:

    • Behind an error channel, catch (const std::exception& exception) and then catch (...) each fill error and return false.

    • Elsewhere, an Allman catch (...) block undoes the partial work and rethrows with a bare throw;.

  • Swallowing an exception SHOULD be confined to noexcept destructors and release helpers.

  • noexcept frames (thread bodies, C callbacks, destructors, release helpers, error reporters) MUST NOT throw: keep the first exception, join every worker, rethrow.

  • Parallel bodies SHOULD NOT call setError.

15.3 Error messages and diagnostics#

  • An error message is one present-tense clause without trailing punctuation; detail follows : , a remedy ; .

  • Open with the identifier concerned (ovclash_<fn>: ..., a setting name, ovstage ...) or with Failed to, Invalid, Missing, Unable to, Unknown.

  • Build messages with + and std::to_string; use a std::ostringstream only where a number needs a fixed precision.

  • Backend diagnostics are std::printf lines under if (enableLog()); a logging framework, std::cout and CARB_LOG are not used so far.

  • Assertions follow section 11.4.

15.4 The C ABI guard#

  • An exported status function MUST delegate directly to its private operation. The forwarding wrapper performs no other work.

  • The operation’s fallible body runs inside a noexcept guard that carries the public function’s name. The guard turns an escaping exception into the returned status. The ovstage backend uses capiResultGuard("<fn>", context, [&]() -> bool { ... }) (section 10.3); the Suite uses suiteGuard.

  • Return kSuccess/kError or suiteResult(bool) rather than brace literals.

  • Order the body: silent null check, rejectWhileAsyncActive, validation, then the work.

  • Validate before touching a resource: C strings !p || !p[0], prim paths p[0] != '/', enum range, indices.

  • Leave no partial out-data: set sentinels or defaults at entry, or write outputs only on success.

This operation body of an ovstage backend unit uses the backend’s own capiResultGuard() and setCapiErrorAndFail(), which source/OvstageClashBackendInternal.h declares. It sits in a function of a unit that includes that header and <cstdint>:

return capiResultGuard("ovclash_count_items", widget, [&]() -> bool {
    if (!widget || !out_count) return false;
    if (!widget->stage) return setCapiErrorAndFail(widget, "ovclash_count_items", "Missing stage");
    *out_count = static_cast<uint32_t>(widget->items.size()); // Written only after every check passes.
    return true;
});

16. Public API headers#

The public headers are the shipped C ABI, in its canonical and Suite layers. They follow the sections from section 1 to section 15 except where this section says otherwise (the files compile as C, feed Doxygen and ship verbatim in the SDK archive). A private C++ convenience class over the C ABI is not installed; section 16.3 ends with its conventions.

16.1 Header structure, includes, export macros and preprocessor#

File skeleton#

  • A header MUST open with its section 1.2 notice (the SPDX pair for a new header), a blank line, #pragma once (the only guard) and a blank line.

  • File-purpose prose belongs in the Doxygen group block, not in the SPDX block.

  • Every header but the macro-only ovclash/ovclash_export.h MUST hold exactly one extern "C" fence. It opens as #ifdef __cplusplus / extern "C" / { / #endif after the includes. In ovclash/ headers it opens after the shared type definitions; the OVCLASH_STANDALONE DLPack types of ovclash/ovclash.h sit inside it. It closes at the end of the file as #ifdef __cplusplus / } / #endif; only a closing /** @} */ MAY follow. Its contents sit at column 0 (unlike section 4).

Includes#

  • Includes MUST form three groups, one blank line between them:

    • project headers, quoted with the install-root prefix: ovclash/ovclash_export.h first, then siblings in dependency order.

    • C standard headers in C spelling (<stdint.h>, never <cstdint>), alphabetical.

    • producer-owned headers in angle brackets, last, in the canonical header only.

  • An extension header MAY take ovclash/ovclash_export.h through its base header.

Export macro, entry points and defines#

  • ovclash/ovclash_export.h MUST define OVCLASH_API once, inside #if !defined(OVCLASH_API); the Suite reuses it.

  • Other files MUST NOT write #define OVCLASH_API, __declspec or __attribute__((visibility(...))). A native test that builds its own shared library is the exception.

  • Every entry point MUST start at column 0 as OVCLASH_API <return_t> ovclash_name( on one line, never decorated with extern, __declspec or __attribute__. Legacy: an ovclash_suite/ prototype with OVCLASH_API <return_t> alone on the line above its name.

  • Types and members carry no macro; the C++ class is class OVCLASH_API Widget and its definitions omit the macro.

  • A hand-written header MUST hold no other #define: constants are enumerators, version macros live only in the generated version header. The one exception is the uint64_t capability bit OVCLASH_OVSTAGE_CAP_AUTHORED_TRANSFORM_UPDATES in ovclash/ovclash_ovstage.h.

  • A hand-written header SHOULD hold no static_assert; asserts go in the .cpp.

Preprocessor layout#

  • __cplusplus fences and short cascades close with bare #endif.

  • Unlike section 13, nested directives indent 4 spaces per level before the #, top level and fenced content at column 0, #else/#elif/#endif at the #if level; never #    define.

Spacing and prototype layout#

  • The one-blank-line rule of section 4 also separates documented prototypes and multi-line types; opaque typedef lines pack.

  • A prototype within 120 columns stays on one line.

  • A longer prototype breaks after ( and indents the parameters 4 spaces: on one line if they fit, else one per line. ); is glued to the last parameter.

  • Legacy, tolerated as is: first parameter on the signature line, others aligned under it. The two forms MUST NOT mix.

In a public header such as ovclash/ovclash.h, which includes ovclash/ovclash_export.h for OVCLASH_API and declares ovclash_result_t, the two layouts read:

OVCLASH_API ovclash_result_t ovclash_scale_widget(ovclash_widget_t* widget, float factor);

OVCLASH_API ovclash_result_t ovclash_create_widget(
    const ovclash_widget_desc_t* desc, ovclash_allocator_t* allocator, ovclash_widget_t** out_widget);

16.2 Doxygen documentation#

Placement and comment form#

  • Doxygen lives only in the shipped public headers.

  • Every exported prototype MUST carry a /** ... */ block directly above it, nothing in between.

  • Write /** alone on its line, * before each body line and */ alone. A one-line /** Sentence. */ serves typedefs and enum briefs; a one-line /** \param name ... */ serves a one-parameter ovclash_suite/ function. An ovclash/ function always takes the full block of ovclash/ block layout.

  • A block MUST NOT use ///, //! or text on the /** line. A member or enumerator MAY carry a trailing //!< (ovclash/ovclash.h) or /**< (ovclash/ovclash_ovstage.h) comment.

  • Legacy: a multi-line block with text on the /** line, moved to its own line when touched.

  • ovclash/ headers write @ commands and ovclash_suite/ headers \ commands; the two MUST NOT mix, except in the /** @{ */ and /** @} */ brackets.

ovclash/ block layout#

  • Block order MUST be @brief (one sentence), prose, one @param per argument in signature order, @return on every function, then @note Label: lines.

  • @note labels are Errors, Lifetime, Side effects, Preconditions, Results, Ordering, Floating point and Device; Threading: is mandatory and MUST come last. Legacy: an unlabeled @note or a qualified label (Lifetime (ovstage):), labeled when touched.

  • @param name [in], [out] or [in,out]: the direction MUST follow the name, not @param[in].

  • A handle is [in] even when the call mutates it.

  • Besides the tags of these layout rules, the headers use @defgroup / \defgroup with @{ / @}, and @ingroup and @p in ovclash/, and \code / \endcode and \name in ovclash_suite/. @see, @ref, @warning, @deprecated, @since, @retval, @returns, @details, @pre, @post, @tparam, @file, @copydoc, [[deprecated]] and their \ equivalents are not used so far.

/**
 * @brief Drops every item stored in a widget while keeping the widget alive.
 *
 * @param widget [in] Widget from ovclash_create_widget. Mutated by this call. Must not be null.
 * @return Result with status OVCLASH_STATUS_SUCCESS, or OVCLASH_STATUS_ERROR when widget is null.
 *
 * @note Threading: serialize all calls on one widget.
 */

ovclash_suite/ block layout#

  • The first sentence is the brief; \param name carries no direction.

  • Outputs are out_*; an optional \return comes last.

  • Functions carry no \note. The shared Preconditions:, Side effects:, Ownership: and Threading: paragraphs and the error catalog live once in the group preamble. A function block repeats such a paragraph, an Error behavior: paragraph or an Example: with \code only for detail of its own.

Wording#

  • Briefs are third-person present, or a noun phrase for a type.

  • Every description is a capitalized sentence ending in a period.

  • References MUST be bare identifiers: no backticks, @ref or name(). Backticks MAY wrap a literal (.clashDetection). Legacy: an ovclash/ reference written as name() or as a backticked field, made bare when touched.

  • Null: Must not be null., May be null. or May be null only when <count> is 0.; MUST NOT write nullptr.

  • Ownership: a view is borrowed; inputs are copied unless documented as borrowed. Name the owner (library-owned), validity (valid until <event>) and disposal (free with <fn>).

  • Threading: ovclash/ writes serialize all calls on one <handle>, the Suite thread-compatible; MUST NOT write thread-safe.

16.3 Naming, types, enums, structs and the C++ class header#

C names#

  • A public C type is ovclash_<snake>_t, ovclash_suite_<snake>_t or ovclash_ovstage_<snake>_t; the tag repeats the typedef name, never an anonymous typedef struct {. An opaque handle is the one-line typedef struct ovclash_widget_t ovclash_widget_t;, body only in sources, never void*.

  • Functions are verb-first snake_case: ovclash_<verb>_<object> (ovclash_get_widget_count), backend ovclash_ovstage_<verb>_<object>, Suite ovclash_suite_<verb>_<object> or handle-first ovclash_suite_<handle>_<verb>[_<field>]. Lifetime: create/release, Suite create/destroy.

  • An enumerator is <STEM>_<VALUE> in SCREAMING_SNAKE_CASE, STEM being the typedef name upper-cased without _t (OVCLASH_WIDGET_MODE_FAST); every enumerator of a new enum has an explicit value.

  • A struct field or parameter is snake_case (samples_per_frame), never the C++ m prefix.

  • A field that counts the elements of a pointer is nb_<x>, right before that pointer. A count parameter is <items>_count. Neither uses num_.

  • Legacy, kept for source compatibility: ovclash/ovclash.h keeps the engine’s camelCase fields and parameters, including uint32_t nb<X> counts and written pointers without out_. Its newer declarations are snake_case.

Enum and struct layout#

  • Enum layout: typedef enum <name>_t, { alone on its line, one enumerator per line at 4 spaces, then } <name>_t;, no trailing comma (legacy: a trailing comma, removed when touched).

  • Some ovclash/ enums must keep out-of-range input representable until the API validates it. Such an enum adds a C++-only fixed base between the name and {: an indented : uint32_t line inside #ifdef __cplusplus / #endif.

  • A flag enum uses (1 << n). An invalid marker is a last <STEM>_UNDEFINED = 0x7fffffff. _COUNT, _MAX and _LAST markers are not used so far.

  • Struct layout: typedef struct <name>_t, Allman {, one type name; per line at 4 spaces, star on the type, } <name>_t;; never K&R braces.

  • Structs are flat: nested structs and reserved or padding fields are not used so far. A versioned struct that must grow compatibly opens with a uint64_t struct_size field.

Parameters and ABI scalars#

  • Every pointer a function writes is a trailing out_<noun>, a new handle a T** out_<noun>; an input array is the adjacent pair const T* <items>, size_t <items>_count.

  • A status-returning entry point returns ovclash_result_t or ovclash_suite_result_t by value, never void; every other struct input is const T*.

  • ABI scalars:

    • uint32_t for nb_<x> counts, indices, flags, modes, enum-valued fields and every Suite boolean;

    • int64_t for persistent ids (-1 = unsaved); uint64_t for hashes and stage ids;

    • int32_t for a signed selector (axis) and the return code of an ovclash_ovstage_*_fn callback;

    • double for times, matrices and Suite geometry;

    • float for epsilons, tolerances and cutoffs;

    • size_t only for a string length, a char* buffer size or an input-array <items>_count.

  • A C header never uses int, unsigned, long, short, 8/16-bit ints or std:: types; bool (from <stdbool.h>) appears only in the canonical ovclash/ovclash.h, never in a Suite header.

Text, callbacks and constants#

  • Text is a { const char* ptr; size_t length; } span, by value in and a borrowed view out: ovclash_suite_string_t in the Suite API, and in ovclash/ headers ovclash_string_t, an alias of the producer-owned ovx_string_t. const char* exists only as that ptr, except the borrowed const char** out_error diagnostic of an ovstage callback. On-demand text uses the trailing triple char* out_buffer, size_t out_buffer_size, size_t* out_required_size; null/0 queries the size.

  • A callback table puts void* user_data; first and declares each member inline as void (*name)(void*, inputs..., uint32_t* out_success);; only *out_success = 1u reports success (section 8.3).

  • The version and numeric ABI constants are exposed through functions and enums, not macros (section 16.1 names the one exception); no hand-written header includes the generated version header.

  • A sentinel SHOULD be lowercase hex (0xffffffff, no u) or -1; UINT32_MAX and ~0u are not used so far.

The C++ class header#

  • A private C++ wrapper class over the C ABI has no extern "C". It opens namespace omni::ovclash and declares class OVCLASH_API <Name> with out-of-line members (unlike section 9.1) and std::unique_ptr<Impl> mImpl; as its first data member.

  • Its names follow section 7 plus get accessors and Nb counts (getNbWidgets); a fallible call returns bool.

17. Formatter settings#

Reviewers apply this guide by hand. CI checks legal headers, not code layout:

  • repo.bat format --legal-only --verify (./repo.sh on Linux), a command of the repo tool, reports every file whose header differs from the two-line Apache-2.0 SPDX template, without changing files. CI runs the same check, and a mismatch fails it. License headers in Contributing describes the file selection, the other checked file kinds and the yearly header update.

  • repo.bat format --list prints the files that repo format selects.

  • The minimal .clang-format disables layout changes. repo format requires the file even for legal-only checks.

Formatter assistance is optional and follows these rules:

  • A contributor who wants clang-format assistance MUST use settings equivalent to the settings table of this section. The option names are those of clang-format 19.

  • Hand-kept forms win over formatter output: one-line accessor and RAII-guard bodies, one-line try { x; } catch (...) {} plumbing, hand-ordered includes, comment prose wrapped at 100 columns and the public-header layout of section 16.1.

  • A file MUST NOT be reformatted wholesale in an unrelated change.

  • Editors use a 4-space indent, UTF-8, LF line endings, trimmed trailing whitespace, one final newline and a 120-column limit.

Option

Setting

Note

BreakBeforeBraces

Custom

Allman: BraceWrapping.After*, .BeforeElse, .BeforeCatch, .SplitEmptyFunction all true.

BraceWrapping.BeforeLambdaBody, .IndentBraces

false

Lambda { stays on the introducer line; braces sit at the statement column.

IndentWidth, ContinuationIndentWidth

4

Four spaces per level and per continuation; no tabs (UseTab Never).

AccessModifierOffset

-4

public: at the class column.

NamespaceIndentation, FixNamespaceComments

None, true

Bodies flush left, closed by } // namespace omni::ovclash; IndentExternBlock Indent (+4).

IndentCaseLabels, IndentCaseBlocks

false

case at the switch column.

ColumnLimit

120

Hard line limit; comment prose is hand-kept at 100 columns.

AlignAfterOpenBracket

Align

Wrapped parameters and arguments align under the first, or break after ( and indent +4.

BinPackParameters, BinPackArguments

false

Aligned parameters one per line; after a break at ( they MAY share one line (section 5.3); wrapped arguments one per line or all on one +4 line, never packed across lines.

BreakBeforeBinaryOperators, BreakBeforeTernaryOperators

None, false

Operators, ? and : end the line; << chains, ./-> member-call chains and a constructor initializer : lead with the operator (section 5.2), hand-kept.

PackConstructorInitializers, BreakConstructorInitializers

BinPack, BeforeColon

On the signature line when it fits, else bin-packed on a +4 line starting : a(x), b(y).

AllowShortIfStatementsOnASingleLine

WithoutElse

One-line guard if (!ptr) return false;; never with else.

AllowShortBlocksOnASingleLine

Empty

catch (...) {} on one line, never if (c) { stmt; }; one-line try/catch hand-kept.

AllowShortFunctionsOnASingleLine

None

Allman body even for one statement; one-line accessor and RAII-guard bodies hand-kept.

AllowShortLoopsOnASingleLine, AllowShortCaseLabelsOnASingleLine, AllowShortEnumsOnASingleLine

false

Loop, case and enum bodies on their own lines.

SpaceBeforeParens

ControlStatements

Exactly one space in if (, for (, while (, switch (, catch (; calls and casts as f(x).

PointerAlignment

Left

T* p, T& r, T&& r bound to the type; DerivePointerAlignment false.

Cpp11BracedListStyle, SpaceBeforeCpp11BracedList

false

Widget{ a, b }, = { 1, 2 }, empty {}.

AlignConsecutiveAssignments, AlignConsecutiveDeclarations

None

Single spaces only, no column alignment; AlignTrailingComments false.

MaxEmptyLinesToKeep, SeparateDefinitionBlocks, KeepEmptyLines.AtStartOfBlock

1, Always, false

One blank line between definitions; never two in a row; none directly after {.

IndentPPDirectives

AfterHash

Nested directives indent 4 spaces after the # (section 13.1); public headers indent before it (section 16.1), hand-kept.

SortIncludes, IncludeBlocks

Never, Preserve

Include groups and their order are hand-kept.

Standard

c++17

Nested namespace definitions and other C++17 forms.