Wrapper Maintenance¶
This page is for Kanama maintainers working on generated wrappers, KDoc, or API refreshes. Game projects do not need these commands.
Generator Role¶
The wrapper generator turns Godot's extension_api.json into conservative
Kotlin wrapper drafts. Its job is to scale API coverage without hand-writing
thousands of MethodBind calls, while refusing shapes where Kanama has not
defined ABI, ownership, or marshalling policy yet.
Generated drafts are not automatically promoted. A class only becomes public source after review, smoke coverage where practical, and reproducibility checks against the generator output. This keeps broad wrapper growth auditable instead of relying on one-off manual wrappers.
Refreshing generated Panama bindings from a new Godot API/header set requires
jextract 25+. Normal game projects do not run jextract; it is only part of
Kanama's API/header refresh workflow.
What the generated API promises script authors (names, types, nullability, enums, defaults,
platform parity) is stated rule by rule in
API Conventions. A generator change that alters
a public signature is a source break: scripts/check_public_signature_changes.py fails until a
- **Source break:** line in CHANGELOG.md names the owner of each changed declaration and the
snapshots in api-snapshots/ are regenerated with --write (see
Source Breaks). Additions and source-compatible
changes (a default added) only need --write; every public declaration must state its type.
Working on Wrappers¶
- Check
extension_api.jsonfor method names, hashes, argument metadata and virtual-method flags. - Check the coverage and candidate reports before adding wrappers:
python3 scripts/api_wrapper_coverage.py
python3 scripts/api_wrapper_candidates.py
- Validate the method binds after a wrapper change:
python3 scripts/validate_godot_api.py --api extension_api.json
- Run the ABI, shape and signature audits that cover the change (Wrapper Guardrails).
- Add a smoke row or a compile fixture for a user-visible API addition.
Only add methods whose types have a known ObjectCalls marshal path. A method
that needs a new ABI shape gets the exact helper and its audit coverage first.
Virtual Methods¶
Methods marked "is_virtual": true in extension_api.json are override points
that Godot calls into the extension. They are never generated as normal
ptrcall wrappers, and the generated wrapper classes leave them out. A script
overrides one with @OverrideVirtual: the Kotlin function name is the
virtual's name, GDScript-style, validated against the generated signature
table (scripts/generate_virtual_signature_table.py) and dispatched through
the script-instance layer. The lifecycle callbacks (@OnReady, @OnProcess,
...) ride the same dispatch. The return types a virtual can have, per
platform, are in Virtual-Return Coverage.
Generated and Hand-Written Wrappers¶
Every Godot class is generated from extension_api.json, once, into the shared
tree src/commonMain/kotlin/.../api. That tree is KMP common code: it may name
only common declarations. The platform classes it needs are expects with one
actual per platform, and an expect carries no default argument.
The hand-written exceptions are the roots GodotObject, RefCounted and
GodotCallable (SHARED_HAND_ROOTS in scripts/generate_api_wrapper.py) and
the expect seams. PER_PLATFORM_WRAPPERS in the same file is the home for a
class the two native platforms must host differently, with a reason per entry;
it is empty today (DESKTOP_HANDSHAPED and IOS_HANDSHAPED are views of it).
Keep that table and the generator policy audits current when you move this
boundary: the full drift gate fails otherwise.
Hand-written code under api/ is a budget, not a default: "The hand-code
budget" under Wrapper Guardrails has the rules. Sugar
for a generated class goes into the generator's tables (FACTORY_HELPERS,
SHARED_MEMBER_SECTIONS, ...), not into a hand class, as "Retiring a
per-platform class" in the same section describes.
Sources of the API Conventions¶
Each rule on API Conventions is produced
by generator code, and Gates and Claims lists
the check that holds it. Generator code is in scripts/generate_api_wrapper.py
unless another file is named.
| Rule | Generator code and runtime pieces |
|---|---|
| 1. Names | WRAPPER_CLASS_ALIASES in scripts/wrapper_model.py (Object is GodotObject); camel_name in scripts/api_wrapper_candidates.py and method_function_name; METHOD_NAME_OVERRIDES (closeConnection, waitBlocking, ...); RESERVED_WORDS and arg_name (the Value suffix); PARAMETER_NAME_OVERRIDES (the Time methods); PROPERTY_NAME_OVERRIDES (curveClosed, polygonClosed). |
| 2. Properties | render_property. |
| 3. Integers | SIGNED_INT_POLICIES / UNSIGNED_INT_POLICIES and abi_kind in scripts/wrapper_model.py: the Kotlin Int/Long choice follows Godot's declared meta, while the ptrcall cell is always an 8-byte int64 (see Wrapper Guardrails); render_companion_constants for class constants. |
| 4. Decimals | SCALAR_KOTLIN_TYPES and FLOAT_POLICIES in scripts/wrapper_model.py (a scalar float crosses as a 64-bit double). The component storage is the generated, internal GodotRealStorage (Real.kt, from generateKanamaReal in build.gradle.kts): Godot's real_t, float32 in the default build and float64 with -PkanamaPrecision=double, and float32 for Color. The stored bits cross unchanged through GodotRealSegment.readRaw/writeRaw on desktop and Android and the iOS ObjectCalls packing; the Web bridge passes the widened value, which is exact. real_t formulas: types/shared/RealMath.kt (one source for native and Web), the operators and short methods in types/BuiltinFormulas.kt and types/shared/BuiltinMath.kt. Transcendental results computed in Kotlin on Web are rounded to real_t but not guaranteed to the bit. The engine-computed methods go through an allocation-free call. Engine-checked inputs (Basis.inverse of a singular basis, ...) are computed in Kotlin and the exact input Godot's check rejects is handed to the engine, so the error matches GDScript. There is no Number overload on the value-type constructors: it boxed every argument, a hidden allocation in a per-frame loop. -PkanamaPrecision=double (desktop only) compiles and the JVM tests pass, but it is not supported: the hard-coded 24-byte Variant size and the Rect2 cell size in ObjectCalls assume single precision. |
| 5. Enums and Bitfields | godot_enum_model.render_enum_class, enum_type_ref, kotlin_type (a @JvmInline value class); GLOBAL_ENUM_RENAMES in scripts/godot_enum_model.py; determine_prefix, enum_value_name; the frozen prefixes in scripts/enum_prefix_lock.json, never recomputed (locked_prefixes); kotlin_enum_default_expression for defaults; every enum implements GodotEnumValue, which the Variant encoders pass as its integer. On Web the generated GDScript proxy declares an enum export with @export_custom(<hint>, "<hint string>"), which cannot set class_name; a List of a Godot enum exports with the hint string "2/2:<hint>". |
| 6. Nullability | kotlin_return_type, is_required_return, requireGodotReturn in src/commonMain/kotlin/net/multigesture/kanama/binding/runtime/RequiredReturns.kt; object_param_is_nullable and NULLABLE_OBJECT_PARAM_OVERRIDES (each entry cites the Godot source that accepts null); NON_NULL_FROM_HANDLE_CLASSES (Resource.fromHandle). |
| 7. Ownership | Inside the runtime a RefCounted wrapper class has no wrap, only wrapOwned (a returned or constructing +1) and wrapBorrowed (a view), so every generated and hand-written site states which one it builds; a returned typed Array of RefCounted retains each element before the Array is destroyed after the decode. The closed-wrapper guard is emits_receiver_guard and checkOpen() in the hand root RefCounted; self_return_collapse_wrapper returns this from a fluent method. An owned wrapper registers a cleanup that holds only its handle; close() cancels it, and borrowed views register none. The from* downcasts take their own +1 (RefCounted.retained). A script on a RefCounted owner holds a +1 and its native link is strong above count 1 and weak at 1, C#'s CSharpInstance model; for a plain script class the fallback does not release forgotten wrappers of its owner until the script is detached or the game shuts down. Wrappers made on any thread release on the main thread after the wrapper's last call (ObjectCalls.keepReachable). The @Export resource reads take one reference per value for the property, released on the next engine set or when Godot frees the script instance, also after the garbage collector dropped the script object; a mutable script property releases the previous wrapper before accepting a new value from Godot (PackedScene?, Texture2D?, List<Texture2D>). Error containment reports the top frame of game code, skipping Kanama, generated, Kotlin and JDK frames; on Web the production build names the containment site. |
| 8. Statics and Singletons | render_draft, singleton branch; the singleton list is Godot's (load_api_singletons in scripts/wrapper_model.py). Statics carry no @JvmStatic; singleton members do. GD has one member per Godot utility function (114 at Godot 4.7.2), generated like the classes. |
| 9. Defaults and Overloads | kotlin_default_expression, kotlin_enum_default_expression, KOTLIN_DEFAULT_EXPRESSION_OVERRIDES; parameter_default_expression records the defaults it cannot express for the generator report. An expect declaration (GodotSignal, ...) carries no default argument because the Android build compiles without the expect file. |
| 10. Collections | SCALAR_KOTLIN_TYPES; a method whose types have no audited call shape is skipped (CALL_SHAPES in scripts/api_wrapper_candidates.py). The String and PackedByteArray methods are extension functions in net.multigesture.kanama.builtins; the godot prefix avoids names kotlin-stdlib or java.lang.String already has, because a star import outranks Kotlin's default imports. Text crosses as UTF-8. NodePath members are Godot's parse ported to Kotlin, run lazily (the last parsed path is remembered); hash() runs in the engine. The ByteArray codecs are Godot's, ported (little-endian, Godot's half-float conversion); the string decoders, compression and decodeVar run in the engine. |
| 11. Handles and Factories | Checked casts ask Godot (Object.is_class) every time, also when the wrapper's Kotlin class already matches (only GodotObject is not asked); they are inline reified functions over generated class-token tables (GodotClasses.kt for the shared tree, PlatformGodotClasses.kt per platform; class_token_entries_shared / class_token_entries_platform, render_class_tokens), built from class literals and constructor calls. X.create() is generated for every instantiable Node and RefCounted class and the from* downcasts come from DOWNCAST_HELPERS, both rendered by render_factory_helpers. |
| 12. Names as Constants | render_signal_constants; MethodName, PropertyName and SignalName from scripts/generate_name_constants.py, generated into src/commonMain. |
| 13. Platform Parity | The API tree is common Kotlin code in src/commonMain/kotlin/net/multigesture/kanama/api, compiled by every native target. The platform-bound pieces it names are expect declarations (GodotSignal, SignalConnection, MainThread), and an actual adds no public member its expect lacks. PER_PLATFORM_WRAPPERS lists classes hand-shaped per platform with a reason each (none at present). Members generated for desktop and Android only sit in a <Class>.jvm.kt companion; iOS-only sugar sits in a generated <Class>.ios.kt (IOS_EXTENSION_SECTIONS, for example PhysicsDirectSpaceState3D.intersectRay's nullable-argument form over the raycast C shim). Web is generated by scripts/generate_web_wrappers.py, one file per class under web-runtime/.../api/generated/, with the same enum prefix lock; it renames keyword parameters by table (KEYWORD_RENAMES), and an object parameter's nullability follows the Web contract slot (api_param_type). The web and common snapshots in api-snapshots/ are the authoritative record of both surfaces. |
Wrapper Guardrails¶
Kanama's conservative wrapper generator is intentionally fail-loud. CI checks the generated method shapes against the runtime FFM helpers, including int32/int64 width, float/double layout, packed-array storage, generic Array/Dictionary/Variant policy, and Callable blocking.
Generated public APIs must keep concrete Godot object types concrete. For
example, a Godot Node3D return should render as Node3D?, not
GodotObject, Object, or a raw pointer. The one handle type a public
signature may name is GodotHandle (the opaque wrapper/script handle, task 104). Exact Godot Object APIs remain
dynamic because the engine itself does not promise a more specific type.
Ownership-sensitive namespace-style types use explicit policy before default
generation. Callable stays blocked unless a helper has a bounded ownership
shape. DirAccess and FileAccess are ordinary generated RefCounted classes since task 129 D
(their hand DirAccessHandle / FileAccessHandle aliases are gone; see "FileAccess and DirAccess"
below). (SceneTree had a handle alias,
SceneTreeHandle, until task 117 P1'(b1) generated SceneTree itself into the
shared tree as SceneTree : MainLoop; Node.getTree(): SceneTree? names it directly now.)
The raw engine pointer in the shared sources is RawSegment, never a
java.lang.foreign type (task 104 step 3). It is declared ONCE, in the root
module's KMP common fragment, as
expect sealed interface RawSegment { fun address(): Long } in
src/commonMain/kotlin/net/multigesture/kanama/binding/runtime/RawSegment.expect.kt,
with the null pointer beside it as a top-level expect val NULL_SEGMENT (a Java
static final field cannot actualize an expect companion member). Each platform
actualizes the pair with a typealias — desktop/Android
src/jvmMain/kotlin/binding/runtime/RawSegment.kt to the FFM MemorySegment (the
PanamaPort remap rewrites it to com.v7878.foreign.MemorySegment and strips the
actual modifier), iOS src/iosMain/.../binding/runtime/RawSegment.kt to its
Kotlin/Native shim — so
RawSegment is the platform pointer type and the two spellings interoperate
freely. The generator emits it in the only three shared-tree shapes that name the
pointer at all: internal fun wrap(handle: RawSegment), NULL_SEGMENT for a static
receiver or a null object argument, and a singleton's private inline val singleton:
RawSegment (read from its bind holder, below; by lazy in a singleton with no binds).
MethodBind holders (task 131 item 18). A generated class keeps every MethodBind it
calls in one private object Binds nested in the class (a singleton object's holder
also carries the engine singleton handle), each one a
@JvmField val xBind = ObjectCalls.getMethodBind("Class", "method", HASH), and a
method passes Binds.xBind to its ObjectCalls helper. The holder's class
initialisation is the laziness: it runs on the first call through any method of that
class, so a class no script calls binds nothing and an engine class absent from the
running build is never looked up; after it each bind is a static final field the JIT
folds into the call (the per-method by lazy it replaced cost a Lazy.getValue -- a
volatile read and a cast -- on every call, and one lambda per method at class init:
Bunnymark V3 frames −5 %, example project first frame −16 %). A desktop-only
companion (<Class>.jvm.kt) has a file-level <Class>JvmBinds (a top-level private
object still compiles to a package-level class, so the name must be unique); the iOS
per-platform files keep by lazy. A failed lookup still prints FAULT
bind-lookup-failed <Class>.<method>, now for every bind of the class when its holder is
first used, called or not. With Godot's official editor and export templates no
generated bind is missing (the methods Godot binds only in TOOLS_ENABLED or
DEBUG_ENABLED builds are not in the generated set); in a custom engine built with
deprecated=no, every deprecated bind of a class reports FAULT the first time anything
calls that class, whether or not the deprecated method itself is called. Hand code in a
generator section refers to a generated bind as Binds.xBind.
The holder also changes how a lookup failure surfaces. getMethodBind itself does not
throw (a missing bind is the FAULT line and a null pointer), but if the holder's
initialiser does throw -- only possible before GodotFFI.bootstrap, e.g. a wrapper called
from a unit test with no engine -- the first call fails with ExceptionInInitializerError
and every later call through that class with NoClassDefFoundError, where the by lazy
retried on each call. Within a running engine that cannot happen: bootstrap precedes the
first script call.
NULL_SEGMENT in the receiver position is the tree's static-method marker
(_null_segment() for an is_static method), and the two backends read it
differently. Desktop/Android pass the null pointer straight to
object_method_bind_ptrcall, which is exactly what Godot expects for a static bind.
iOS cannot: its C instance entry point kanama_ios_godot_ptrcall keeps a deliberate
null-instance guard, so the iOS ObjectCalls routes a zero instance to the separate
kanama_ios_godot_ptrcall_static entry point through the hand-written
ptrcallDispatch helper, which every hand and generated ptrcall member in that file
calls. Never "fix" a static call site by inventing a receiver, and never drop the
dispatcher: without it every shared-tree static is a silent no-op on device.
The generator's marker is not the only way a zero instance arises: a failed singleton
lookup yields one too, and it now reaches Godot on iOS exactly as it does on desktop —
as a null this, not as a no-op the C guard swallowed — so a lookup that can fail must be
checked before its result is used as a receiver. Both ObjectCalls.getSingleton
implementations therefore log loudly when the lookup returns null
([kanama][ios][kn] ERROR: getSingleton("<name>") returned null … and the [kanama:kt]
equivalent on desktop; Godot's own error print for this does not reach the iOS device console
capture). They still return the null pointer unchanged — the return shape is public behaviour.
That guard is not unique to kanama_ios_godot_ptrcall. Over twenty
kanama_ios_godot_* entry points — the packed-array, array-blob, UTF-8,
Variant-scalar and object-call shapes an ObjectCalls helper reaches for a
non-generic return — carry the same instance == 0 early return, and the shared tree
reaches statics through their helpers too. The rule: every guarded entry point an
ObjectCalls helper calls gets the 30c949a1 split — the body in an unguarded
static <symbol>_dispatch(...), the existing symbol keeping its guard and calling it,
and a <symbol>_static(...) sibling (declared in ios/include/kanama_ios.h, the
cinterop header) calling it with a null instance — and is named exactly once in
ObjectCalls.kt, inside a private <entry>Dispatch function that picks the _static
sibling when the instance is zero. Never remove an existing guard and never change an
existing signature to make a static work. scripts/check_ios_static_dispatch.py (a
local_ci.sh stage) enforces this: it derives the guarded set from the shim itself —
by SIGNATURE (kanama_ios_* taking both an int64_t method_bind and an instance it
early-returns on), not by name prefix, which is what finally brought
kanama_ios_classdb_instantiate_owned into scope — and fails on any raw call, so the
next static the generator renders through a new shape is covered without anyone
remembering this paragraph.
The gate also reads the shim's own _dispatch bodies, because the Kotlin rule is
only half the property. A _dispatch body is the unguarded half of a split, so it is
by definition reachable with a zero instance; if it then calls a guarded entry point
instead of that entry's _dispatch body, the early return bites one frame below the
Kotlin dispatcher and the _static sibling above it is a dead end — the result cell
is never written and the call no-ops exactly as before. Two bodies shipped that way
(..._ret_raycast_dict_dispatch and ..._ret_object_handles_dispatch, both calling
kanama_ios_godot_ptrcall instead of kanama_ios_godot_ptrcall_dispatch). Inside a
_dispatch body, call the callee's _dispatch body.
The per-platform generated files keep the JDK/shim spelling, and a genuine
const void* argument still renders as MemorySegment: the three desktop-only
helpers GDExtensionManager.loadExtensionFromFunction(initFunc),
OpenXRAPIExtension.transformFromPose(pose) and
OpenXRAPIExtension.setCustomPlaySpace(space) take a raw native pointer, not an
object handle, and are the only public signatures left that name a
java.lang.foreign type. check_wrapper_generator.py fails if any file under
src/commonMain (which holds the wrapper tree) names one at all (comments excluded: the
expect files' KDoc names the JVM type when it explains the typealias).
Generated wrappers are held to a single-tree drift gate. There is one generated
wrapper tree, src/commonMain/kotlin/net/multigesture/kanama/api, part of the KMP
common fragment of the one multiplatform module since task 117 P4′: the JVM and both
iOS targets compile it as common code, and the Android plugin's remapped copy of
commonMain carries it. compileCommonMainKotlinMetadata compiles it on its own, so a
tree file that names a platform-only declaration fails the build — the API is
platform-neutral by construction. The few platform classes the tree names are expect
declarations beside it (GodotSignal.expect.kt with SignalConnection,
MainThread.expect.kt) with one actual per platform, and an expect declaration
carries no default argument (overloads instead): the Android copy skips
*.expect.kt and strips actual, so a default declared only on the expect would not
exist there. scripts/check_expect_no_defaults.py (a local_ci stage) fails on one. The shared
file of a class carries the members both native backends can call: the method set is
the iOS-audited helper-shape set (IOS_AUDIT_ONLY), the surface is desktop's
(@JvmStatic, factory helpers). Members desktop can call but iOS cannot yet (no
audited ObjectCalls helper for the ptrcall shape, or a wrapper type iOS does not
host) are generated as extensions into a per-class desktop companion
src/jvmMain/kotlin/.../api/<Class>.jvm.kt; the companion header names the helpers it
waits on, and the generated iOS Shape Gap
page lists the whole gap. When a helper lands on iOS the next regen moves the member
back into the shared file. Because those members are extensions, a script that calls
one needs the member imported by name (import net.multigesture.kanama.api.<member>), not only
the class import. iOS-only sugar on a shared class (IOS_EXTENSION_SECTIONS) is
generated the same way into src/iosMain/.../api/<Class>.ios.kt. Sugar every platform compiles
but callers import by name (top-level extensions) goes in SHARED_EXTENSION_SECTIONS instead: its
text is appended to the shared <Class>.kt after the class (the AnimationMixer.setParameter /
getParameter / getStateMachinePlayback helpers, one copy since task 129 D).
Hand-written members a generated wrapper must carry live in the custom-section
tables of scripts/generate_api_wrapper.py, keyed by class: SHARED_MEMBER_SECTIONS
/ SHARED_COMPANION_MEMBER_SECTIONS for shared classes (their text may only use what
both platforms resolve), DESKTOP_*/IOS_*_MEMBER_SECTIONS and
*_COMPANION_MEMBER_SECTIONS for the per-platform generated ones, and the
*_EXTENSION_SECTIONS above for platform sugar on a shared class.
check_section_tables refuses a key in the wrong table. The factory helpers are
not sections. create() is generated for every class extension_api.json marks
is_instantiable that is a Node or a RefCounted (generates_create; GDScript's
X.new()): a RefCounted create() is owned (the constructing +1), a Node one is not.
A plain Object subclass (UndoRedo, JSONRPC, MainLoop, ...) gets none, because
Kotlin has no free() for an object no tree or reference count frees. Web follows the
same rule (generates_create in generate_web_wrappers.py) for the classes it
generates. The from* downcasts are rows in DOWNCAST_HELPERS (task 119 item 33),
because every one of them was the same two shapes pasted by hand. Add a row, not
Kotlin:
"SphereMesh": (Downcast("fromResource", "Resource", False),),
"FastNoiseLite": (Downcast("fromResource", "Resource", False),),
Each Downcast(name, param_type, nullable) emits fun <name>(value: <param_type>): C?
— the isClass form for a non-null parameter, the ?.takeIf { … }?.let { … } form for
a nullable one (a fourth field renames the parameter, which only
SceneMultiplayer.fromApi(api:) needs). render_factory_helpers owns both bodies and
their comments; the block is appended to the companion object after the class's custom
section and before the MethodBinds (every generated class is shared since task 129 C, so
the helpers carry @JvmStatic on every platform). check_factory_helpers fails the run
if a DOWNCAST_HELPERS key is not a class the generator renders, or if a companion
section pastes a create() or a downcast the generator renders (any visibility or
annotation).
The classes that are not shared are listed once, platform-tagged, in
PER_PLATFORM_WRAPPERS (scripts/generate_api_wrapper.py): for each, what desktop
does (generated into src/jvmMain/kotlin/.../api, or hand) and what iOS does
(generated into src/iosMain/.../api, hand, collision for a class hand-written
inside IosGodotApi.kt or a bespoke file, or unsupported). DESKTOP_HANDSHAPED,
IOS_HANDSHAPED, IOS_HANDWRITTEN_COLLISION_CLASSES and IOS_UNSUPPORTED_CLASSES are
views of that table. A class is per-platform only when the platforms genuinely host it
differently, and a hand cell is the only thing the gate exempts; a class joins that
table only when the generator genuinely cannot reproduce it on both platforms. Non-API
files (Mathf, KanamaScript, …) are auto-excluded, and so are the hand-written roots
described next.
Retiring a per-platform class: a table row, not a hand class (task 129). Every
PER_PLATFORM_WRAPPERS entry is a class written twice, and the two copies drift (iOS Tween had 7
of Godot's 28 methods until task 129 A). To generate one once:
- Delete its entry and both hand copies (the desktop file, the iOS file or its block in
IosGodotApi.kt). - Run
generate_api_wrapper.py --write-tree, thensync_kdoc_from_godot_docs.py --writeand./gradlew ktfmtFormat.--write-treeadopts every class ofextension_api.jsonthat has no wrapper file (it writes a placeholder, then renders it) and lists what it adopted;ADOPTION_EXCLUDEDnames the classes it never adopts (Object, the hand-writtenGodotObject). It repeats until a pass writes nothing, so members that return the new class itself, such as fluent setters, render on the second pass.--emit-class <Class> --allow-overwriteadopts one class the same way. The drift gate fails while an API class has no wrapper. - Carry the hand copies' sugar over as data, keeping the desktop names and signatures:
create(): nothing (every instantiable Node or RefCounted gets one); afrom*downcast: aDOWNCAST_HELPERSrow;- parameter names Godot spells differently:
PARAMETER_NAME_OVERRIDES; - overloads and helpers both platforms can compile:
SHARED_MEMBER_SECTIONS[<Class>](member text) orSHARED_COMPANION_MEMBER_SECTIONS(companion text);Tween's String-pathtweenPropertyand target-plus-methodtweenCallback/tweenMethodare the example; - top-level extension sugar callers import by name:
SHARED_EXTENSION_SECTIONS; - sugar only one platform can compile:
DESKTOP_EXTENSION_SECTIONS/IOS_EXTENSION_SECTIONS; - a Godot default the generator does not emit (a
nullObject default, as inSurfaceTool.commit(existing = null)): aKOTLIN_DEFAULT_EXPRESSION_OVERRIDESrow; - a rule
extension_api.jsoncannot express, checked before Godot sees the call: aMETHOD_PRECONDITIONSrow, Kotlin statements in the method's parameter names emitted after the receiver guard (Engine.registerSingletonrejects aRefCounted; theaudit_singleton_refcounted_policy.pygate checks the row and the generated body); - an out-parameter Godot writes into (an
Arrayit fills): oneObjectCallshelper every platform implements, called from a shared section (ptrcallLoadStatusWithProgressforResourceLoader.loadThreadedGetStatusWithProgress), not a per-platform class. A member the iOS helper set cannot call yet lands in the class's generated<Class>.jvm.ktcompanion by itself (listed inios-shape-gap.md); do not hand-write it. - Delete what the old copies called and nothing else does:
IosGodotfunctions, C shim entry points and theirkanama_ios.hdeclarations. Theactualmodifiers of the desktopObjectCallsfollow by themselves (see ObjectCalls per Platform). - Run
check_public_signature_changes.py; announce any break in the CHANGELOG, fix the demos in a paired change, then--write. A declaration that leftjvm.txt/ios.txtand is incommon.txtnow, unchanged or source-compatibly changed, is reported as moved, not as a break; only what really changed needs aSource breakline. Drop the files fromscripts/hand_code_budget.json(check_hand_code_budget.py --write); a section the class's sugar moved into is added to itssectionswith areason.
Task 129 C retired 20 classes this way (the hand/generated band, the iOS-hand band,
ProjectSettings, AudioStreamPlayer, ResourceLoader, Engine) and task 129 D the last two,
FileAccess and DirAccess: PER_PLATFORM_WRAPPERS is empty.
FileAccess and DirAccess (task 129 D). Both are generated RefCounted classes with Godot's
statics in the companion, the shape GDScript and godot-dotnet give them (FileAccess.Open(...)
returns a FileAccess instance there too). open / openCompressed / openEncrypted* /
createTemp return an owned FileAccess? (task 132). Godot's own close() method is renamed
closeFile() (METHOD_NAME_OVERRIDES) because close() is RefCounted's AutoCloseable
release, and a SHARED_MEMBER_SECTIONS["FileAccess"] override makes close() call it first: like
GDScript's file.close() (and the retired FileAccessHandle.close()), close() / use { } close
the file even on a borrowed view or while another reference holds the object, then release this
wrapper's reference. DirAccess keeps RefCounted.close(): Godot's DirAccess has no close
(listDirEnd() ends a listing, the destructor the rest). sync_kdoc_from_godot_docs.py documents
a renamed method from Godot's doc of the original (closeFile() gets FileAccess.close's), and its
CLASS_KDOC_NOTES adds the Kotlin lifetime paragraph to the FileAccess class KDoc. What used to make them hand-written is data now: the FileAccess-returning static call
shapes are a call_shape table, and open_encrypted's empty iv default a
KOTLIN_DEFAULT_EXPRESSION_OVERRIDES row. The desktop hand files' 38 FileAccess path one-shot
helpers (get8At(path), writeString(path, text), ...) and 23 DirAccess *At(directory, ...)
helpers were removed rather than generated: GDScript has none of them (it opens the file or
directory and calls the instance method), and Godot's whole-file statics (getFileAsString,
getFileAsBytes, getFilesAt, ...) are generated. The CHANGELOG lists each with its migration.
GD is generated from the utility functions (task 129 B). render_gd in
scripts/generate_api_wrapper.py writes src/commonMain/.../api/GD.kt at --write-tree: one
member per entry of extension_api.json's utility_functions, each calling the seam in
binding/runtime/UtilityCalls.expect.kt through a UtilityFunction(name, hash) handle. A function
whose arguments and return are all float / int / bool writes them into the thread's
BuiltinFrame and calls callUtility (no allocation); every other one goes through
UtilityCalls.call(fn, argTypes, args, retType), which converts each argument to its parameter's
Variant type and decodes the return like a GodotObject.call result. The platforms implement only
the mechanism: desktop/Android src/jvmMain/kotlin/binding/runtime/UtilityCalls.kt (FFM, the
pointer variant_get_ptr_utility_function returns), iOS src/iosMain/.../UtilityCalls.kt over the
C shim's kanama_ios_godot_get_utility_function / kanama_ios_godot_utility_call (no argument
cap: vararg cells past 16 live on the heap). The data is in the generator: GD_NAME_OVERRIDES
(the Kotlin names that differ from Godot's camel case), GD_TEXT_UTILITIES (the print family and
str, whose non-Variant arguments are passed as toString()), GD_TYPED_OVERLOADS (the
Double / Long / Int overloads of the Variant-form max, abs, clamp, ..., each delegating
to the typed function), and GD_MEMBER_SECTIONS
(budgeted hand members: the typed isInstanceValid, the text helper). sync_kdoc_from_godot_docs.py
documents each member from @GlobalScope.xml through the file's Fn table. Mathf is hand-written
once in common (sugar): Godot's formulas in Kotlin, the transcendentals
through kotlin.math with Godot's clamps (its Float overloads stay hand-written: generated ones
would have to be extension functions, which a script importing only Mathf would not see). Only
the float-to-int conversions, posmod by zero and asinh / acosh / atanh call GD. The runtime
smoke's parity pair (generate_builtin_ops.py, rows mathf= / mathfedge= / gd= / rand=)
holds both to GDScript: the arithmetic bit for bit, and each transcendental, Double and Float
overload, within its MATHF_LIBM_BOUNDS bound of the engine's result (mathfbound=; the desktop
JVM's and Kotlin/Wasm's libm differ from the host's in the last bit or two).
The hand-code budget. scripts/check_hand_code_budget.py (a local_ci.sh stage) lists every
hand-written Kotlin file of the API (under an api/ directory, or declaring the
net.multigesture.kanama.api package anywhere in src/ or web-runtime/src/) in
scripts/hand_code_budget.json with its category: seam (the platform call mechanism),
runtime-core (what extension_api.json does not describe), sugar (GDScript-syntax sugar written
once) or transitional (should be generated; carries the task-129 parcel that retires it). Every
file has a line ratchet, and so does the hand Kotlin inside the generator tables (each *_SECTIONS
key and METHOD_PRECONDITIONS row here and each Web CLASS_POLICY string). The gate fails on an unlisted hand file, a listed file
that is gone or generated, and any growth. Only the GENERATED ENUMS regions a generator really
splices into a file are left out of its count; a GENERATED marker pair in any other API file fails
the gate. A legitimate seam, runtime-core or sugar change raises its ratchet with
check_hand_code_budget.py --write --reason "<why>", which records the reason in the JSON; a
transitional file never grows, because an API addition is generated. "Generated" is the set of
regenerate_tree() write targets, not a file header.
The roots are written once (task 117 P3′). GodotObject, RefCounted and
GodotCallable are hand-written files in the shared tree
(src/commonMain/kotlin/.../api/{GodotObject,RefCounted,GodotCallable}.kt), compiled by every
platform like the generated classes they are the base of; neither platform has a copy.
RefCounted shares its name with a Godot class, so SHARED_HAND_ROOTS in the generator keeps it
out of the tree universe (and --ios-emit-class RefCounted refuses it); GodotObject (Godot's
Object) and GodotCallable carry no Godot class name and were never generated. Every member of
the three is a ptrcall through ObjectCalls, except four platform-bound hooks that go through the
internal ObjectRuntime seam — internal expect object ObjectRuntime in
src/commonMain/.../binding/runtime/ObjectRuntime.expect.kt, the compiler-checked contract in the
same style as ObjectCalls and the builtin-call BuiltinFrame:
| hook | called from | desktop/Android actual | iOS actual |
|---|---|---|---|
instanceIdOf(segment) |
GodotObject.instanceId (captured at construction) |
ObjectCalls.objectGetInstanceId |
IosGodot.objectGetInstanceId |
emitSignal(segment, signal, args) |
GodotObject.emitSignal |
binding.runtime.Signals.emitAny |
shim fast paths for one Int/Long/Vector2i, else Variant emit_signal |
onPropertySet(segment, property, value) |
GodotObject.set, call("set", …) |
ScriptBridge.applyOrRecordScriptPropertySet |
documented no-op |
onSetScript(segment, script) |
GodotObject.setScript (before the ptrcall) |
ScriptBridge.noteSetScript |
documented no-op |
Keep the seam that small: a hook belongs there only when a root's body cannot be a ptrcall. The
root Object helper shapes the roots call are part of the generated expect object ObjectCalls
like any other referenced helper; on iOS the generator emits them from the root Object methods
(collect_root_object_shapes) where the renderer can, and the rest are hand-written above the
GENERATED MEMBERS marker (listed in IOS_HANDWRITTEN_HELPERS). GodotSignal and
SignalConnection are the two genuinely per-platform classes left (desktop
SignalCallbackRegistry + bound Callable, iOS IosCallableRegistry + the shim's custom
Callable): since task 117 P4′ they are expect classes in
src/commonMain/.../api/GodotSignal.expect.kt with one actual per platform, and MainThread
is an expect object the same way — the compiler holds both platforms to every member of the
expect, and scripts/check_actual_public_surface.py (a local_ci stage) fails on an actual that
declares a public member the expect does not, which the compiler allows; so the old
scripts/check_wrapper_parity.py and its allowlist are retired. Their former default
arguments are overloads (connect(target, method) + connect(target, method, flags),
connect(target, argumentCount, callback) + connect(target, argumentCount, flags, callback),
connectObject(target, callback) + connectObject(target, flags, callback), await(target) +
await(target, argumentCount)). The drift gate fails on a stale per-platform copy of a root (a
<Root>.kt in a platform api directory, or a class <Root> declared in any platform api file);
a non-actual platform copy of an expect class is a compile error.
Typed engine signals (task 134 D4) are generated beside each class's Signals constants by
render_signal_accessors in scripts/generate_api_wrapper.py: one property per signal over the
hand-written Signal0 … Signal5 in src/commonMain/.../api/TypedSignals.kt, typed by
signal_arg_type, named by signal_accessor_names (a Signal suffix where a member of the class,
an ancestor or a descendant already has the name). Each platform decodes the arguments through a
SignalArgReader (JvmSignalArgReader, IosSignalArgReader). check_typed_signals in
scripts/check_wrapper_generator.py fails when an engine signal has no accessor or one with the
wrong arity; GodotObject carries its signal accessors by hand. Web generates
Signal0/Signal1 for its policy signals in scripts/generate_web_wrappers.py.
check_single_tree in scripts/check_wrapper_generator.py regenerates the whole tree
in-process (a few seconds) and fails if any generated file — a shared class, a
per-platform generated class, a companion, the GENERATED MEMBERS region of the iOS
ObjectCalls.kt (compared by member set, since ktfmt reformats it), or the gap index —
differs from a fresh regen
(behavior-comparable; sync_kdoc_from_godot_docs.py owns the prose), if a committed
companion is no longer produced (its gap closed), or if a shared class also has a copy
in a platform directory. A hand edit to a generated file, an un-adopted generator
improvement, or a platform-local shape change all fail here: there is one tree, so the
platforms cannot drift from each other. Re-adopt with
python3 scripts/generate_api_wrapper.py --write-tree followed by
sync_kdoc_from_godot_docs.py --godot-docs … --write (the regen output carries no
KDoc); --emit-class <Class> --allow-overwrite does the same for one class, writing it
into its home (the shared file plus companions, or its per-platform directory).
Android has no separate committed tree — prepareAndroidKanamaSources copies
src/commonMain (minus *.expect.kt, so the tree comes with it) and the desktop sources
through the PanamaPort remap, so the desktop side
of the gate covers it transitively. Adopted classes with skipped methods are only
accepted when every skip is a Godot virtual callback that belongs to the
override-registration design rather than the public ptrcall wrapper surface. When Godot gives one
of the listed classes a method whose call shape has no helper yet, the class stays in its list: the
method gets a PENDING_HELPER_SKIPS row in check_wrapper_generator.py until the helper lands:
(reason, owner, since), where the owner is the task or issue that adds the helper and since the
ISO date of the row. A row whose method generates again, or with no task or issue, fails as stale;
one older than 60 days warns on every run. Under --baseline-api <previous
extension_api.json>, which upgrade_godot.sh passes, such a method is reported with the row to
paste instead of failing. How the
two trees were merged, and what the KMP expect/actual form would still take, is
recorded in Shared Wrapper Tree: Design Check.
Typed Godot Enums and Required Returns¶
Since task 128 every Godot enum and bitfield (764 class enums, 22 global, 7 on builtin value types:
793 value classes on Godot 4.7.2) is a @JvmInline value class X(val value: Long), and every
generated parameter, return and property Godot types enum::X / bitfield::X uses it. The model
lives in scripts/godot_enum_model.py; the generator, the KDoc sync, the migration script and the
gate all import it.
- ABI unchanged. The generator keeps the logical kind
"enum"/"bitfield"for call-shape selection (SCALAR_KOTLIN_TYPESstill maps both toLong: that is the helper's ABI type, not the surface), so the sameptrcall*Long*helpers carry them and noObjectCallshelper was added. Only the Kotlin surface changes:kotlin_typereturnsenum_type_ref(type), arguments cross asname.value, returns are wrappedX(raw), vararg fixed arguments go into the Variant list as.value, and defaults render as the named constant whose value equals Godot's default (X(<n>L)when none does). The JVM erases a non-null value class tolong, so there is no boxing. - Placement. A class enum nests in its owner's generated file (
Node.ProcessMode); globals go to the generatedsrc/commonMain/.../api/GlobalEnums.kt, renamed only on a collision (GLOBAL_ENUM_RENAMES:Error->GodotError,PropertyHint->GodotPropertyHint,Variant.Type/Variant.Operator->VariantType/VariantOperator). Generated code names a class enum owner-qualified and a global by its plain name, package-qualified only where a class enum of the same simple name could shadow it (Orientation). - Hand-written owners (the
hand/collisioncells ofPER_PLATFORM_WRAPPERS, the shared roots, and the builtin value types undersrc/commonMain/.../types) carry a marked region// ===== BEGIN GENERATED ENUMS: <Class> ... =====/// ===== END GENERATED ENUMS: <Class> =====inside the class body.--write-treerewrites only that region and refuses missing, duplicate or misplaced markers; the drift gate checks it like any generated file (whitespace-insensitively in the ktfmt-formatted value types). Each target gets its own spelling: Kotlin/Native-only sources carry no@JvmInline(an@OptionalExpectationonly common and JVM code may name). - Enum-only expects. A per-platform owner whose enum a shared signature names
(
PropertyTweener.setTrans(trans: Tween.TransitionType),ZIPPacker.startFile(permissions: FileAccess.UnixPermissionFlags)) cannot be seen from common code, so the generator finds such owners in the rendered shared tree (find_expect_enum_owners; none since task 129 D generatedFileAccessonce,Tweenwent in task 129 A) and emitssrc/commonMain/.../api/<Class>.expect.ktdeclaring only the nested enums; the platform regions become theiractuals (oneactualper line, so the Android copy strips them).scripts/check_actual_public_surface.pyscopes the rest of those hand-written classes (HAND_SURFACE_SCOPED) and prints the cross-platform gap task 129 closes. - Value names come from ONE function,
godot_enum_model.enum_value_name(prefix, godot_name): Godot's C# rule (bindings_generator.cpp_determine_enum_prefix/_apply_prefix_to_enum_constants) ported exactly, SCREAMING_CASE kept, except C#'s hard-codedERR_prefix forError: Kanama keepsGodotError's full names (GodotError.ERR_FILE_NOT_FOUND). The prefix is frozen per enum inscripts/enum_prefix_lock.json(generated, do not edit): the generator uses an existing entry as-is, appends one only for a new enum, and a value that does not carry its enum's frozen prefix keeps Godot's full name, so siblings never change name across Godot versions. The file's "do not edit" header is the only guard against a hand edit of an EXISTING entry, by design: the generator trusts the lock, andcheck_typed_enums.pythen holds every emitted name to it. - Raw values are always constructible (
X(3L)) and readable (.value);toString()stays the value-class default. Every value class implements the generated markerGodotEnumValue(GlobalEnums.kt): theAny?-> Variant encoders (desktopBuiltinTypes.initVariantFromAny, the iOSpackVariantDesc/encodeVariantArgs/ containertaggedValue/ script-returnencodeIosReturn) map a boxed one to INT, soset("process_mode", Node.ProcessMode.ALWAYS)works; dynamic paths (call/get, Variant returns) still RETURNLong. - The KSP processor's copy (task 128 B) is
processor/src/main/resources/net/multigesture/kanama/processor/godot-enums.tsv: one row per enum (Godot key, Kotlin FQN, enum/bitfield,NAME=valuepairs through the same naming function and lock), written by--write-treebeside the lock and compared by the drift gate. The processor needs the values, not just the names (property hint strings, constant-folded@Exportdefaults, the@OverrideVirtualtyped-signature check), and a compiled API library gives KSP the companion getters' names only. - Companion values are getters (
val ALWAYS: ProcessMode get() = ProcessMode(3L)): no backing field and no companion static initialiser, the smallest JVM shape that keeps them typed (measured in task 128: 1.70 MB of class files for the 786 enums vs 1.98 MB with backing fields). - Required object returns. A Godot object return marked
meta: "required"renders non-null and goes throughbinding.runtime.requireGodotReturn, which throwsIllegalStateException("Godot returned null from required <Class>.<method>"); every other object return stays nullable. - Gates.
scripts/check_typed_enums.py(a local_ci stage) reads the committed sources: every enum slot of every method tied to its Godot method through itsgetMethodBinduses its value class, required returns are non-null (others nullable), no generated top-level name equals a Kotlin default import or a public Kanama type, the lock covers every enum and every emitted value name is the naming function under it.scripts/migrate_enum_constants.py --table docs/reference/generated/enum-migration.md --checkkeeps the migration table current.
RefCounted Return Ownership¶
This section is the ABI truth, for contributors. The rule a game developer needs — and the owned / borrowed / engine-owned / node categories it produces — lives in Godot API → Resource Ownership. Keep the two in step: this page explains why the
+1exists, that page explains what to do about it.
Engine methods whose return type derives from RefCounted hand the ptrcall
caller a +1 reference through the return slot. This holds for every such
method: Godot's PtrToArg<Ref<T>>::encode copy-assigns into the slot and
PtrToArg<RequiredResult<T>>::encode nets the same +1 — meta: "required"
signals never-null-on-success, not a different ownership convention
(runtime-measured on Godot 4.7-stable; see the Tweener ownership probe in
scripts/runtime_smoke.sh). Non-RefCounted object returns (nodes, servers)
are raw pointers with no reference transfer.
The wrapper convention on desktop/Android:
- A generated wrapper returned from a RefCounted-typed method owns that
reference;
close()releases it (unreference()+ destroy at zero). This matches the script-property retention path (ScriptBridge.retainScriptResource), which takes its own reference. - Ownership is a constructor fact (task 132 D1). A RefCounted wrapper class
has no
wrap: its companion carrieswrapOwned(the wrapper owns a+1) andwrapBorrowed(a view), andRefCounted.owned(wrapper)marks a wrapper built some other way (create(), a hand-written loader). The generator picks one per site (wrap_owned_helper/wrap_borrowed_helper): RefCounted returns, the self-return collapse andcreate()are owned;fromHandle, thefrom*downcasts and typed-Array element callbacks (X::wrapBorrowed, becausereadArrayObjectsOwned/ iOSownedListElementretain the element and mark it owned) are borrowed. Hand-written and per-platform files follow the same rule, andrefcounted_ownership_problemsinscripts/audit_generator_shape_policy.pychecks every site. - Only an owned wrapper registers the GC fallback (task 132 D2-D5,
binding/runtime/OwnedReleases.kt): a cleanup holding the raw handle and instance id (never the wrapper) throughOwnedReleaseCleaner-- one sharedjava.lang.ref.Cleaneron desktop/Android,kotlin.native.ref.createCleaneron iOS. The cleanup only enqueues on a lock-free queue; the main thread drains it once per frame (ScriptLanguage._frameon desktop/Android,KanamaIosRuntime.frame()on iOS) and at SCENE deinitialization after a forced collection, before Godot's leak report.close()cancels the cleanup first, so a+1is released once; a release whose object is already gone (instance id no longer resolves) is skipped.retainForKotlinWrapper()makes a borrowed wrapper owned, fallback included.close()disarms atomically (PendingRelease.tryDisarm): if the cleanup won the race, close() leaves the release to the drain. A wrapper built on any thread registers (task 138 item 6): every engine call ends withObjectCalls.keepReachableon the receiver and each object argument, so the main-thread drain never releases a wrapper a worker is still calling through; a runtime without that fence reports the cleaner unavailable.close()on a wrapper that holds no reference of its own (a borrowed view) releases nothing and warns in debug builds; thefrom*downcasts take their own+1(RefCounted.retained). - A script object keeps its RefCounted owner alive (task 132 blocker 1,
ScriptOwnerLinks.kton desktop/Android,IosScriptInstanceinKanamaIosRuntime.kton iOS): C#'sCSharpInstancemodel. The instance of aKanamaScriptobject holds a+1on its owner; the runtime's link to the instance (ObjectRegistry,ScriptBridge's owner maps) is strong while the owner's count is above 1 and weak at 1, switched inrefcount_incremented/refcount_decremented(which now returns false at count 1). The script object anchors the instance (KanamaScript.kanamaInstanceAnchor) and carries the cleanup that queues the owner's release once it is unreachable. A plain script class has no anchor and takes no+1; insteadOwnedReleases.drainparks the GC releases of its owner's owned wrappers until the script is detached (or shutdown), the lifetime it had before the fallback. A collected instance whose owner the engine references again before the release ran is rebuilt from the script factory, as C#'s_internal_new_manageddoes, and refilled from an uncached load of the owner's file -- both on the instance's first use (materialize), never inrefcount_incremented(Godot holds the ResourceCache lock and theResourceLoadermutex there) nor on the free path (siFreereads the link without building; owner/script/placeholder metadata never builds). The drain runs owner-link releases first and at once, and owned-wrapper releases within a ~1 ms frame budget (the rest carries over); above 100,000 live registrations new owned wrappers stop registering. Plain-class parking is keyed by owner and re-checked only when that owner's script is detached (UnparkHook). - Self-returning fluent methods collapse: when the returned address equals
the receiver's handle, the generated method releases the duplicate reference
and returns
thisinstead of minting a second owning wrapper (chained calls such astweenAwait(...).setTimeout(...)stay reference-neutral). The generator emits this pattern whenever the receiver class conforms to the method's return class (Tween.setParallel(...), generated since task 129 A, is one). TheTweenerfluent setters aremeta: "required"in Godot, so since task 128 they return the non-null self type (setTrans(...): PropertyTweener) and a null engine return throws throughrequireGodotReturn(see "Required object returns" below); other generated object returns stay nullable. The wholeTweenerfamily is generated since task 117 P2'. - A method returning a typed
Arrayof RefCounted hands back an Array that the ptrcall helper destroys right after decoding it, which drops the Array's own reference to each element — for an element nobody else holds (Engine.captureScriptBacktraces()), the object dies there. So the decode is the owning one: desktopBuiltinTypes.readArrayObjectsOwnedretains each RefCounted element (retainForKotlinWrapper) before the destroy, and the iOS shim'skanama_ios_godot_ptrcall_ret_object_handlesdoes the same in C; the element wrapper owns that+1. RefCounted-ness of an untyped element is read from bit 63 of its instance id (ObjectID::is_ref_counted), so the test costs no engine call. A decode that fails midway releases what it retained.scripts/audit_generator_shape_policy.pyfails on any barereadArrayObjectsinObjectCalls(task 131). - Wrappers minted from Variant-path returns or
fromHandlecasts borrow; a release there underflows. Self-collapse must therefore sit on a ptrcall object-return helper, never oncallWithVariantArgs(PropertyTweener.fromregressed exactly this way once; its generated form goes throughptrcallWithVariantArgRetObjectfor the same reason). That helper is not aMETHOD_CALL_SHAPE_OVERRIDESentry — that table holds only the twoClassDBrows. It comes from a return-type-keyed special case in_candidate_for_impl(scripts/generate_api_wrapper.py): anObjectreturn over a singleVariantargument picks the ptrcall helper instead of the Variant path when the declaredreturn_typeis one ofNode/PropertyTweener. Adding a class to that set is how a new self-collapsing(Variant) -> Objectmethod gets the ptrcall shape.
The iOS island mirrors the same convention (task 30): the C-shim exposes
object_destroy (kanama_ios_godot_object_destroy) and ObjectCalls.destroyObject
wraps it. Since task 117 P3′ there is one RefCounted for every platform — the hand-written
shared root — carrying close() (unreference + destroy at zero) and the internal
releaseHandle primitive, so the collapse pattern above is emitted identically in the
shared tree and the iOS-only generated files. GodotObject is not AutoCloseable;
RefCounted declares it and owns close() (node/server returns are raw pointers with no
reference transfer). The shared RefCounted's ownership members and the collapse emission are
locked by check_ios_policies, and the on-device self-test matrix carries a
refcounted-ret-owns-plus1 refcount probe (duplicate() → refcount 1 → close()).
Ownership of Freshly Created Resources¶
X.create() factories return an owning wrapper. All backends construct via
classdb_construct_object3 (Godot 4.7), which returns a RefCounted subtype
already owned (refcount 1) — Godot's own contract: "the caller … is
responsible for decrementing it again when the object is no longer needed." No
hand-rolled init_ref claim: the wrapper owns its +1 straight out of
construction, balanced by close() (or use { }).
This is what makes handing a created resource to the engine safe. When you pass
it to a Ref<>-taking sink — a surface-override material, a node property,
ResourceSaver.save — the engine takes its own reference on top of the
wrapper's. A later close()/use { } then drops only the wrapper's +1, so the
resource survives for the engine (issue #91 — previously, on the deprecated
construct_object2 path, create() was non-owning and close() dropped the
engine's only reference, so the material/mesh vanished from the saved scene).
Two Ref<Material> sinks (surface override + material override) plus a
create_refcount=1 assertion are guarded by the MaterialHandoffSmoke row in
scripts/runtime_smoke.sh; iOS guards the same on-device in its
ObjectCalls self-test.
What a game developer does about this +1 — close what you create, close what
a getter hands back, use { } where possible — is the one rule in
Godot API → Resource Ownership;
this page only records why the +1 exists on every path.
Issue #81 is subsumed. Before the
construct_object3migration (task 62),create()was non-owning, soResourceSaver.save's transientRefcould drop a fresh resource's only reference to zero and free it mid-call (issue #81, a JVM SIGSEGV), which a protective-reference guard in the save ptrcall helper worked around. Withconstruct_object3the wrapper's own+1outlives the transientRef, so the guard was removed —saveneeds no special-casing. Theissue81 packed_scene_saverow (ref_after_save=1,alive_after_save=true) proves the fresh resource survives save with no guard.
Two dynamic paths share this ownership problem: ClassDB.instantiate and
ClassDB.class_call_static both return a Variant that holds the fresh
instance's only reference, so the borrowed Variant-scalar decode would hand
back a handle that dies with the Variant (use-after-free for RefCounted classes
— GitHub PR #42; instantiate is also the canonical construction path for
third-party GDExtension classes, and a static factory such as
RegEx.create_from_string or Image.create has the same sole-reference
return). Both route through the same mechanism — a METHOD_CALL_SHAPE_OVERRIDES
entry in generate_api_wrapper.py that names the owned dispatch helper the
generated wrapper calls — and differ only in that helper:
ClassDB.instantiateis a generated ptrcall →ptrcallWithStringNameArgRetVariantScalarOwned.ClassDB.class_call_staticis a varargsObject.call, so its override names the vararg helpercallWithVariantArgsOwned, which delegates tocallWithVariantArgs(owned = true)(render_vararg_methodreads the override to pick the helper, defaulting tocallWithVariantArgs).
In both cases RefCounted results are retained before the return Variant is
destroyed and come back as the owning RefCounted wrapper (close() releases).
On iOS the retain must happen inside the C shim, before it destroys the return
Variant: instantiate uses the dedicated entry
kanama_ios_classdb_instantiate_owned, while class_call_static uses the
shared kanama_ios_godot_object_call with its out_is_refcounted out-param
(non-NULL turns on the retain). Non-RefCounted and non-object results stay
borrowed. Do not blanket-retain in variantToScalar itself — every other
dynamic object read (property gets, ordinary call() returns) is a borrow, and
a retain there leaks one reference per read. Other fresh-sole-reference dynamic
calls (obj.call("duplicate")) remain unfixed by design for now; add a
METHOD_CALL_SHAPE_OVERRIDES entry naming an owned helper if one bites.
Validated by the ClassDB instantiate ownership and ClassDB class_call_static
ownership probes in scripts/runtime_smoke.sh.
Engine-wide MethodName, PropertyName, and SignalName constants are
generated from extension_api.json separately from the class wrapper drafts, into
src/commonMain/.../api (every platform; desktop-only until task 129 D):
python3 scripts/generate_name_constants.py
scripts/check_wrapper_generator.py runs the same generator in --check mode,
so a Godot API refresh fails loudly if the committed name constants are stale.
iOS Generator Policy¶
iOS-mode rendering (IOS_AUDIT_ONLY: it decides the shared tree's method set and renders
the iOS-only generated files) has extra policy so a regen stays honest instead of silently
dropping or clashing. These are locked by check_ios_policies
in scripts/check_wrapper_generator.py:
-
Bare-
Objectreturns.get_collider()-style methods that return the root GodotObjectwrap toGodotObject?.wrapper_has_wrapfindsGodotObject.wrap()in the sharedGodotObject.kton every platform (until task 117 P3′ the iOSGodotObjectlived insideIosGodotApi.ktand needed a special case). Without it the iOS regen drops every bare-Object-return method (a silent coverage loss), even though theptrcallNoArgsRetObjecthelper is fully wired (Node returns use it). -
Subclass-override openness (no live probe since task 117 P1'(b2); kept as the rule for the next real case). Where a hand-written iOS subclass overrides a generated method, the base method must be generated
open— otherwise a regen drops the keyword and the override stops compiling. The standing example wasNode.createTween(), opened for the hand-written iOSSceneTree, which overrode it with the correctSceneTree.create_tweenbind (the FPS F2 fix). Both halves are gone now:SceneTreeis a generatedMainLoopsince task 117 P1'(b1), andNodeis generated into the shared tree since P1'(b2), wherecreateTweenis a plain generated member since task 129 A generatedTweenonce. Add a real case to the class'sSHARED_MEMBER_SECTIONSentry (orIOS_EXTENSION_SECTIONSfor an iOS-only helper), not by hand-editing the generated file. -
A custom section that REPLACES a generated member. A section normally adds members the generator cannot emit; when it declares the same Kotlin name AND parameter list as a generated one (a different return type, say), the two collide as conflicting overloads. Record the pair in
IOS_SECTION_REPLACED_METHODSwith its reason — the generated form is then skipped on the iOS render target and the reason lands in the skip report. The table is empty today: its one entry was("Node", "get_tree"), whose section declaredgetTree(): SceneTreenon-null, andNodeis generated once into the shared tree since task 117 P1'(b2) — every caller sees the generatedSceneTree?. -
Explicit class collisions. Real Godot classes that are deliberately hand-written on iOS (inside
IosGodotApi.ktor a bespoke single-class file) are thecollisioncells ofPER_PLATFORM_WRAPPERS(theIOS_HANDWRITTEN_COLLISION_CLASSESview), each with a reason.--ios-emit-class <that class>logs acollision:line and skips it, instead of writing a<Class>.ktthat duplicate-declares the class and breaks the compile. When a class graduates to a real generated wrapper (asTime/InputMap/PhysicsServer3Ddid, andEngine,ProjectSettings,ResourceLoaderandAudioStreamPlayerin task 129 C,FileAccessin task 129 D), delete its entry so generation is allowed. None is left. -
Explicit uncompilable classes. The
unsupportedcells ofPER_PLATFORM_WRAPPERS(theIOS_UNSUPPORTED_CLASSESview) list the classes whose generated draft cannot compile on iOS, each with its reason. None is left:DirAccess(its draft referenced the hand-authored desktopDirAccessHandle) was the last, until task 129 D;MethodTweenersat here until task 117 P2' retired the hand-written iOSTweenerglue its fluent methods clashed with.--ios-emit-class <that class>logs anunsupported:line and skips it. Together with the collision registry these are the only by-design exceptions to iOS class-set parity with desktop (task 30); retire an entry by porting the desktop policy surface it depends on. -
RefCounted ownership. The shared hand-written
RefCounted'sclose()/releaseHandle/checkOpen()/requireOpenHandle()members, the iOS renderer's refusal to emit a secondRefCounted, and the fluent self-return collapse emission (see "RefCounted Return Ownership" above) are locked bycheck_ios_policiesso a refactor cannot silently reintroduce the per-call RefCounted return leak. (Until task 117 P3′ the iOSRefCountedwas generated with these as custom sections.)
Two cross-platform load-bearing wrapper shapes are reproduced by explicit policy (so a regen
does not drop them), locked by check_ios_policies:
- Composite default-value overrides.
KOTLIN_DEFAULT_EXPRESSION_OVERRIDESinjects a final Kotlin default expression by exact(class, method, arg).Node3D.look_atandNode3D.look_at_from_position(bothup = Vector3.UP) — demos call the shortlookAt(target)form and rely on it — andSurfaceTool.commit(existing = null, task 129 C) are the current entries. Kept surgical (per exact arg) so no other method silently gains a default. - Non-null factory.
NON_NULL_FROM_HANDLE_CLASSES(currently{Resource}) emitsfromHandle(handle): Resource(non-null) so a@ScriptClass(attachTo = "Resource")script's(GodotHandle) -> ResourceselfFactory type-checks. The nullablewraphelper stays on the raw pointer (RawSegmentin the shared tree) — it is the(MemorySegment) -> T?callbackObjectCallstakes, andRawSegmentis that same type on each platform; it isinternal, so it never appears in a public signature.
The broad pre-existing regen drift (a fresh regen once changed the majority of the committed desktop generated files — accumulated generator improvements that were never re-adopted) has been closed by the task 21 convergence pass: all in-API wrappers were regenerated and re-adopted from the honest generator, and the full drift-gate above now keeps committed == fresh regen on every platform, so that class of drift cannot silently return.
Coverage Triage¶
For wrapper work, use the coverage reports as the baseline instead of waiting for another demo to expose a gap:
- Refresh
docs/reference/generated/api-coverage.mdanddocs/reference/generated/wrapper-generator-report.md. - Start from the generator skip categories and missing helper shapes.
- Rank gaps by common Godot workflows: scene tree, resources, physics queries, animation, UI, input, materials, signals, RPC, and export-facing APIs.
- Prefer removing raw escape hatches (
Object.call,Object.get,Object.set, string method names, manual handle casts) from normal user workflows over broad class-count increases. - Use public demos as regression coverage after choosing a wrapper slice, not as the only source of wrapper priorities.
The current coverage pages already separate promoted source coverage from generator capability. Treat low-coverage areas such as variant/dictionary helper shapes, typed arrays, and multiplayer/editor methods as API design work: add helper policy and audits before promoting wider wrappers.
Long-Tail Triage¶
Desktop-only by design. A member whose argument types cannot exist on iOS at all (a raw
const void*, a C function pointer) stays in its desktop companion file and is recorded in
IOS_DESKTOP_ONLY_BY_DESIGN in scripts/generate_api_wrapper.py with the reason. The gap page
(docs/reference/generated/ios-shape-gap.md) lists those members in their own "Desktop-only by
design" table and does not count them as waiting on a helper, so "0 desktop-only members waiting"
is the steady state after task 100. Unlike BY_DESIGN_METHOD_SKIPS, this does not remove the
member from desktop.
Once the class surface is broadly promoted, the remaining skips are a long tail of data-type / shape gaps, not missing classes. A full triage of the non-virtual skips and the skipped properties found:
- Non-virtual method skips (65 as of task 28's start): the large majority are intentional, not gaps —
- ~49 root
Objectmethods (call/get/set/connect/emit_signal/…) are deliberately routed through the hand-shapedGodotObjectpolicy, not regenerated per subclass. These are the escape hatches; keep them onGodotObject. - 2
RefCountedlifetime methods (reference/init_ref) are ownership-sensitive and hand-shaped. - One clean low-ABI slice landed — a new call shape that recombines
already-audited primitives and whose signature contains a type not in
IOS_ARG_KINDS/IOS_RET_KOTLIN, so it generates on desktop+Android and is cleanly iOS-skipped (no C-shim helper, no self-test row, no device gate — the same guardrail Dictionary uses):(Rect2i, Object, Color, int32, Object)→void(DrawableTexture2D.blit_rect) viaptrcallWithRect2iObjectColorIntObjectArgs— reuses the Rect2i/Object/Color/int cells.Rect2iis not an iOS arg kind.
Dictionary→Dictionary(GDScriptTextDocument.resolve/.rename) is a by-design skip, not a gap. Task 22 briefly landed it viaptrcallWithDictionaryArgRetDictionary, but the shape was pulled from the generator for stability (the helper body is still inObjectCalls.kt; nothing emits a call to it): a Dictionary-in/Dictionary-out passthrough through the genericMap<String, Any?>helper silently drops non-String keys, soaudit_generator_shape_policykeeps the('Dictionary',) -> 'Dictionary'shape out ofCALL_SHAPES(it must stay hand-audited if ever needed). The two methods are editor-LSP plumbing with no game-runtime workflow.-
The formerly deferred ~12 landed in task 28 as audited desktop/Android families (all iOS-cleanly-skipped — none of the new kinds are iOS arg/return kinds; task 30 brought iOS to full class-set parity, and these per-method shape mirrors remain documented skip-report deferrals):
- Typed-array argument family: RenderingDevice
blas_create/tlas_build/raytracing_pipeline_create,ImporterMesh.merge_importer_meshes(TypedObjectArray+TypedTransform3DArray),DrawableTexture2D.blit_rect_multi,RenderingServer.texture_drawable_blit_rect(TypedRIDArray+Rect2i), and OpenXRdo_entity_update— newObjectCallshelpers recombining the auditedinitArrayOfObjects/initArrayOfRids/initArrayprimitives, registered in the shape-policy audit's dynamic helper sets. Signalscalar arg (Tween.tween_await): admitted per-method like Callable (never in the genericCALL_SHAPEStable).BuiltinTypes.initSignalbuilds Signal(Object, StringName) for the call and destroys it after; the engine keeps its own ObjectID-based copy, so no Kotlin state is retained. Runtime-validated inruntime_smoke(await resolves on real emission).- Hand-shaped-class landings:
OpenXRSpatialAnchorCapability.create_new_anchor/do_entity_updateare hand-hosted on theirDESKTOP_HANDSHAPEDwrapper in the exact generated form (draft-verified) — the committed copies had drifted to pre-4.7 signatures on compatibility hashes and now target the current 4.7 binds.EditorExportPlatform.export_projectandFont.find_variationwere on that list until task 117 P1'(a): both classes leftPER_PLATFORM_WRAPPERS, so the generator now emits those methods itself intosrc/commonMain/.../api/EditorExportPlatform.ktand.../Font.kton the same current 4.7 binds.
After task 28, the generator report's non-virtual skips are only the documented by-design entries above (root-Object policy, RefCounted lifetime, the
GDScriptTextDocumentDictionary revert) — each carries its rationale verbatim in the report viaBY_DESIGN_METHOD_SKIPS/ the policy messages. - ~505 skipped properties are NOT a marshalling gap. Triaged: - ~415 are indexed / parameterized accessors whose getter takes an argument (e.g.get_list_stream(i),get_param(param)). Godot lists them asfoo/0,foo/1, … pseudo-properties; they are not Kotlinval/vars by design, and the underlying getter/setter methods are already generated and callable. Not a gap. - ~90 have no simple own getter method — the getter is inherited (the property surfaces on the parent wrapper and the getter method is inherited), an engine virtual_get_*(task 13 territory), or an indexed inherited getter. None are unlocked by a new marshalling shape. - Typed-array argument family: RenderingDevice
Net: no skipped property is a "quick win behind a shape." Property coverage advances only when its getter method becomes generatable (a new no-arg return shape) or via ergonomic hand-shaping, never by widening property emission.
Virtual-Return Coverage¶
@OverrideVirtual return marshalling covers every Variant-expressible return
family in the 4.7 virtual signature table on desktop/Android. Tasks 13 + 29
landed, per family (Kotlin return type in parentheses): the audited scalar/POD
set, String, PackedStringArray (List<String>), all remaining fixed-element
Packed*Arrays (ByteArray/IntArray/LongArray/FloatArray/DoubleArray/
List<Vector2>/List<Vector3>/List<Color>), Dictionary
(Map<String, Any?>, String keys — the audited container policy), generic and
typed Arrays (List<Any?> — also the shape for the engine's typedarray::*
returns), RID, Rect2, AABB, Transform2D, Transform3D, Projection,
and Variant (Any?). Two families additionally ride existing ones by
Variant conversion: StringName returns are declared as String (the engine
casts the returned Variant at the call site, exactly as it does for GDScript),
and enum/bitfield parameters and returns are the typed value class (task 128 B:
INT on the wire, X(raw) in and .value out; a Long there fails the build,
and the two meta: "required" _get_space_state returns must be non-null).
By-design excluded returns (6 virtuals): void* (3) and const Glyph*
(3, TextServerExtension glyph buffers). Raw-pointer returns are not
Variant-expressible — GDScript cannot override these virtuals either — so they
stay outside the @OverrideVirtual surface permanently.
iOS mirror bounds: iOS value-returns cover Bool/Int/Float/Vector2/Vector2i/
Vector3/String/RID, all fixed-element Packed*Array families (a
KanamaIosPackedArgDesc + flat element buffer through the PT return scratch),
PackedStringArray, Dictionary and generic Array (tagged-entry blobs), and
Variant returns over that audited inner-type set (an unaudited inner value
serializes as nil — a valid Variant). The Rect2/AABB/Transform2D/
Transform3D/Projection returns are desktop/Android-only for now, by
design: Transform3D/Projection exceed the 32-byte PT return scratch (they
need the pointer-to-scratch route), the C shim has no variant_from boxing for
the four yet, and no 4.7 virtual returning them has arguments that are
declarable in Kotlin today — the iOS emitter warn-skips them fail-loud (the
same guardrail the task-28 desktop families use), and the mirror belongs to the
iOS wrapper-family follow-up slice.
Width-sensitive coverage: the desktop families are runtime-validated in
runtime_smoke.sh (the vret rows — GDScript typeof() + content checks
through the script-instance dispatch, including Int.MAX_VALUE, 1.0e308, and
full-range bytes); the iOS families have Kotlin encode round-trips plus C
build/box round-trips in the on-device self-test matrix (the
virtual-packed-*-ret / virtual-dictionary-ret / virtual-array-ret rows).
iOS @Export conversion parity: narrow scalars
(kotlin.Float/kotlin.Int widened to the 64-bit FLOAT/INT slots), Kotlin
enum class exports (INT slot carrying the ordinal), and enum-list exports
(typed int Array of ordinals) use the same conversions on iOS as on
desktop/Android. The iOS emitter narrows numeric slots, clamps scalar enum
ordinals, and maps/clamps enum-list elements. Integer arrays have a dedicated
C/runtime delivery entrypoint rather than sharing object-array cells, so stale
or malformed integers cannot be misread as object handles. Scene-loaded values
and later engine-originated Object.set updates both take this path. The iOS
descriptor now preserves each property's hint, hint string, and usage, while
the ScriptInstance getter maps the Kotlin values back to widened scalars or
ordinal arrays for engine reads.
KDoc Maintenance¶
Public Godot-backed wrappers and builtin value types carry generated KDoc
imported from Godot's doc/classes/*.xml files. The generated blocks include a
Generated from Godot docs: marker so they can be refreshed safely instead of
hand-edited.
Docs version pin: wrapper KDoc is synced from the Godot 4.8 beta 2
doc/classes (commit cafc17a192), matching the runtime baseline. Do
not sync from any other tree: a mismatched docs tree reintroduces
version skew. Bump this pin when the Godot runtime baseline moves, and re-run the
full refresh (part of the Godot Upgrade Runbook).
To check whether KDoc is current against a local Godot source tree:
python3 scripts/sync_kdoc_from_godot_docs.py \
--godot-docs /path/to/godot/doc/classes --check
To refresh the whole tree (a baseline refresh):
python3 scripts/sync_kdoc_from_godot_docs.py \
--godot-docs /path/to/godot/doc/classes --write
The script uses $GODOT_DOCS when set, otherwise it defaults to
godot/doc/classes relative to the current working directory. Use
--godot-docs /path/to/godot/doc/classes when syncing against a different
Godot checkout. The classes a module defines (ZIPReader/ZIPPacker, WebSocket*,
WebRTC*, CSG*, GLTF*, OpenXR*, ENet*, ...) are documented in the engine
source under modules/<module>/doc_classes, not in doc/classes: the script finds
that directory from the --godot-docs path (a source checkout's
<root>/doc/classes has <root>/modules/*/doc_classes beside it), and the drift
gate covers those wrappers too. A docs directory outside that layout syncs the core
classes only. Use --classes Node,Node3D,Tween for a focused refresh while
working on one wrapper slice, or --scope types --classes Vector3 when
working on builtin values. By default the api scope covers the shared tree, the
desktop per-platform files and their <Class>.jvm.kt companions; --api-dir
narrows it to one directory. Keep --types-dir (.../kanama/types) separate —
pointing it at an api dir mislabels node classes as value types.
The refresh is gate-neutral: check_full_drift_gate strips
Generated from Godot docs: blocks before comparing (comparable_source), so a
KDoc refresh never affects drift-gate correctness and only touches comments. The
sync replaces an existing generated block in place (multi-line or the older
single-line /** … */ form), so re-running is idempotent.
ObjectCalls per Platform¶
net.multigesture.kanama.binding.runtime.ObjectCalls is the only seam between the shared
wrapper tree and the engine, and it exists once per platform under that one
fully-qualified name: src/jvmMain/kotlin/binding/runtime/ObjectCalls.kt over Panama/FFM for
desktop (Android gets it through the source remap), and
src/iosMain/.../binding/runtime/ObjectCalls.kt over the C shim for iOS. Since task 104
step 3 both are actual object ObjectCalls, actualizing the GENERATED
expect object ObjectCalls in
src/commonMain/kotlin/net/multigesture/kanama/binding/runtime/ObjectCalls.expect.kt — all
1,450 helpers the tree calls. Until task 117 P4′ seven were documented exceptions (six named a
wrapper class the common fragment could not see, callWithVariantArgs carried an owned
default); scripts/check_objectcalls_parity.py now fails on any exception. The compiler, not a
script, is the parity contract. A helper whose desktop signature carries a default argument stops
--write-tree: split it into overloads, as callWithVariantArgs (borrowed) /
callWithVariantArgsOwned were.
One file per platform. The iOS file is hand-written except for a marked region at the
end of the object ObjectCalls body:
// ===== BEGIN GENERATED MEMBERS (scripts/generate_api_wrapper.py — do not edit) =====
... 1,384 generated helper members + the PT_* ptrcall tag table
// ===== END GENERATED MEMBERS =====
generate_api_wrapper.py --write-tree rewrites only what is between the markers, and
refuses to run when the pair is missing, duplicated or inverted. Everything above the BEGIN
marker is hand-written: the override set (IOS_HANDWRITTEN_HELPERS), the read-back and
descriptor machinery the generated bodies call (ptrcallRetUtf8, pack<Kind>Desc, …) and
the device self-test. The PT_* tags are declared once, inside the region: the generator
emits the whole table (not just the tags a run happens to use) because both halves read it.
Before task 104 step 3 parcel B the generated helpers were extension functions
fun ObjectCalls.x(...) in a separate ObjectCallsGenerated.kt. They are members now
because the rest of step 3 makes this object an expect object, and common code can only
see MEMBERS of one — a platform-only extension is invisible from src/commonMain.
Extensions are still fine for a helper nothing in the shared tree references.
Parameter names are desktop's. An expect member is actualized only by a member with
the same parameter names, and foo(bar = 1) does not compile against an actual that
spells the parameter differently. The generator reads the desktop file's signature for each
helper name and applies it positionally
(desktop_objectcalls_signatures / _desktop_parameter_rename); it refuses — keeping the
generated names and printing the helper in the run summary — when desktop has no such
helper, when the arities disagree, or when a generated parameter is not one of the
a<N> / a<N>Object / a<N>Method / fromHandle shapes it knows how to map, so a
surprise can never silently relabel an argument.
The gate. scripts/check_objectcalls_parity.py (a local_ci stage) parses both objects
and requires every helper the shared tree calls to be a member on both platforms with equal
arity and equal parameter names in order. It compares names, never types: the raw engine
pointer is MemorySegment on desktop/Android and the Kotlin/Native shim on iOS by design
(RawSegment), and expect/actual resolves that through the typealias. It reports
missing-on-desktop, missing-on-iOS, extension-not-member, param-count and name-mismatch,
and --list prints the contract. Overloads compare as sets of parameter-name tuples, and
iOS may declare more than desktop needs — an actual object may carry extra members, which
is how the iOS-only ptrcallNoArgsRetByteArray(methodBind, instance, sizeHint) coexists
with the two-argument shape desktop declares.
An Array return buffer holds a constructed Array. The engine writes a ptrcall's return into
the buffer the caller passes. For most types it assigns, which works on a zero-filled buffer, but a
method whose C++ return type is Vector<Variant>, Vector<RID> or Vector<Plane> (exposed as an
Array or a typed array, e.g. Animation.method_track_get_params, Geometry3D.build_box_planes)
resizes the buffer's Array in place, and a zero-filled buffer is a null Array: the process crashes.
Every desktop helper that reads an Array return constructs an empty one in the buffer first
(BuiltinTypes.constructEmptyArray, in callArrayReturn and in the helpers that read their Array
return directly), and so does the iOS shim, in its typed-array return
(kanama_ios_godot_ptrcall_ret_array_blob) and its container return
(kanama_ios_ptrcall_encode_container). Packed arrays, String, Dictionary and Variant returns take a zero-filled buffer.
A Variant return buffer reused after variant_destroy is not zero-filled: the destroyed Variant
keeps its type and payload, and the engine's assignment releases them again (an Object on Godot 4.8,
a packed array or a custom Callable on 4.7 too). A loop that reuses one resets it with
BuiltinTypes.destroyVariantToNil; VariantDecodeProbe (in the runtime smoke) checks every
container decode for it.
The desktop actual set is generated. The desktop file is hand-written, but which of its
members carry actual is not a hand decision: the expect is generated from the helpers the shared
tree calls, so a Godot bump that adds or drops a method moves that set. --write-tree rewrites only
the modifier (sync_desktop_actuals in the generator): actual on exactly the members whose name
and parameter list (names and types, since desktop has overloads that differ in a type only) match
an expect member, plain on the rest. A helper that lost its last shared caller stays in the file as
a desktop-only member. The drift gate compares the same set, so a hand-added or hand-dropped
actual fails it and a ktfmt re-wrap does not.
The drift gate (check_single_tree) compares the region's MEMBER SET rather than its bytes,
because the file is ktfmt-formatted outside the region and so the region gets reformatted
after every regen; --write-tree skips rewriting the file for the same reason when the
member set has not changed. scripts/fixtures/wrapper_generator/ios/ObjectCalls.generated-members.kt.txt
locks the region's rendering for one class (Node3D) byte-for-byte.
API Exercise Inventory¶
A defect in a helper is shared by every call site of it, so the plan for a generated API exercise is
one row per referenced helper per backend. scripts/generate_api_exercise.py keeps the inventory
that plan starts from: it classifies every helper referenced_objectcalls_helpers returns by the best
row any of its call sites allows (a static compared with ClassDB.class_call_static, a property
set/get pair, a const method compared with Object.callv, a singleton, reach only, or excluded with a
reason) and writes the API Exercise Inventory page. It maps
each call back to its Godot method through the generator's own method_function_name, so a rename
table cannot fool it. The judgement calls live in one hand-kept file, scripts/api_exercise_policy.py:
the exclusion list (exact class names and substrings, each with a reason), the stateless singletons,
where an abstract class's rows get their instance (TextServer from TextServerManager), the methods
whose result cannot be compared (a clock read, a new object per call), the runtime helpers that take
no MethodBind, the static rows' arguments and the user:// scratch directory rule, which covers every
row that takes a path. An argument-free static that can return its type's zero on a healthy host is
marked weak, and the page names the helper's next-best row; a static returning Error needs arguments
that make it fail.
--check (the local_ci stage "API exercise inventory drift") fails when the page is stale, when a
policy entry names a class or method the API lacks or matches nothing, when a STATIC_ARGS default
differs from extension_api.json, when a helper the tree calls is classified by nothing, and when one
call of a helper is spelled in a way the scanner does not read (with its file:line). After a generator change or a Godot API refresh, run
python3 scripts/generate_api_exercise.py --report and review the page's diff. A new static with
arguments needs a STATIC_ARGS entry; the failure prints the line to add. The rules are also checked
against a small made-up API in scripts/fixtures/api_exercise/ (--write-fixture rewrites the
expected output after an intended rule change).
Exercise Rows¶
--report also writes the rows, src/commonMain/kotlin/net/multigesture/kanama/exercise/ApiExercise.generated.kt,
and --check fails when that file differs from what the generator writes. The rows cover every helper
whose best case is a static (C), a property pair (A), a const method (B), a singleton method (D) or
reach only (F), for a weak static the helper's next-best A, B or D row as well, and one row per Godot
Variant type per generic Variant path (T). A row is one function of straight-line code that calls the generated wrapper exactly as a
script would, with the Kotlin signature read from the committed tree, and reports to the hand-written
ApiExerciseRunner.kt beside it:
- a C row calls the static with its
STATIC_ARGSand compares the result withClassDB.class_call_staticon the same arguments: equal and not the type's zero, an object result a non-null object of the declared class from both paths, anErrorresult the same non-OK value from both. A weak row (an argument-free static, or oneSTATIC_RESULTSmarks) only checks that the two paths agree and is counted apart; afreshone (a new value per call) checks both are non-zero. - an A row constructs a fresh instance of the receiver, reads the property, sets a recognisable
value of its type that differs from what it read (
7,0.75,"kanama125",Vector3(0.25, 0.5, 0.75), a fresh object, the opposite bool), and requires the value back from the getter and fromObject.get.PAIR_OVERRIDESgives a property a value it can keep (an MP3 stream keeps only bytes that decode) or takes it out of the pair rule when a fresh object cannot keep any set value (a frame index clamped by a missingSpriteFrames); its setter and getter then get their method's own case and the helper's next pair row is used. On aSINGLETON_PAIRSsingleton (Engine,AudioServer) every property the tree calls gets its row (not only where it is its helpers' best), and the row sets process-wide state, so it reads the original throughObject.getand puts it back throughObject.setin afinally, also when the row fails: never through the setter and getter under test, so a broken wrapper cannot leaveEngine.time_scalewrong; the finally reads the value back the same way and fails the row when the restore did not take.PAIR_GROWmakes a row only ever raise a count (AudioServer.bus_count: fewer buses would delete the project's).SINGLETON_KEYED_PAIRSruns a keyed set/get pair the same way (ProjectSettings.set_setting/get_settingon a key no project defines, restored throughObject.call("set_setting", ...), which erases it again). - a B row calls a const method on a fresh instance (or the descendant or
RECEIVER_SOURCESfactory the inventory names) and a D row a const method of a singleton, or any method of a stateless one (Geometry2D,Geometry3D,Marshalls); both compare the result withObject.callof the same method with the same arguments on the same object. The arguments are the required ones (defaulted ones take their defaults on both paths): a recognisable value per type, and each further argument of the same type in the call gets the next of three or more values (7/3/5/2,0.75/0.25/0.5, different vectors), so a helper that swaps any two cells of one type passes different values (a bool has only two); a path under the scratch directory for aStringpath argument; a square, a tetrahedron or a box's six planes for the geometry lists; a fresh object for an object argument. A result equal to its type's zero (what a fresh, empty object mostly answers) is weak: the two paths agreed, but a no-op could have produced it. The run counts those apart; they are not failures.ROW_ARGSgives a weak row real arguments (one per required argument: a real class and member forClassDB, valid base64, a datetime dictionary, locales, shapes that intersect) andROW_RECEIVER_SETSsets properties of its fresh receiver throughObject.setfirst (anInputEventActionforui_accept, a grid's region). - a RID factory row (
RID_FACTORIES: the rendering, physics and navigation servers and the text server) calls an argument-free*_create/create_*, requires a valid RID, reads one const<prefix>_get_*of it through the wrapper andObject.callwhere the server has one, and frees it in afinally. The same factories make the RID arguments of those servers' B and D rows (an argumentxtakes the class's ownx_create, or itsRID_ARG_SOURCESentry, such as a shaped text or a font forTextServer), freed after the row; the leak check at exit holds the rows to that. The row also calls the factory throughObject.calland frees both RIDs: an invalid RID from both paths is the host's (the headless dummy renderer makes no lights, skies or particles; the iOS renderer no decals, fog volumes or VoxelGI) and counts weak, printed as aWEAK:line with that reason; an invalid RID from the wrapper alone fails. A RID argument is made inside the row's guarded block, so a failing later one still frees the earlier ones. - an F row (reach only) calls its helper once on a valid receiver with the arguments a B row would
get (a no-op
Callableand the probe node's signal where one is needed) and passes when the call returns without an exception or a backend fault; it proves the shape crosses into the engine and back, not its value. Engine error prints for arguments a fresh object cannot use (an index past an empty list, an invalid RID) are expected. A RID a server returns is freed, an owned result closed, a new parentlessNodefreed.REACH_RECEIVERSnames a valid receiver where a fresh instance is not one (aTweenfromcreate_tween(), killed when the row ends),HAND_ROOT_REACHspells the calls of the hand-writtenGodotObjectroot (connect/disconnect/isConnected, whose Callable is split into a target and a method),REACH_AFTERadds what the engine expects after a call (load_threaded_getafterload_threaded_request, or the token leaks), andROW_ARGSgives an F row arguments too (receiver.create_item()is an object the row's own receiver makes). A method whose call would change what a running game shows or hears on a device, with no getter to restore it (a boot splash, the microphone, process-wide rendering settings, a made-up native texture handle), is excluded inMETHOD_OVERRIDESwith that reason: on iOS and Android the exercise runs inside the game. - a T row (
VARIANT_TYPE_VALUES, one entry perVariant.Typeofextension_api.json, so a type a new Godot adds fails--checkuntil it has one) runs one value through a generic Variant path against a value the engine built or compared (anExpressionevaluates the GDScript literal on the run's probe node):ret(the literal comes back as the Kotlin value),elem(inside an Array and a Dictionary),arg(the Kotlin value throughObject.call("set_meta", ...), alone and in containers, equal to the literal by the engine's own==) andin(the literal emitted to a Kotlin lambda's Variant signal argument). The comparison is exact: a PackedInt32Array element must arrive as anInt, a PackedFloat32Array one as aFloat. A path a type has no row on carries its reason in the entry (Kotlin has no distinct value for a StringName or a packed array as an argument; a Callable or Signal decodes tonull). The inventory page also lists, per typed-Array argument kind the iOS generator emits, the rows that pass such an array, and--checkfails on a kind no row passes.
Every path a row touches is under the run's own directory, user://kanama-api-exercise/<pid>-<random>/,
which the runner creates with its fixtures (fixture.txt with an extended attribute, fixture.mp3,
fixture.wav, sub/) before the first row and removes after the last (teardown fails when it is still
there; the shared parent is removed once empty). Every worktree's example project shares one user://,
so a per-run directory is what lets two smokes run at once without deleting each other's fixtures. Setup
also removes the directories of earlier runs that crashed before their teardown: those whose fixture is
older than an hour (by age alone; OS.is_process_running only knows the caller's own children, so it
would call a concurrent run in another process dead). FileAccess.create_temp and DirAccess.create_temp take no path;
they create a kanama-api-exercise-* entry in the OS temp directory that is removed when the row frees
the result. A static returning Error is given arguments that make it fail (an existing directory, a
missing file, a copy onto itself), and three of those print the engine's own error line on purpose.
The rows are a Kanama test hook and never ship: they compile only into a build made with
-PkanamaApiExercise=true (desktop and the Android plugin copy) or, on iOS, with the self-tests
(-PkanamaIosSelfTest=true, through iosMain only). Every publish* task, packageDistributions,
the kit and store package* tasks and installAddonJar fail on a flagged build, and local_ci runs
generate_api_exercise.py --check-jar on the published and the installed kanama.jar (the same check
reads an AAR's classes.jar: CI's Android lane and android_export_minified.sh run it on the runtime
AAR, and the Android plugin build refuses a release variant with the flag). Where they run:
- Desktop:
runtime_smoke.shbuilds the example addon with the flag (only there; local_ci's "external addon install" stage builds the user-shaped jar without it) and runsapi_exercise_smoke.tscnwith the project settingkanama/debug/api_exercise=true. The hook (ApiExerciseHook, beside the signal self-test incallFrame) runs the rows on the first frame and prints[kanama] API EXERCISE: <n> passed, <m> failed, <w> weak, <k> known, <r> reach, <e> excluded in <ms> msand one[kanama] API EXERCISE FAIL: <helpers> <row> <what>per failure.KANAMA_API_EXERCISE=1forces a run without the setting andKANAMA_API_EXERCISE_TRACE=1prints a line before each row and its verdict after it (= Ppassed,= Wweak,= Rreached,= Ffailed), which is how a row that prints an engine error, hangs or crashes is found (run every row headless before adding a device run of new rows). The smoke runs with the trace on, so a crash names the row it happened in. A method whose call aborts the engine itself (an index Godot does not bounds-check before aCRASH_BAD_INDEX) is excluded inMETHOD_OVERRIDESwith that reason. - Android: the same hook on ART, run by
KANAMA_ANDROID_API_EXERCISE=1 scripts/android_smoke.sh(the runtime AAR built with the flag,kanama/debug/api_exercisewritten into the demo'sproject.godotfor the run,kanama/debug/api_exercise_tracewithKANAMA_ANDROID_API_EXERCISE_TRACE=1); see Android backend. - iOS:
ApiExerciseSelfTest.ktruns the same rows after the frame-1 self-test rows and prints[kanama][ios][kn] OBJECTCALLS SELFTEST (api exercise): ... faults=<f> expected=<e> in <ms> ms, a line both device runners require. A FAULT the shim prints while a row runs fails that row by name (the runner compares the shim's fault count before and after it), as well as the count.
A row that fails on one platform for a gap already tracked is listed in KNOWN_FINDINGS (row, platforms,
the failure text it excuses, reason, where it is tracked): it still runs there. A C row checks the
wrapper's own result before it calls the Variant path, and only a failure of the Variant-path half
(an A row's read-backs) whose message contains that text prints KNOWN: instead of FAIL: and counts
as known; any other failure fails, and when the row passes the run fails with "known finding no longer
reproduces" until the entry is removed. --check fails on an entry that names no generated row.
After a Godot bump, run the rows headless (runtime_smoke.sh) before any device run: a class the new
version adds gets rows it has never run (see the upgrade runbook's "API exercise" step).
Web cannot share these rows (its wrapper tree is the contract's, not the shared one): its exercise is
one row per Web call shape, generated by scripts/generate_web_exercise.py into the web3d fixture and
run by the Web matrix. See Web backend: Validation Fixtures.
Value-Type Audits¶
The 19 builtin value types are ONE hand-written set under
src/commonMain/kotlin/net/multigesture/kanama/types since task 104 step 2 — the
the module's JVM and iOS targets and the Android copy task all compile those
files, and neither platform keeps a copy. Only Real.kt is per platform
(generated at build time on desktop, hand-written on iOS, written by the plugin
build script on Android) — as GodotHandle was until task 104 step 3 moved it into
the shared tree over RawSegment.
A shared body reaches the engine only through the builtin-call facade
net.multigesture.kanama.binding.runtime.BuiltinFrame / BuiltinMethod, declared once as
internal expect classes in src/commonMain/.../binding/runtime/BuiltinFrame.expect.kt and
implemented over Panama/FFM in src/jvmMain/kotlin/binding/runtime/BuiltinFrame.kt (Android gets
it through the source remap) and over the C shim in src/iosMain/.../binding/runtime/BuiltinFrame.kt,
so adding a member to one half without the other is a compile error at the edit. A call allocates
nothing: the generated member writes its base and arguments into the thread's frame slots and
calls through one constant downcall (task 134 B). The VT_*/PT_* wire numbers are common
const vals in BuiltinTags.kt — values, which an expect declaration cannot carry.
Which methods are engine-computed is a policy, not a preference: a method with a
transcendental (sin/cos/atan2/exp/pow) or a long body — Euler angles,
orthonormalization, shortest-arc slerp — calls the builtin; exact arithmetic
(operators, dot, lerp, moveToward, rect/AABB tests, is_normalized's epsilon
comparison) is plain Kotlin with Godot's operand order, so it costs no round trip
and is never slower than GDScript. Value-type helpers that mirror
Godot builtin methods should call the matching builtin unless the local
implementation is deliberately proven equivalent. Use the audit script when
editing types/*.kt:
python3 scripts/audit_value_type_wrappers.py --api extension_api.json
The audit is report-only by default, and --strict is wired into local CI. It
also checks the builtin float ABI in its new shape: Godot's ptr-ABI passes a
Variant float argument as an 8-byte double whatever the engine's real_t
precision, so such an argument must be written with putDouble, never
as a putReal component. Reviewed local scalar
formulas are allowlisted in the script; any newly added Godot-named value helper
that does not call the builtin should be treated as suspicious until it is either
bound to Godot's builtin or deliberately added to the reviewed list with focused
parity evidence.
Generated Operators and Methods¶
Every builtin operator and method of the value types is generated by
scripts/generate_builtin_ops.py from extension_api.json into two marked regions per class
(GENERATED BUILTIN MEMBERS in the class body, GENERATED BUILTIN STATICS in the companion);
the rest of each file stays hand-written, and a hand-written member with the Godot name wins (the
generator skips it). Operators and the methods in the generator's PURE_METHODS are Kotlin:
component-wise ones come from templates, composite ones call the hand-ported formulas in
types/BuiltinFormulas.kt (Godot's operand order, real_t width). Every other method calls the
engine through the thread's BuiltinFrame (base and arguments written by Godot type through the
generated types/BuiltinMarshalling.kt: real_t components, int32 for Vector2i-style types,
float32 for Color, a String built for the call; one BuiltinMethod constant per method). types/BuiltinScalarOperators.kt holds 2.0 * v and
points * transform. After editing the generator or a value type:
python3 scripts/generate_builtin_ops.py --write
./gradlew ktfmtFormat
python3 scripts/sync_kdoc_from_godot_docs.py --godot-docs "$GODOT_DOCS" --scope types --write
python3 scripts/check_builtin_coverage.py --report
The generator also writes the runtime smoke's probe pair (example_project/BuiltinParitySmoke.kt
and builtin_parity_ref.gd): every Kotlin-computed member over 256 fixed-seed random inputs and
every engine-backed one over 8, hashed and compared with GDScript; a changed formula that is not
Godot's to the bit fails the smoke and names the member. The Web build compiles the same value
types (task 134 D1), so WebBuiltinParityTest runs every Kotlin-computed entry compiled to Wasm
under Node against Godot's hashes recorded in scripts/fixtures/builtin_parity_expected.json,
and every Web-local port (WebLocalBuiltins, the transcendental methods Web runs in Kotlin)
against Godot's values recorded beside them (facade_values), within the float32 ulp bound
WEB_LOCAL_FACADE records per method with its reason. The runtime smoke's --verify-recorded
compares the engine on the machine it runs on with the same recording through the same bound: a
transcendental result's last bit depends on the platform's libm (Linux x86_64 and macOS arm64
differ), so a method built on sin/cos/atan2/asin/acos may not have bound 0, and the pure (hash)
entries may not call one at all; the generator fails on either (the generator also writes
WebBuiltinSignatures.kt, the argument and return Variant types the Web builtin-call crossing
needs for each engine-backed method). A pure method whose Godot counterpart has a MATH_CHECKS
guard lists the guard's formula in ENGINE_FALLBACK: it returns null for exactly the inputs the
guard rejects, and the generated member then calls the engine; after a
change to the probe, record them from a runtime smoke log (the smoke prints its path first; pin it
with KANAMA_SMOKE_LOG=/path/to/log) with
python3 scripts/generate_builtin_ops.py --record-parity /path/to/log, then
--write (the runtime smoke re-checks the recording with --verify-recorded).
scripts/check_builtin_coverage.py fails when an API operator or method has neither a Kotlin
member nor a recorded reason.
The builtin classes Kotlin represents with its own types (task 134 D2) are rendered by
scripts/builtin_boxed_methods.py, which generate_builtin_ops.py imports, writes and checks:
Godot's String methods as extensions on kotlin.String (builtins/GodotString.kt), the
PackedByteArray methods on ByteArray and the other packed arrays' to_byte_array on their list
types (builtins/GodotBytes.kt), NodePath's methods into a GENERATED BUILTIN MEMBERS region of
types/NodePath.kt, and their method constants and the NodePath parse (builtins/BoxedMethods.kt).
An engine-run one goes through the boxed builtin call, UtilityCalls.callMethod (desktop/Android
in the thread's BuiltinFrame, held until its cells are destroyed and its return read; iOS
kanama_ios_godot_builtin_call_boxed; Web the builtin-call crossing), so only const methods may
be engine-run; the byte codecs (PBA_PURE) and NodePath's members (NODE_PATH_PURE, all but
hash) are Godot's code ported. No generated extension may take a name kotlin-stdlib or
java.lang.String already has for its receiver: scripts/stdlib_names.py --write records them
with javap (scripts/fixtures/kotlin_stdlib_names.txt, refreshed when the Kotlin version
changes), the generator gives such a Godot method a godot prefix, and check_builtin_coverage.py
re-reads the stdlib when it can and fails on a stale record or a colliding name. STRING_REASONS
lists only the methods the stdlib answers identically. The Callable and Signal members are
hand-written in the GodotCallable / GodotSignal roots; CALLABLE_DISPOSITIONS /
SIGNAL_DISPOSITIONS record which method each is, or why there is none, and
check_builtin_coverage.py checks every recorded member exists. The probe pair's bytes= row
compares the codecs with GDScript over random arrays (and the Web test with the recorded bytes
hashes), text= every engine-run and NodePath member on fixed samples, invalid paths and
out-of-range indices included.
For scalar Godot float method arguments, the ptrcall helper layout audit is
the ABI guard (it absorbed the narrower audit_scalar_float_abi.py, retired in
task 99 — see the Gates Index):
python3 scripts/audit_ptrcall_helper_layouts.py
Godot's scalar float ptrcall slot is 64-bit (JAVA_DOUBLE) even when
single-precision real_t value components are float32 in engine buffers (and in the
value types' storage; GodotRealSegment.readRaw/writeRaw move them); every helper with a
scalar float slot must use JAVA_DOUBLE, and only Color component storage may
use JAVA_FLOAT.
Integers follow the same rule: Godot's PtrToArg<int32_t> (and uint32_t, the smaller ints and
enums) converts through int64_t, so every scalar integer argument and return cell is an 8-byte
JAVA_LONG, written widened (toLong(), a range-checked uint32 as its unsigned value) and read
back narrowed (get(JAVA_LONG, 0).toInt()). JAVA_INT is only the component storage of
Vector2i, Vector3i and Rect2i. The same holds for a virtual Kanama implements: the engine's
r_ret is PtrToArg<m_ret>::EncodeT, an int64 for an int or Error return and a whole Variant
for a Variant return. A 4-byte cell works by accident (the JVM rounds a native allocation up to
8 bytes, malloc to 16, and a little-endian read of the low half is the int), so no smoke or memory
tracker sees it: the audit guards it. An Array or Dictionary virtual return arrives already constructed
(Godot's Array ret; allocates its storage). On desktop and Android a virtual writes such a
return only through BuiltinTypes.writeVirtualReturn(VariantType.<kind>, rRet) { ... }: the block
builds the return into a cell of Kanama's own, and only then is Godot's value destroyed and the
built one moved in, so a throw inside the block leaves Godot's value intact. The iOS shim calls
kanama_ios_release_virtual_*_return right before it builds. A cell Kanama allocated itself is
uninitialised and is never destroyed.