Open-Source Wikis

/

Godot

/

Systems

/

Core foundations

godotengine/godot

Core foundations

Purpose

core/ is the bottom layer of the engine. It defines the Object base class, the reflection registry (ClassDB), the Variant value type, math primitives, container templates, OS abstraction, file I/O, the resource system, the input layer, and the GDExtension entry point. Everything above core/ (scene, servers, modules, editor) depends on it; nothing in core/ depends on anything above it.

Directory layout

core/
├── config/         Engine, ProjectSettings, GlobalConstants
├── crypto/         Crypto, hashing, certificates
├── debugger/       Engine debugger client/server protocol
├── error/          Error macros, error logger
├── extension/      GDExtension C ABI and class loader
├── input/          Input map, action processing, gamepad/joypad
├── io/             Resource loader/saver, FileAccess, packed file (PCK), HTTP, marshalls
├── math/           Vector2/3/4, Basis, Transform, AABB, Quaternion, Plane, Rect2, Color, RNG
├── object/         Object, ClassDB, MethodBind, Signal, Callable, MessageQueue, WorkerThreadPool
├── os/             OS abstraction (file, thread, mutex, semaphore, mutex, time, mainloop, midi)
├── profiling/      Performance/profiler hooks
├── string/         String, StringName, NodePath, translation, locales
├── templates/      Vector, HashMap, RBMap, RingBuffer, Pair, RID, RID_Owner
└── variant/        Variant, Array, Dictionary, packed arrays, Callable, variant_op tables

Object, ClassDB, MethodBind

The reflection model is the single most important thing to internalize. Three components carry it:

Type File Role
Object core/object/object.h (object.cpp ~76 KB, object.h ~47 KB) Base class. Holds an ObjectID, a class name, a ScriptInstance pointer, and a per-instance dictionary of metadata.
ClassDB core/object/class_db.h Static registry of every native class. Maps class name → constructor + parent + method/property/signal lists.
MethodBind core/object/method_bind.h, method_bind_common.h Templated trampoline that converts a Variant array into a typed C++ call and back.

Every native class declares a static void _bind_methods(). Registration is performed by macros that expand to:

ClassDB::bind_method(D_METHOD("get_position"), &Node2D::get_position);
ClassDB::add_property("position",
    PropertyInfo(Variant::VECTOR2, "position"),
    "set_position", "get_position");
ADD_SIGNAL(MethodInfo("renamed"));

The expansion picks up parameter and return types via GetTypeInfo<T> (core/variant/type_info.h) so the editor inspector and scripting glue can render the right widget and convert Variants on the fly.

make_virtuals.py (core/object/make_virtuals.py) generates gen/method_bind_*.gen.inc files at build time so virtual-method binding works for every arity without manual templating.

ObjectID and lifetime

ObjectID (core/object/object_id.h) is a 64-bit handle that combines a generation counter with the index in a global object table. ObjectDB::get_instance(id) returns nullptr after the original object has been freed, even if a new one is allocated at the same address. This is how callbacks and signals can safely refer to objects without shared ownership.

Script instance

Object::set_script(...) attaches a Ref<Script>. The script language creates a ScriptInstance (core/object/script_instance.h) that hooks property get/set, method call dispatch, signal emission, and notifications. This is what GDScript and C# plug into.

Variant

Variant (core/variant/variant.h, ~95 KB cpp) is a tagged union of:

  • NIL, BOOL, INT, FLOAT, STRING
  • VECTOR2, VECTOR2I, RECT2, RECT2I, VECTOR3, VECTOR3I, TRANSFORM2D, VECTOR4, VECTOR4I, PLANE, QUATERNION, AABB, BASIS, TRANSFORM3D, PROJECTION
  • COLOR, STRING_NAME, NODE_PATH, RID, OBJECT, CALLABLE, SIGNAL, DICTIONARY, ARRAY
  • PACKED_BYTE_ARRAY, PACKED_INT32_ARRAY, PACKED_INT64_ARRAY, PACKED_FLOAT32_ARRAY, PACKED_FLOAT64_ARRAY, PACKED_STRING_ARRAY, PACKED_VECTOR2_ARRAY, PACKED_VECTOR3_ARRAY, PACKED_COLOR_ARRAY, PACKED_VECTOR4_ARRAY

