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
caselabels 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.elseMUST 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 oncein 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; enumeratorsKind::Solid; functions verb-firstcomputeTotal().Locals, parameters and plain-struct fields
rowCount; class membersmCount; constantskMaxItems.C-ABI fields and parameters snake_case (
nb_items,items_count), except the legacy camelCase names ofovclash/ovclash.h(section 16.3); C-ABI enumeratorsOVCLASH_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 namespaceMUST NOT appear at global scope.Constants are plain
constexprkNamevariables, never macros;constgoes 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 andsize_tcarriesstd::.Counted loops read
for (size_t index = 0u; index < n; ++index); directives sit at column 0 and test#if defined(X).
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
.cppSHOULD 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
.hand.cppfiles 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 onceMUST be a header’s only guard and its first directive, followed by a blank line.#pragma onceMUST NOT appear in a.cpp.#ifndefguards 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 onceand a blank line; in a.cppit follows the blank line after the SPDX pair.
1.4 File names#
File names MUST follow this table;
snake_caseis reserved for the C-ABI units.
Unit |
Name |
Example |
|---|---|---|
C++ header or source |
PascalCase after the main type or topic |
|
Shim for a shadowed include |
The exact path of the include it shadows |
|
C-ABI forwarding unit of an API layer |
|
|
Shipped C-ABI header |
Stable snake_case public include name |
|
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
#includeoutside 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.hcase files where the cases need them.One blank line MUST separate the include block, forward declarations and the rest of the file.
A
.cppMUST open with the header it implements, after"UsdPCH.h"when that leads (Widget.cppincludes"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.
"UsdPCH.h", then the own header, then other project headers alphabetically.Third-party:
<carb/...>,<ovstage/...>,<ovx/...>,<omni/...>, PhysX.C++ standard headers, ASCII-sorted.
<pxr/...>, in headers only; a unit that includes"UsdPCH.h"repeats none of them.Platform-only includes in a
#if defined(_WIN32)/#else/#endiffence (section 13.2).
A feature-gated include sits in its group’s sorted slot inside a column-0
#if defined(OVCLASH_FEATURE)/#include/#endifwith 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 insource/, otherwise by its path fromsource/("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>) andstd::-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>forPATH_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-localstatic(static inlinehelpers 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>foruint32_t) rather than rely on a sibling.A
.cpprelies 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;, orclass X;for a type defined as aclass(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 astd::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>(} // namespacewhen 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 |
|---|---|
|
The engine API and general header-only utilities. |
|
Other header-only helpers and internal types. |
|
Code of the engine validation observer, fenced by |
|
Private types and helpers shared by the ovstage backend units. |
|
Helpers shared by the scene-reader units, the |
|
The private adapter of the opt-in retained source snapshot experiment. |
|
The OVCLASH matrix-decomposition mode, ovclash’s own decomposition math. |
|
Native test code, and the code of Sentinel, the correctness campaign. |
A global |
Helpers shared by the units of one native test executable, which its global allocator replacement and |
A foreign namespace ( |
Only to declare or define a stand-in for a foreign symbol. |
Global scope |
C entry points and |
Legacy: a camelCase test namespace, renamed when touched.
A library
.cppMUST reopen onlyomni::ovclash, or a foreign namespace for a stand-in, and writedetail::x/validation::xinside it. A unit that defines declarations ofdetail::ovstageorscene_reader_detailMAY 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::ovclashfunctions 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 shippedovclash/headers. A private export that no shipped header declares carriesextern "C" OVCLASH_APIon its definition.The Suite export unit holds includes followed by one
extern "C"block of forwardingovclash_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
.cppMUST live in one unnamed namespace right after the includes and forward declarations (section 2.4). Namespace aliases follow section 3.4.staticMUST 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
inlinein the internal header. Chooseinlinewhen 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 namespaceandPXR_NAMESPACE_USING_DIRECTIVEMUST 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_SCOPEMUST 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,tryandcatchMUST be Allman, even when the condition wraps; the one-linetry { x; } catch (...) {}swallow of section 14 is the exception.elseandcatchstart 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-linethrowor one short guarded statement.Brace it once the condition or statement wraps, nests a control statement or gains an
else.elseMUST 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#
caseanddefaultlabels sit at theswitchcolumn 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;orreturnand everyswitchSHOULD have adefault:; aswitchwithoutdefault: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
namespacebody adds none.Access specifiers sit at the
classcolumn,caselabels at theswitchcolumn, 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 undera.
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, ortype 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 aftersuiteGuard(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 *pMUST 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
forsemicolon 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 |
|
|
Function, method, lambda, local, C++ parameter |
|
|
Data member of a class with |
|
|
Field of a plain aggregate that no other row covers; legacy engine field of |
|
|
Field of an |
|
|
Constant at namespace or class scope; local |
|
|
File-scope global, |
|
|
RAII helper; hash functor |
|
|
Macro, preprocessor switch, env var, C-ABI enumerator |
|
|
Namespace, namespace alias |
lowercase word; |
|
Public-header C-ABI function, type and out-parameter |
|
|
7.1 Words and spelling#
Words are spelled out (
Index,Count); counts are<noun>Count, nevernum*.Acronyms are cased as words (
Json,Utf8,Id); brand casing only forPhysX.A 1:1 stand-in for an external API SHOULD keep the external spelling (
npos, engineeValue).
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
usingrather thantypedef.Template parameters are role nouns (
RowSink) or genericT.
7.3 Enums and C-ABI handles#
Internal enums are
enum classwith bare PascalCase enumerators (noe,kor ALL_CAPS) and a fixed-width base when stored or serialized.A plain
enum Name : uint32_tSHOULD 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_*_ttypes 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 areout<Camel>, neverout_<snake>on a camelCase helper.erroris the last parameter before defaulted ones.A snake_case local only when forwarding a C-ABI argument or an
ovclash_*_tmember.Role names (SHOULD):
ok,exception,lhs/rhs,it,found,inserted,indexor the counted noun; lookup maps<value>By<Key>; bools are bare adjectives (hidden), never Hungarian.Pair halves are
item0/item1.Legacy:
kon a runtime-initializedstatic const,a/bcomparators,stmt, andi/j/koutside fixed-size math, normalized when touched.
8. Declarations, const, auto and literals#
8.1 Constants, const and inline#
Namespace-scope constants SHOULD be plain
constexprand MUST NOT be#defines.Non-literal types such as
std::stringuse plainconst; class constants arestatic constexpr.constMUST go west of the type (const std::string& s).Make a local
constwhen nothing mutates it after initialization; pointer locals, RAII guards and by-value parameters stay unqualified.Headers hold prototypes,
constexprconstants, templates andinlinefunctions; a non-template free function defined in a header MUST beinline.A header constant MAY be
inline(inline constexprorinline const).staticon a namespace-scope constant is not used so far;static inlineappears only in C-compatible code (section 2.3).
8.2 Declarations, auto and initialization#
Prefer spelled-out local types;
autois 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
ifcondition tests a pointer orstd::shared_ptrresult (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 zeroingmemsetis legacy, normalized when touched.Class-type members stay bare; references,
constand 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_tfor anb_<x>field or an index,size_tfor an input-array<items>_countor 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:
uon unsigned values and flag tests (= 0u,1u << N),fon floats (1.0e-12f); doubles carry a point and no suffix (0.0). Byte sizes derive fromsizeof; a C array’s element count isstd::size(table)(legacy:sizeof(a) / sizeof(a[0]), normalized when touched).Sentinels SHOULD be spelled by name (
std::string::npos,kNoSlot). A missinguint32_tindex is0xffffffffu, and a missing signed id is-1.ABI booleans MUST be exactly
0uand1u.A single string constant SHOULD be
constexpr const char* kName = "...";; the array form is acceptable whensizeof(kName) - 1uor 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"), awmainargument).
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 asconst T*; a Suite boolean MUST beuint32_t, notbool.A string parameter SHOULD be
const std::string&internally;std::string_viewis 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;classonly when aprivate:section hides state behind bare-nounconstaccessors.Not used so far:
friendand 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::methodin a header,inlineor 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 oneprivate:label follows after one blank line. Labels sit at theclasscolumn, members one level deeper.Class order: aliases, nested types and
kconstants; the ctor/dtor/= deletegroup; methods;private:helpers and data.Struct order: constants, data, special members, methods.
A C-ABI handle MUST be a
struct ovclash_*_tmatching 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()orrelease()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_ptris not used so far.A scope guard is an all-public struct named as section 7 prescribes (
WidgetGuard), holding the retired reference, abool keepflag or a disarmingrelease(), and a destructor that never throws.
9.5 Members, virtuals and operators#
Every non-mutating member MUST be
const;mutableonly for a cache or a mutex.staticmember functions SHOULD be limited to stateless helpers or factories; mutable static data SHOULD NOT be used.virtualSHOULD be limited to callback and abstract collaborator interfaces, such as serializers.An overrider MUST say
override(legacy: barevirtual, normalized when touched).In use:
finalon concrete serializer, cursor and bulk-writer implementations;[[nodiscard]]on a fallible internal helper whose result must be checked;dynamic_castonly 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::hashspecializations are not written so far.
10. Templates and lambdas#
10.1 Templates#
template <typename Body>MUST go on its own line; writetypename, notclass.Templates are unconstrained (C++17 has no concepts);
if constexpr, SFINAE, specializations and CTAD are acceptable where they fit.static_assertSHOULD be reserved for invariants (ABIsizeof, enum-value equality).Let template arguments deduce; spell them only when deduction fails (
std::make_unique<Widget>) orstd::min/std::maxmix 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_thandles of the ovx headers and of ovstage;pointers and
pxr::SdfPath;small key structs with a member
==and a<X>Hashfunctor.
A
std::hashspecialization 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::functionis 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
capiResultGuardor a row-consumer template MUST spell-> bool. The OpenUSD backend’scapiResultGuardbody spells-> ovclash_result_tand returnskSuccessorkError. AsuiteGuardbody MUST spell-> ovclash_suite_result_t(legacy: deduced, normalized when touched).Elsewhere spell
-> Tonly for a reference return, a fixed width or a named multi-statementboolstep.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/rhsand tests its keys in priority order, one guard per key, ending in an unconditionalreturn;std::tieis 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 byelse.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 : falseand== trueSHOULD NOT be used.Test pointers by truthiness, containers by
.empty(), andfindresults againstnposor.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 throughauto&, 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 bare0initializer, normalized when touched.Skip an item with a
continue;guard at the top of the body and leave on a decisive state withbreak;. The rest of the body SHOULD NOT be wrapped inelseinstead.Prefer
for (;;)for an unbounded loop;while (true)is acceptable in the samples.A
do-whileserves 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 withbreak;.gotoSHOULD 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/elseor parenthesize.Dispatch on an enumerator, char or small code with
switch; layout anddefault:follow section 4.3.Ranges and string tests use
if/else ifchains 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_assertover runtimeassert;assertis 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 0and 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
// Helperslabels.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)paramuncommented.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,breakor 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 asWidget::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/#elifor before#endif, save the padded file-scope fence around whole functions;#elseMUST NOT be annotated.#endifis 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#ifand 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__cplusplusfence of section 16.1 and the#ifndefdefault 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/#endifserves 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#elseonly 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
constexprvariables,inlineor template functions, anonymous namespaces andstatic_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_EXPORTScomes from the build andOVCLASH_APIonly fromovclash/ovclash_export.h.Native white-box tests MAY
#definea library, PhysX or ovstage symbol to a test double before they include the unit under test, and#undefit 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 (
dupto_dupin C). Each stays in the test unit or test header that uses it. Legacy: an unprefixed C++ test macro, prefixedOVCLASH_when touched.Workarounds live only in
UsdPCH.hor around the include that needs them. These are the workarounds:#pragma warningand#pragma GCC diagnostic, each with a matching pop;#pragma comment(lib, ...)for a Windows import library;#undefof a foreign macro;unprefixed
NOMINMAXandWIN32_LEAN_AND_MEAN.
Every other header carries only
#pragma once; a.cppcarries 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::exchangefor handle release,std::optionalfor absent values and_vtraits.std::prefixes every standard name, even C ones (std::memcpy), the bare<cstdint>integer names andsize_tof 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 throughomni::ovclash::nativePathFromUtf8(), or throughsuitePathFromUtf8()in the Suite API. It returns to UTF-8 throughpath.u8string().A public Suite entry point that takes a store or file path checks it with
validateSuitePath()first.The narrow
std::filesystem::pathand fstream constructors andpath::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 classwith PascalCase enumerators, always qualified (Mode::Insert); its base type and the bit-maskenum : uint32_tform follow section 7.A constant is a
kNamevariable,constexpror plainconstas section 8.1 says; a macro MUST NOT stand in for it. Aconstexprfunction is acceptable where a variable does not fit.Integers are bare
<cstdint>names,size_tfor sizes and indices,uint64_tfor IDs; a size SHOULD NOT be anint.An unsigned literal takes a lowercase
u(0u; a bare0is legacy).A float literal is
0.0fand a double literal0.0. Literals MUST NOT be written as0.for.5.Null is
nullptr; MUST NOT writeNULLor0. Prefer truthiness tests of pointers and handles (if (!p));p != nullptris the form when the result is used as a value.
14.3 Containers and loops#
Prefer
std::vectorandstd::unordered_map/unordered_set;std::maponly for ordered output.std::setis used for ordered directory entries;std::dequeandstd::listare acceptable where their access and allocation behavior fits.A
push_backloop of known size SHOULD be preceded byreserve(n).emplace_backis the form for multi-argument construction;push_backotherwise.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_castfor numeric, enum and pointer conversions,reinterpret_castonly for bytes,const_castonly on a C-ABI handle. MUST NOT write(T)x, except(void)param;.An owned heap object is a
std::unique_ptrfromstd::make_unique; a shared immutable payload is astd::shared_ptr<const T>.Raw
newSHOULD appear only in:a C-ABI factory, freed in the matching
*_releaseor Suite*_destroy(section 16.3); where the body can still fail after the allocation, astd::unique_ptrholds 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, wherestd::make_uniquewould value-initialize it first.
Native tests also use raw
newfor a facet thatstd::localeadopts and for a C handle or payload that the test hands to the code under test. Other code SHOULD NOT own a raw pointer.mallocandcallocappear only in tests so far.std::movea local on its last use into a container, member or out-parameter; a callable is anF&¶meter,std::forwarded once. SHOULD NOT writereturn 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.
noexceptmarks code running while unwinding or across a callback ABI (guards, deleters, moves), whose body wraps fallible calls in a one-linetry { x; } catch (...) {}(section 4.1); MUST NOT mark anextern "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:relaxedfor stop flags and counters,release/acquirefor publication,acq_relfor an RMW handoff.A mutex is locked as
std::lock_guard<std::mutex> lock(m);(section 11.4);std::unique_lockserves 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
booland fillstd::string& errorinstead of throwing;a C API handle sets
last_errorviasetError(why)orsetCapiErrorAndFail;the Suite calls
setError(why)and returnsfalse;utilities and serializers
throwto 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
okholds.Cancellation drops partial state and returns
falsewithoutsetError; loops pollcheckCancelled().
15.2 Exceptions#
Throw standard exception types:
std::invalid_argumentfor bad input;std::logic_errororstd::out_of_rangefor a broken invariant;std::length_errororstd::overflow_errorfor an exceeded size or numeric range;std::system_errorfor an operating-system error code;std::bad_allocfor a null C allocation;std::runtime_errorotherwise.
A local tag type serves only control flow, such as forcing a
std::call_onceretry. 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 thencatch (...)each fillerrorandreturn false.Elsewhere, an Allman
catch (...)block undoes the partial work and rethrows with a barethrow;.
Swallowing an exception SHOULD be confined to
noexceptdestructors and release helpers.noexceptframes (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 withFailed to,Invalid,Missing,Unable to,Unknown.Build messages with
+andstd::to_string; use astd::ostringstreamonly where a number needs a fixed precision.Backend diagnostics are
std::printflines underif (enableLog()); a logging framework,std::coutandCARB_LOGare 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
noexceptguard that carries the public function’s name. The guard turns an escaping exception into the returned status. The ovstage backend usescapiResultGuard("<fn>", context, [&]() -> bool { ... })(section 10.3); the Suite usessuiteGuard.Return
kSuccess/kErrororsuiteResult(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 pathsp[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.hMUST hold exactly oneextern "C"fence. It opens as#ifdef __cplusplus/extern "C"/{/#endifafter the includes. Inovclash/headers it opens after the shared type definitions; theOVCLASH_STANDALONEDLPack types ofovclash/ovclash.hsit 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.hfirst, 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.hthrough its base header.
Export macro, entry points and defines#
ovclash/ovclash_export.hMUST defineOVCLASH_APIonce, inside#if !defined(OVCLASH_API); the Suite reuses it.Other files MUST NOT write
#define OVCLASH_API,__declspecor__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 withextern,__declspecor__attribute__. Legacy: anovclash_suite/prototype withOVCLASH_API <return_t>alone on the line above its name.Types and members carry no macro; the C++ class is
class OVCLASH_API Widgetand 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 theuint64_tcapability bitOVCLASH_OVSTAGE_CAP_AUTHORED_TRANSFORM_UPDATESinovclash/ovclash_ovstage.h.A hand-written header SHOULD hold no
static_assert; asserts go in the.cpp.
Preprocessor layout#
__cplusplusfences 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/#endifat the#iflevel; 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-parameterovclash_suite/function. Anovclash/function always takes the full block ofovclash/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 andovclash_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@paramper argument in signature order,@returnon every function, then@note Label:lines.@notelabels areErrors,Lifetime,Side effects,Preconditions,Results,Ordering,Floating pointandDevice;Threading:is mandatory and MUST come last. Legacy: an unlabeled@noteor 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/\defgroupwith@{/@}, and@ingroupand@pinovclash/, and\code/\endcodeand\nameinovclash_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 namecarries no direction.Outputs are
out_*; an optional\returncomes last.Functions carry no
\note. The sharedPreconditions:,Side effects:,Ownership:andThreading:paragraphs and the error catalog live once in the group preamble. A function block repeats such a paragraph, anError behavior:paragraph or anExample:with\codeonly 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,
@reforname(). Backticks MAY wrap a literal (.clashDetection). Legacy: anovclash/reference written asname()or as a backticked field, made bare when touched.Null:
Must not be null.,May be null.orMay be null only when <count> is 0.; MUST NOT writenullptr.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/writesserialize all calls on one <handle>, the Suitethread-compatible; MUST NOT writethread-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>_torovclash_ovstage_<snake>_t; the tag repeats the typedef name, never an anonymoustypedef struct {. An opaque handle is the one-linetypedef struct ovclash_widget_t ovclash_widget_t;, body only in sources, nevervoid*.Functions are verb-first snake_case:
ovclash_<verb>_<object>(ovclash_get_widget_count), backendovclash_ovstage_<verb>_<object>, Suiteovclash_suite_<verb>_<object>or handle-firstovclash_suite_<handle>_<verb>[_<field>]. Lifetime:create/release, Suitecreate/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++mprefix.A field that counts the elements of a pointer is
nb_<x>, right before that pointer. A count parameter is<items>_count. Neither usesnum_.Legacy, kept for source compatibility:
ovclash/ovclash.hkeeps the engine’s camelCase fields and parameters, includinguint32_t nb<X>counts and written pointers withoutout_. 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_tline inside#ifdef __cplusplus/#endif.A flag enum uses
(1 << n). An invalid marker is a last<STEM>_UNDEFINED = 0x7fffffff._COUNT,_MAXand_LASTmarkers are not used so far.Struct layout:
typedef struct <name>_t, Allman{, onetype 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_sizefield.
Parameters and ABI scalars#
Every pointer a function writes is a trailing
out_<noun>, a new handle aT** out_<noun>; an input array is the adjacent pairconst T* <items>, size_t <items>_count.A status-returning entry point returns
ovclash_result_torovclash_suite_result_tby value, nevervoid; every other struct input isconst T*.ABI scalars:
uint32_tfornb_<x>counts, indices, flags, modes, enum-valued fields and every Suite boolean;int64_tfor persistent ids (-1= unsaved);uint64_tfor hashes and stage ids;int32_tfor a signed selector (axis) and the return code of anovclash_ovstage_*_fncallback;doublefor times, matrices and Suite geometry;floatfor epsilons, tolerances and cutoffs;size_tonly for a string length, achar*buffer size or an input-array<items>_count.
A C header never uses
int,unsigned,long,short, 8/16-bit ints orstd::types;bool(from<stdbool.h>) appears only in the canonicalovclash/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_tin the Suite API, and inovclash/headersovclash_string_t, an alias of the producer-ownedovx_string_t.const char*exists only as thatptr, except the borrowedconst char** out_errordiagnostic of an ovstage callback. On-demand text uses the trailing triplechar* 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 asvoid (*name)(void*, inputs..., uint32_t* out_success);; only*out_success = 1ureports 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, nou) or-1;UINT32_MAXand~0uare not used so far.
The C++ class header#
A private C++ wrapper class over the C ABI has no
extern "C". It opensnamespace omni::ovclashand declaresclass OVCLASH_API <Name>with out-of-line members (unlike section 9.1) andstd::unique_ptr<Impl> mImpl;as its first data member.Its names follow section 7 plus
getaccessors andNbcounts (getNbWidgets); a fallible call returnsbool.
17. Formatter settings#
Reviewers apply this guide by hand. CI checks legal headers, not code layout:
repo.bat format --legal-only --verify(./repo.shon 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 --listprints the files thatrepo formatselects.The minimal
.clang-formatdisables layout changes.repo formatrequires 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 |
|---|---|---|
|
|
Allman: |
|
|
Lambda |
|
|
Four spaces per level and per continuation; no tabs ( |
|
|
|
|
|
Bodies flush left, closed by |
|
|
|
|
|
Hard line limit; comment prose is hand-kept at 100 columns. |
|
|
Wrapped parameters and arguments align under the first, or break after |
|
|
Aligned parameters one per line; after a break at |
|
|
Operators, |
|
|
On the signature line when it fits, else bin-packed on a +4 line starting |
|
|
One-line guard |
|
|
|
|
|
Allman body even for one statement; one-line accessor and RAII-guard bodies hand-kept. |
|
|
Loop, |
|
|
Exactly one space in |
|
|
|
|
|
|
|
|
Single spaces only, no column alignment; |
|
|
One blank line between definitions; never two in a row; none directly after |
|
|
Nested directives indent 4 spaces after the |
|
|
Include groups and their order are hand-kept. |
|
|
Nested namespace definitions and other C++17 forms. |
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 inovclash/headers also the return.Every public header but the macro-only
ovclash/ovclash_export.hMUST have exactly one#ifdef __cplusplusextern "C"fence, and every C entry point MUST carryOVCLASH_APIfromovclash/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.