Operations on Variant are dispatched through generated tables:

  • variant_op.cpp (~94 KB) — binary/unary operators per (type-left, type-right) pair.
  • variant_setget.cpp (~62 KB) — indexer/keying tables (e.g., vec.x, dict["k"]).
  • variant_call.cpp (~159 KB) — built-in method dispatch (e.g., Array.push_back).
  • variant_construct.cpp — explicit constructors (e.g., Vector3(x, y, z)).
  • variant_utility.cpp (~66 KB) — global utility functions exposed to scripting (abs, sin, print, lerp, …).

variant_parser.cpp (~71 KB) parses the textual .tres/.tscn form back into Variant graphs.

Math

core/math/ contains vector/matrix types and primitives:

Type Purpose
Vector2, Vector2i, Vector3, Vector3i, Vector4, Vector4i Float and integer vectors
Basis, Transform2D, Transform3D, Projection Rotations and transforms
Quaternion 3D rotations (used heavily in animation/physics)
Rect2, Rect2i, AABB 2D/3D axis-aligned bounding boxes
Plane 3D planes
Color RGBA color (linear or sRGB)
RandomPCG PCG random number generator (random_pcg.h)
Triangle*Mesh, ConvexHull* Computational geometry helpers
Geometry2D, Geometry3D Static helpers (intersect, clip, decompose, triangulate)
BVH, Octree, BVHTree Spatial acceleration structures
delaunay_2d, delaunay_3d Triangulation
bvh_* Bounding-volume hierarchy used by physics + rendering culling

Float vs double is selectable at build time with precision=double. Symbols are defined as real_t so the same code compiles either way.

Containers

core/templates/ is Godot's STL replacement (the engine intentionally does not use <vector>/<unordered_map> to keep ABI control and game-friendly memory characteristics):

Template Purpose
Vector<T> COW dynamic array (the workhorse)
LocalVector<T> Non-COW vector for local hot paths
HashMap<K,V> Open-addressed hash map
HashSet<T> Hash set
RBMap<K,V>, RBSet<T> Red-black tree map/set
OrderedHashMap<K,V> Insertion-order preserving
RingBuffer<T> Lock-free single-producer ring
Pair<A,B>, Triplet<...> Small composites
RID, RID_Owner<T> RID tables for servers (see below)
SafeNumeric<T>, SafeRefCount Atomic primitives
SelfList<T>, SelfList<T>::List Intrusive doubly-linked lists
PagedAllocator<T>, PagedArray<T> Pool/arena allocators
Cowdata Internals of COW Vector/String

RID_Owner<T> is what every server uses to vend opaque handles for resources, instances, etc. It pages large arrays so RIDs stay small and cheap to allocate.

OS abstraction

OS (core/os/os.h) is the singleton interface for OS-level capabilities: time, environment variables, process spawning, dynamic library loading, clipboard, file system roots, and the engine's exit code. Each platform supplies a subclass (e.g., OS_LinuxBSD, OS_Windows, OS_MacOS, OS_Android, OS_IOS, OS_Web) under platform/<name>/ that implements the abstract methods.

Sibling primitives:

  • Thread (thread.h) — wraps std::thread with a stable interface (start, wait_to_finish).
  • Mutex, BinaryMutex, SafeBinaryMutex, Semaphore, RWLock — synchronization primitives, mostly C++11-backed.
  • MainLoop (main_loop.h) — the abstract per-frame driver that SceneTree subclasses.
  • MIDI (midi_driver.h) — abstract MIDI interface plus per-platform impls under drivers/.
  • Time (time.h) — high-resolution timer and date/time helpers.

I/O and resources

core/io/ covers the I/O surface area:

Component File Role
FileAccess file_access.h Abstract file with backends for filesystem, encrypted, packed, compressed, network
DirAccess dir_access.h Directory iteration
Resource resource.h Reference-counted, serializable, path-tracked asset base class
ResourceLoader / ResourceSaver resource_loader.h, resource_saver.h Format-pluggable load/save (binary, text, imported caches)
ResourceFormatLoader resource_format_* One per format. Built-ins: binary, text, image. Modules add more (gltf, mp3, ogg, …)
PackedData file_access_pack.h The PCK pack file format used by exported projects
JSON json.h JSON parser/serializer (used by GDExtension API dumps and tooling)
XMLParser xml_parser.h XML pull parser, used by class reference docs
Marshalls marshalls.h Variant binary serialization (var_to_bytes/bytes_to_var)
HTTPClient, HTTPRequest http_client.h Async HTTP client (used by editor + multiplayer)
Compression compression.h Wrappers over zlib, zstd, gzip
image.h / image.cpp image.h CPU-side Image (pixel manipulation, format conversion, mipmap generation)
IP ip.h DNS resolution and hostname helpers
StreamPeer* stream_peer*.h Buffered byte streams with TLS, GZip, TCP variants

Input

core/input/ aggregates input from the display server, MIDI, and joypads:

  • InputEvent* types (key, mouse, joypad, screen touch, magnify gesture, MIDI, action) — see input_event.h.
  • Input — the global singleton that tracks current key/button state, joypad axes, and an action map populated from project settings.
  • InputMap — maps action names to event sets; loaded from project.godot and editable per-platform.
  • ShortcutMap — keybinding sets (used by the editor).

Object messaging

Three primitives let objects communicate without tight coupling:

  • Signals — declared in _bind_methods via ADD_SIGNAL, emitted with emit_signal, connected via Object::connect. Signal handlers are stored as Callables.
  • Callables — first-class function/method references (core/variant/callable.h). Backed by either a method on an Object, a free function, a lambda, a bound version of any of the above, or a custom subclass.
  • MessageQueue (core/object/message_queue.h) — the buffer behind Object::call_deferred and set_deferred. Drained between frame phases on the main thread.

Worker thread pool

WorkerThreadPool (core/object/worker_thread_pool.cpp, ~32 KB) is a fork-join task scheduler with a fixed worker count. Two task shapes:

  • Single tasks (add_task(Callable)) for one-off work.
  • Group tasks (add_group_task(Callable, elements, tasks_needed)) that fan out a numeric range across N workers.

It is used by the resource loader, the navigation mesh baker, the lightmap baker, the GDScript compiler's analyzer pool, and any subsystem that wants parallelism without spinning up its own threads.

GDExtension

core/extension/ implements the C ABI Godot exposes to native libraries (replacing the older "GDNative"). A GDExtension .so/.dll/.dylib is loaded at runtime, hands the engine a list of class registrations, and from then on its classes appear in ClassDB like any other native class.

Highlights:

File Purpose
extension/gdextension.h, gdextension_interface.h The C ABI declarations
extension/gdextension_loader.h Loads .gdextension config files and dlopens the library
extension/gdextension_manager.h Tracks active extensions and rebinds classes on reload
extension/gdextension_compat_hashes.h Method-hash map for backwards-compatible API changes

bin/godot --dump-extension-api writes extension_api.json, a full machine-readable description of the API that consumers (e.g., godot-cpp, the C# bindings, third-party language bindings) generate code from.

Project settings + engine config

  • Engine (core/config/engine.cpp) — global frame counters, target FPS, time scale, build info, singletons table.
  • ProjectSettings (core/config/project_settings.cpp) — reads project.godot/project.binary, exposes setting overrides. Settings can be overridden per "feature tag" (e.g., mobile, web, s3tc) so different platforms see different effective values.

How it works

graph LR
    Script -->|Variant args| MB[MethodBind]
    MB -->|typed C++ call| ObjectM[Object method]
    ObjectM -->|return Variant| Script
    Script -->|emit signal| Signal
    Signal -->|invoke| Callable
    Callable --> ObjectM
    Loader[ResourceLoader] -->|FileAccess| Disk[(disk / PCK / network)]
    Loader -->|Resource graph| Object
    WorkerPool -->|parallel tasks| ObjectM

Entry points for modification

  • Adding a new built-in type → register in core/variant/variant.h, add a Variant::Type enum, extend the operator/setget/call tables. Expensive — rare.
  • Adding a new utility math function → put it in core/math/math_funcs.h or variant_utility.cpp (and bind it in the latter).
  • Adding a new file format → create a ResourceFormatLoader/ResourceFormatSaver pair and register them in register_core_types.cpp. Module-level formats register in their register_module_types.
  • Tweaking RTTI behaviour → core/object/class_db.cpp is where method/property/signal lookup lives; tread carefully.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Core foundations – Godot wiki | Factory