Actors

Chuck Smith edited this page 2026-11-25 01:11:10 +00:00 · 1 commit

Actors: design note (issue #59)

Status: decided, 2026-11-19 (user: every recommendation of section 16); nothing implemented yet. Rewritten the same day after the user's review (editor-first, our own names, the Mass comparison added). Next: step 1 of section 15. #59 comes before #3 on the roadmap (#25), because #3's "geometry and lights as components" (#52 step 6) takes its shape from the parts here. Section 16 lists the decisions.

1. The direction: editor-first, programmable

The user chose an actor model on 2026-11-19 (after Docs/Ecs.md 10.8) so that mesh, light, camera and so on are different class types, and asked for the best scripting fit for Primal, not a copy of Unreal.

Two questions are easy to mix up here:

  1. Typed parts: a mesh, a light and a camera are classes with their own functions, and a game can derive from them. Unreal has this (UStaticMeshComponent). Unity has it too (MeshRenderer, Light are component classes), and so does Godot (MeshInstance3D, OmniLight3D are node classes). This note keeps it.
  2. Where a thing is put together:
    • code-first: a C++ constructor creates the parts (Unreal's CreateDefaultSubobject);
    • editor-first: the parts are composed in the editor and saved as an asset, and code attaches behavior (Unity's prefabs, Godot's scenes with a script on the root, Unreal's Blueprints on top of a C++ class).

Primal goes editor-first, with code as an option:

  • The prefab is the unit of reuse. A prefab is a tree of parts with their values, made in the editor and saved as an asset.
  • Scenes place prefabs, and game code spawns them.
  • A prefab's actor may have a C++ class. The class gets typed access to the prefab's parts by name, and holds the logic.
  • A class may also create default parts in its constructor when code is the handier place (a part the class always needs). The editor shows them as part of every prefab of that class.

Why this fits Primal:

  • Game code is C++ only (#47 decided against C#, and there is no visual scripting), so the editor is the only place where a non-programmer composes anything. Code-first construction would make every new kind of object a C++ change.
  • The editor work of #52 step 5 (the scene tree, reflected fields for every type, several scripts per entity) is most of a prefab editor already.
  • #13 rewrites the editor anyway, so prefab editing can be designed into it.
  • The saved form is the same for both ways of building (parts by name with their values, section 10). A constructor's default parts and a prefab's parts load through one path.

2. Names

Concept Primal Unreal Unity Godot
A placed or spawned thing Actor Actor GameObject (root) scene instance
Logic without a place in the world Behavior (today's script) ActorComponent MonoBehaviour script
A piece with a transform: mesh, light, camera, ... Part (MeshPart, PointLightPart, CameraPart) SceneComponent GameObject + component Node3D subclass
An editor-made, reusable actor Prefab Blueprint class Prefab PackedScene
The low-level ECS handle Entity Mass entity Entity (DOTS) —
  • Part and the ECS's component are different words on purpose: a part is an object that game code and the editor see, and a component is plain data in a chunk.
  • Namespaces:
    • primal::actor holds Actor, Behavior, Part and the engine's parts;
    • primal::ecs and primal::game_entity::Entity stay as they are.

3. The model in one paragraph

An actor is an object, of the plain Actor class or of a game's class derived from it. It owns:

  • behaviors: logic, today's scripts;
  • a tree of parts under its root part. Every part is an object of a part class and owns one ECS entity.

A part's entity holds:

  • its transform, relative to the part it's attached to, so the attachment tree is the entity hierarchy of #52 step 1;
  • its data: MeshRenderer, PointLight, Camera, a game's PRIMAL_COMPONENT structs.

The actor's transform is its root part's. Engine systems never see the objects: they query the entities' data. Game code and the editor use the objects, whose typed functions read and write that data in the ECS.

"Turret" prefab, actor class Turret                ECS world (game_entity::world())
├─ root: Base  (MeshPart) ──────────────────────▶ entity 12: Position Rotation Scale ... MeshRenderer ActorOwner
│   └─ Head    (MeshPart) ──────────────────────▶ entity 13: ... Parent{12} HierarchyDepth{1} MeshRenderer ActorOwner
│       └─ Flash (PointLightPart) ──────────────▶ entity 14: ... Parent{13} HierarchyDepth{2} PointLight ActorOwner
└─ behaviors: Aim, Health                          (objects only, no entity)

4. Where things live

ECS (data, entities) Objects (game code, editor)
Transform of a part transform::Position, Rotation, Scale (local to the part it's attached to) and the derived ones; Parent, HierarchyDepth Part::position(), set_local_position(), attach_to(): thin calls into the ECS
What to draw MeshRenderer (geometry content id, materials, visibility, LOD bias) MeshPart (set_mesh(), set_material(), ...; game subclasses)
Lights DirectionalLight, PointLight, SpotLight, AmbientLight (plain data) DirectionalLightPart, PointLightPart, SpotLightPart, AmbientLightPart
Cameras Camera (projection parameters) CameraPart
A game's bulk data its PRIMAL_COMPONENT structs (as today) read and written through the part or actor (get<T>(), write<T>())
Ownership ActorOwner{actor id} on every entity of an actor the Actor owns its parts and behaviors
Behavior, state that isn't bulk data actor and behavior member variables, update(), begin_play()
Class identity, part names not needed by systems the object (reflected type, name); the editor and saved files use it

The rule: data the engine processes for many things at once is an ECS component. Everything else is an object member. A part object holds its entity id, its name, its actor, and nothing the ECS already has. It caches no transform or render data, so the ECS stays the only copy, and systems stay correct whenever gameplay code writes.

5. How actors interact with the ECS

5.1 Systems see entities, never actors

The transform update, render preparation (the frame packet of Docs/RendererThreading.md), light culling and later physics are ECS systems and queries over chunks, on the job system with their declared access, as today:

  • render preparation asks for every entity with LocalToWorld + MeshRenderer;
  • light culling asks for the lights with their world transforms.

The mesh of a turret, the mesh of a door and a mesh entity that a crowd system made without any actor land in the same chunks and the same loops. Everything #31 and #52 measured stays: the batched transform update, change detection per chunk, parallel render preparation.

5.2 Class types don't split archetypes

An archetype is the set of ECS components an entity has, not the class of the object that owns it:

  • MeshPart, a game's FlickeringMeshPart : MeshPart, and a skinned mesh part one day all have transform + MeshRenderer, so they share chunks.
  • A subclass that needs bulk data of its own adds a PRIMAL_COMPONENT struct to its entity, and only that moves it to another archetype.

So many part classes cost nothing in iteration speed. The class lives in the object, where the editor and the saved files need it.

5.3 Attachment is the entity hierarchy

attach_to(part, rules) is game_entity::set_parent() on the part's entity, and "keep world" or "keep relative" is transform::KeepWorld. #52 step 1 carries over:

  • world space for the short names, local_* relative to the parent;
  • children updated level by level on the job system;
  • cycles refused.

Moving an actor writes its root's Position, and the rest follow in the next update_matrices().

Two rules change:

  • Attaching one actor to another (a sword in a hand) parents the sword's root entity to the hand's entity. The sword stays its own actor: its ActorOwner doesn't change.
  • "Removing an entity removes its children" (#52 step 1) becomes this: destroying an actor destroys its own entities and detaches other actors attached to it, keeping their world transform. A plain entity attached to an actor's part goes with the actor, as today.

5.4 Every part is an entity: the cost

A part's entity has:

  • the six transform components;
  • Parent + HierarchyDepth (except the root);
  • ActorOwner;
  • its own data.

That is about 230 bytes per part before the mesh or light data, so an actor with five parts is about 1.2 KB in chunks plus its objects. 5,000 such actors are 25,000 entities, inside what the transform benchmarks covered (100,000).

A part that only groups others (an empty Part) is an entity with a transform and nothing else. There's no special case for "a part without a transform of its own": one transform per entity is the ECS's rule, and two meshes in one entity would need arrays inside a component that render preparation can't batch.

5.5 Structural changes: spawning and destroying

The ECS rule stays: entities and components are created and removed between frames or at the sync point, and inside a frame through queues.

  • actor::spawn(prefab, transform) inside a frame queues the spawn and returns a handle that becomes valid at the next sync point. There:
    • the actor object is constructed, which creates its class's default parts;
    • the prefab's parts are created and its values applied (section 6);
    • begin_play() runs, as scripts do today.
  • Between frames (loading a scene, the editor), spawn is immediate.
  • destroy() is queued. At the sync point:
    • the behaviors' end_play(), then the actor's;
    • the entities go, deepest first;
    • then the objects.
  • Adding a part or a behavior to a live actor follows the same rule: queued inside a frame, usable from the next frame.

This costs one frame of latency on spawns from update(), as queue_create() has today. In return, the ECS stays lock-free while systems run.

5.6 Reads and writes from objects

A part's functions read and write its entity's data with get<T>() and write<T>(), immediately, as scripts do since #52 step 2. For example, MeshPart::set_visible(false) writes MeshRenderer::visible and marks the chunk, and that frame's render preparation sees it through the chunk version. Nothing is cached in the object, so nothing needs syncing.

Actor and behavior updates run one at a time on the frame thread, before the game systems (SystemGroup::game_update) and the transform update, so these writes don't race. The way to parallel gameplay code later is unchanged (Docs/Ecs.md 9.6: queued writes, or declared access).

5.7 Behaviors or systems

Two kinds of game code stay side by side, and the docs should say when to use which:

  • A behavior's update() is logic for one thing: a door, a turret, a player controller. Actors and behaviors that don't override update() aren't ticked at all (a flag the generator sets when the class overrides it), so a scene of static props ticks nothing.
  • A system (world().add_system<...>() from a game-level script, #52 step 4) is the same logic over many things. 10,000 spinning pickups are one system over a Spin component, not 10,000 updates.
  • They mix: a prefab's part can carry the Spin component (set in the editor like any other component), and the game's spin system turns it with all the others.

5.8 Plain entities next to actors

Not every entity belongs to an actor:

  • Bullets, particles, crowd agents and debris can be plain entities (made through world(), game_entity::create(), or from a prefab's data alone, section 11), with no objects. This is the Mass model.
  • Scenes, prefabs and the editor deal in actors.
  • A query that cares about the owner reads ActorOwner and skips entities without it.

5.9 Rendering, lights and cameras: what #3 builds on

This is why #59 comes before #3. Today:

  • geometry is an engine-internal array indexed by entity, which creates render items;
  • lights and cameras are renderer objects in renderer tables (graphics::create_light()) that point back at an entity.

With parts they become ECS data:

  • Meshes: MeshRenderer{geometry content id, material set, flags} on a mesh part's entity. #3's render preparation queries it with LocalToWorld to build the frame packet. The render item cache (pipelines, buffers) stays the renderer's, keyed by geometry and materials, and is refreshed when a MeshRenderer chunk changes.
  • Lights: PointLight, SpotLight, DirectionalLight, AmbientLight as plain data. Light culling gathers them by query, and the light set becomes a field.
  • Cameras: Camera as data on a camera part's entity. A surface renders the camera entity it is given.

#59 defines these types and the part classes that write them; #3 rewrites the renderer to read them (#52 step 6).

5.10 Limits to watch

  • 64 component types (ecs::max_component_types, u64 masks):

    • in use today: 8 for transforms, plus a game's own;
    • this adds MeshRenderer, four light types, Camera and ActorOwner, about 16 for the engine.

    Widening the masks to 128 bits is a small, measured change in World.cpp when a game needs it.

  • Per-entity writes cost about 4 ns (record → archetype → chunk), against about 1 ns for a plain array. Gameplay objects writing a few values each frame won't notice; bulk work belongs in systems (5.7).

6. Prefabs

A prefab is an asset: one actor described as data.

  • The actor class: optional, by name. Without one, the actor is a plain Actor.
  • Its parts: each with a name (unique in the prefab), class, attach parent (by name), local transform, the values of its reflected fields, and its entity's reflected components.
  • Its behaviors: each with its class and field values.
  • The actor's own field values.

Building an actor from a prefab (spawning, loading a scene, the editor):

  1. Construct the actor object of the prefab's class. Its constructor may create default parts (section 7).
  2. Walk the prefab's parts. A part whose name matches a default part sets that part's values; any other part is created.
  3. Create the behaviors and apply the actor's, parts' and behaviors' values.
  4. begin_play(), unless in the editor.

A default part the prefab doesn't mention keeps the class's values. A prefab part that names a default part the class no longer creates is created as a plain part of the saved class, with a warning. This is how Unreal matches levels to class defaults: changing a class's constructor updates every prefab built on it.

Scenes and prefabs:

  • A scene is a list of actors. Each is either an instance of a prefab (the prefab, its transform, its name) or a one-off actor stored inline in the scene, in the same format as a prefab.
  • "Save as prefab" turns a one-off actor into an asset.
  • Editing a prefab updates every instance the next time the scene is opened or run, since instances store only what differs.

Overrides per instance (changing one placed turret's turn_speed):

  • First version: the instance's transform, name, and the reflected fields of the actor and its behaviors. Those are the values a level designer sets per copy.
  • Later: overriding any part's value (a different material on one copy), and nested prefabs (a prefab that places another prefab's actor attached to one of its parts). Both are decisions 6 and 7.

From code:

  • PrefabRef is a reflected field type. A behavior has a PrefabRef bullet{} field, the editor shows a picker of prefab assets, and actor::spawn(bullet, transform) spawns it.
  • actor::find_prefab("Turret") looks one up by name.

Built games: the prefabs a game uses travel with it (section 10). Content for built games in general is #33.

7. The game API (sketch)

An actor class for the "Turret" prefab. The prefab (made in the editor) has the parts Base, Head and Flash; the class adds logic, two reflected fields and one default part:

// Turret.h
#pragma once
#include "Turret.generated.h"

PRIMAL_ACTOR()
class Turret : public primal::actor::Actor
{
    PRIMAL_GENERATED_BODY()
  public:
    explicit Turret(const primal::actor::ActorInit &init);

    auto begin_play() -> void override;
    auto update(f32 dt) -> void override;

  private:
    PRIMAL_PROPERTY(.min = 0.f, .tooltip = "Degrees per second")
    f32 turn_speed{90.f};
    PRIMAL_PROPERTY()
    primal::actor::ActorRef<Player> target{};

    primal::actor::MeshPart *head{nullptr};
    primal::actor::PointLightPart *flash{nullptr};
};
// Turret.cpp
Turret::Turret(const actor::ActorInit &init)
    : Actor{init}
{
    // Optional: a default part every Turret has, whatever prefab it comes from. It may attach to the root or to
    // another default part (the prefab's own parts don't exist yet). Prefabs set its values by its name.
    add_default_part<actor::AudioPart>("Hum");
}

auto Turret::begin_play() -> void
{
    // The prefab's parts, by name and class: nullptr (and a logged warning) when the prefab has no such part.
    head = part<actor::MeshPart>("Head");
    flash = part<actor::PointLightPart>("Flash");
}

auto Turret::update(const f32 dt) -> void
{
    if (const Player *const player{target.get()}; player != nullptr && head != nullptr)
    {
        head->set_rotation(math::rotate_towards(head->rotation(), player->position(), turn_speed * dt));
    }
}

A behavior, reusable on any actor, that acts on one part chosen in the editor:

PRIMAL_BEHAVIOR()
class Blink : public primal::actor::Behavior
{
    PRIMAL_GENERATED_BODY()
  public:
    using Behavior::Behavior;
    auto update(f32 dt) -> void override;

  private:
    PRIMAL_PROPERTY(.tooltip = "The light that blinks")
    primal::actor::PartRef<primal::actor::PointLightPart> light{};
    PRIMAL_PROPERTY(.min = 0.f)
    f32 period{0.5f};
};

The pieces of the API:

  • Engine classes:

    • actor::Actor;
    • actor::Behavior (today's EntityScript, renamed and owned by an actor);
    • actor::Part (has an entity: entity(), the transform functions, attach_to(), children());
    • MeshPart, DirectionalLightPart, PointLightPart, SpotLightPart, AmbientLightPart, CameraPart, all derived from Part.

    Games derive from any of them. AudioPart above is an example of a later one.

  • Pointers to an actor's own parts and behaviors stay valid as long as the actor lives (it owns them, and they never move).

  • References with a generation (get() returns null when the target is gone) are reflected field types with editor pickers:

    • ActorRef<T> to another actor; it replaces today's game_entity::Entity fields;
    • PartRef<T> to a part of the same actor;
    • PrefabRef to a prefab asset.
  • Finding things:

    • part<T>("Name"), parts<T>(), behavior<T>();
    • actor::find_actors<T>() (a list per class);
    • owner() on a part or behavior;
    • actor::owner_of(entity) through ActorOwner.
  • Game-level scripts: GameScript stays (game mode, managers: logic with no actor). Whether it becomes a kind of actor later is not part of #59.

8. Lifetime

  1. Build (section 6; at the sync point, or immediately between frames). The constructor and the default parts come first, then the prefab's parts and the values.
  2. begin_play(): behaviors first, in their order, then the actor. The editor runs no frames, so nothing begins play there, as today.
  3. Each frame:
    • every ticking actor in spawn order: the actor's update(dt), then its ticking behaviors';
    • game systems, transforms, render preparation;
    • late_update() the same way.
  4. destroy() (queued): the behaviors' end_play(), then the actor's. Other actors attached to it are detached, its entities are removed deepest first, then the objects are deleted.

9. Reflection and the editor

Reflection. New markers for the generator (ReflectionTool/):

  • PRIMAL_ACTOR();
  • PRIMAL_BEHAVIOR(), which replaces PRIMAL_SCRIPT();
  • PRIMAL_PART().

Their fields work like script fields today: only PRIMAL_PROPERTY members. New field types: ActorRef<T>, PartRef<T>, PrefabRef. A part also shows its entity's ECS components (MeshRenderer's fields, a game's PRIMAL_COMPONENTs) through the reflection that already edits components by name (#52 step 5).

The editor:

  • Scene outliner: the scene's actors. Attached actors are indented under their parents, and prefab instances are marked. The tree from #52 step 5 becomes this one.

  • Details:

    • the actor's class and fields;
    • its part tree (drag to attach, "Add Part" with every part class, engine and game);
    • its behaviors ("Add Behavior");
    • the selected part's or behavior's fields, below.

    For a prefab instance, the parts are shown read-only in the first version; "Edit Prefab" opens the prefab.

  • Prefab editing: a prefab opens like a scene with one actor (its own tab or window). Saving it updates the instances.

  • Content browser: drag a prefab into the scene to place it. "Save as Prefab" on a one-off actor.

  • Add Actor menu: an empty actor, a mesh actor, the light and camera actors (small built-in prefabs), and the game's actor classes. Today's "Empty Game Entity", "Cube", light and camera items become those.

  • How much in WPF and how much waits for #13: decision 8. The view models are written to carry over either way.

10. Saved files: scenes, prefabs, game.bin v3

  • One actor record is used by prefab assets, one-off actors in scenes, and game.bin:

    • the actor class (name hash, or none);
    • the actor's fields;
    • the parts (name, class, attach parent by name, local transform, fields, the entity's components);
    • the behaviors (class, fields).

    Values are keyed by name hash, as in game.bin v2. An unknown class, part or field is skipped with a warning, and a missing value keeps its default.

  • game.bin v3:

    • a table of the prefabs the game uses (actor records);
    • then the scene: per actor, either a prefab index plus its overrides (section 6), or an inline actor record.

    Built games read prefabs from that table until #33 gives them content files. Version 2 files are not read (no backwards compatibility for game projects).

  • The editor's project files store prefabs as assets in the project's content folder, and scenes as lists of instances and one-off actors.

11. Promotion and demotion: the Mass comparison

Unreal's Mass framework can switch a thing between representations: a crowd agent far away is a cheap Mass entity drawn as an instanced mesh, and up close it becomes a full actor. Unreal needs machinery for this (MassRepresentation, actor spawners, "translators" that copy data between the actor and the Mass entity), because an Unreal actor is a heavy object with its own copy of the data.

Primal doesn't need that machinery, because an actor's data already is ECS data. An actor is objects attached to entities that exist on their own:

  • Demote: actor::release(actor) runs the behaviors' and the actor's end_play(), deletes the objects and removes ActorOwner. The entities stay where they are, keep their transforms and components, and keep rendering. Nothing is copied.
  • Promote: actor::adopt(root_entity, prefab) builds the actor's objects around the entity tree that is already there (matched to the prefab's parts), adds ActorOwner and begins play. Nothing is copied.
  • Data only: actor::spawn_entities(prefab, transform) makes a prefab's entities and components without objects: the cheap crowd version from the start, promotable later.

To match an entity tree to a prefab's parts, entities made from a prefab carry its part index (a small PrefabPart{prefab, part} component, only on entities made that way).

Like every structural change, adopting and releasing happen at the sync point. Rendering far-away crowds cheaply (instancing) is renderer work for #3.

Recommended: design for it now (ActorOwner as a removable component, objects that never own ECS data, the PrefabPart link), and build adopt/release/spawn_entities only when a game needs crowds (decision 9). Building the ECS in from the start is what makes this cheap.

12. The editor's two engine copies

Today the editor has two copies of the engine library:

  • EngineDLL's, whose world the editor's entities live in;
  • the game DLL's, used by script code.

Scripts don't care that these are different worlds, because the editor runs no frames.

Actors and prefabs break that. The editor builds actors to show and edit them: an actor class's constructor runs in the game DLL and creates default parts there, in the game DLL's own unused world. Two ways out:

  • (a) Forwarding: EngineDLL hands the game DLL a table of functions (create an entity, set a parent, add a component, world()), and the game DLL's copy of the engine calls those instead of its own state. That's work in every engine function that game code reaches, and it breaks silently when one is missed.
  • (b) One engine as a shared library (PrimalEngine.dll / libPrimalEngine.so) that EngineDLL, the game DLL and the game executable all link. One world, one registry, component ids the same everywhere; the type copying in EngineDLL/EditorSupport.cpp goes away. Docs/Preferences.md already plans this "for #13/#3".

Recommended: (b), as the first step of #59. It needs:

  • export macros on the engine's API;
  • CMake and MSBuild changes;
  • care that a game's types unregister when its DLL unloads, which they already do (release_imported_types()).

13. Alternatives considered

  • Code-first actors (the first version of this note, Unreal without Blueprints):

    • parts are created only in C++ constructors, and prefabs come later;
    • simpler to build and to unit-test;
    • but every new kind of object is a C++ change, and the editor only places and tweaks.

    Not recommended for a C++-only engine whose editor is its only non-code authoring tool.

  • Unreal's full object model (objects own the transform and render data, and the ECS goes or becomes an internal cache):

    • every engine function becomes a call on an object;
    • loses the batched transforms, the per-chunk change detection and the parallel render preparation that #3 is about to be built around;
    • undoes #31.

    Not recommended.

  • Unity's model as it is (every part is a GameObject, and behaviors attach to any of them; no actor):

    • this is today's Primal plus typed part classes and prefabs;
    • but it has no unit that owns a subtree (spawned, destroyed, attached and saved as one), no C++ class for the whole thing, and behaviors scattered over parts.

    The actor here is that unit; behaviors that act on one part reach it with PartRef (section 7).

  • Pure ECS with tags (Bevy: a "mesh" is an entity with a Mesh component, with no classes): fast and simple, but no part classes, no virtual behavior, no class for the whole thing. That is what the user doesn't want.

  • Several parts sharing one entity: impossible with one transform per entity (5.4).

14. What changes in existing code

  • Scripts: script::EntityScript → actor::Behavior, and PRIMAL_SCRIPT() → PRIMAL_BEHAVIOR(). Game projects are converted by hand, with no compatibility macros. GameScript stays.
  • game_entity::Entity stays as the ECS-level handle (systems, plain entities, Part::entity()). Its script-facing helpers (script<T>(), scripts(), find_script_in_children()) move to Actor.
  • Geometry, lights and cameras: their engine-internal arrays and renderer tables become ECS data (5.9). Until #3, either an adapter feeds today's renderer from that data, or rendering waits for #3 (decision 10).
  • Files: game.bin v2 → v3. The editor's scene model becomes actors and prefabs. EngineDLL/EditorSupport.* shrinks with 12 (b).
  • Tests: the EngineTest tests and GraphicsTests build their scenes from plain entities and keep working. The renderer test moves to actors and prefabs to exercise them.

15. Order of work

  1. This note and the user's decisions (section 16).

  2. One engine library (12 b), on both build systems, checked in the VM. Measure the game DLL's load time and frame times against today. Done 2026-11-19: section 17.

  3. Runtime:

    • Actor, Behavior, Part, ActorOwner;
    • spawn and destroy with the sync-point rules, attachment and detaching (5.3), ticking (5.7, 8);
    • ActorRef, PartRef, the find functions.

    Unit tests for each rule of 5.3-5.6. This absorbs #58 steps 1-2. Done 2026-11-19: section 18.

  4. The engine's parts and their data: MeshRenderer, the light types, Camera and their part classes. The renderer reads them through the adapter of decision 10, or #3 starts here. Done 2026-11-20: section 19.

  5. Reflection: the markers, the new field types and the generator. Done 2026-11-20: section 20.

  6. Prefabs and files: the actor record, prefab assets, building an actor from a prefab (section 6, with the default-part matching), game.bin v3. Unit tests for the matching and the warnings. This absorbs #58 step 3. Done 2026-11-20: section 21.

  7. The editor: outliner and details (section 9), prefab editing, save as prefab, the content browser drag, Add Actor. Done on the Windows desktop (user, 2026-11-20), where the editor runs on the real GPU; the Linux checks of its C++ follow on Linux or in CI. Done 2026-11-21: section 22.

  8. Conversion: game projects (the VM's ScriptTest, the templates, the new-script dialog → new behavior / new actor class), the docs. Then #3. Done 2026-11-21: section 23. #59 is closed.

Size: L, closer to XL with prefab editing. Steps 1, 5 and 6 are the largest.

16. Decisions

Settled on 2026-11-19 (user): an actor model, editor-first with prefabs as the unit, C++ classes optional; our own names (Actor, Behavior, Part, Prefab, Entity); no Mass-style switching machinery.

Decided (user, 2026-11-19): the recommendation of every item below, in brackets.

  1. Every part is an entity (recommended, 5.4), or parts without a transform of their own as a special case. [every part is an entity]
  2. Behaviors belong to the actor and reach a part through PartRef (recommended), or behaviors attached to individual parts (Unity's way). [on the actor, PartRef]
  3. Tick order: each actor, then its behaviors (recommended, simple and predictable), or all actors, then all behaviors. [each actor, then its behaviors]
  4. Spawning inside a frame waits for the sync point (recommended, the ECS rule, one frame of latency), or immediate with locking. [at the sync point]
  5. Default parts from constructors: allowed, matched to prefabs by name (recommended), or prefabs only, with no parts created in code. [allowed, matched by name]
  6. Overrides per instance, first version: transform, name, and the actor's and behaviors' fields (recommended); any part value later. Or all values from the start. [transform, name, actor and behavior fields]
  7. Nested prefabs (a prefab placing another prefab's actor) later (recommended), or in #59. [later]
  8. Editor scope in WPF: prefab editing and the outliner/details split in WPF now (recommended: it's how prefabs get made and tested until #13), or only the data model and files now, with the UI in #13. [in WPF now]
  9. Promotion/demotion (section 11): design for it now, build it when a game needs crowds (recommended), or build it in #59. [design now, build when needed]
  10. The renderer until #3: an adapter from the new ECS data to today's renderer (recommended: #59 can be checked visually on its own), or rendering stays on the old path until #3. [an adapter]
  11. One engine as a shared library first (recommended, 12 b), or forwarding tables (12 a). [shared library first]
  12. Plain entities stay public for mass gameplay (recommended, 5.8), or everything game code creates is an actor. [plain entities stay public]

17. Step 1 done: one engine library (2026-11-19)

What changed.

  • Build: the engine is one shared library, PrimalEngine.dll + PrimalEngine.lib (MSBuild) and libPrimalEngine.so (CMake, next to the programs in x64/<Config>/, found through RUNPATH $ORIGIN). A game executable's entry point moved out of it into the static library EngineMain (Engine/Core/Main{Win32,Linux}.cpp; new EngineMain/EngineMain.vcxproj, CMake target EngineMain). Game projects link PrimalEngine.lib;EngineMain.lib; in every configuration (a DLL doesn't pull WinMain in); the editor's upgrade rewrites Engine.lib, and Run copies PrimalEngine.dll (+ .pdb) next to the game.
  • Exports: PRIMAL_API (Common/CommonDefinitions.h) marks what other binaries call: the free functions of the API headers, the out-of-line members of classes (Window, Surface, Camera, Light, Entity, the transform handle, InputSystemBase, ecs::World, the script classes) one by one (never a whole class, which makes MSVC warn about every member type: C4251), the modules' functions (in the .ixx), engine_initialize()/update()/ shutdown(). The engine is built with hidden visibility on Linux, so a missing mark fails the Linux link as it does on Windows. jobs::Counter's two members are inline in the class (in a module they aren't implicitly).
  • One registry for every binary (Reflection/Reflection.cpp): a header's type registers once from each binary that includes it, so a name that is registered again by the same C++ type gives the first registration's index instead of an error. "The same type" is TypeInfo::identity, reflect::detail::type_identity<T>(): an FNV-1a hash of the compiler's name for the type (__PRETTY_FUNCTION__, __FUNCSIG__), the same in every binary of a process (one compiler); 0 in an anonymous namespace.
  • Game libraries that come and go: what EngineDLL did with the game DLL's exported tables (import_types() in EditorSupport.cpp) moved into the registry. EngineDLL brackets LoadLibrary with reflect::begin_library_load()/end_library_load(): types registered in between are copied (names, fields, enums, default values), at addresses that outlive the library; a later load refreshes the copies in place; a component whose size changed keeps the old copy, logged. reflect::release_library_types() before FreeLibrary clears the creators and field functions.
  • ECS component ids are the process's: ComponentInfo::identity (the same hash) finds a type another binary registered first, also for components that aren't reflected (transform::HierarchyDepth).
  • EngineDLL no longer calls the game DLL's exports: primal_get_types(), primal_get_script_creator(), get_script_names() and set_log_forward() are gone (from Components/Script.cpp); GetScriptCreator and GetScriptNames read the registry (scripts of the current load: they have a creator). The editor's C# is unchanged.
  • Log: forwarding is gone (log::detail::set_forward(), write_forwarded()), a game DLL logs into the one log. The ring buffer keeps its own copies of file names (a game DLL's names go away with it), and EngineDLL flushes the log before FreeLibrary.
  • Tests: UnitTests/GameLibraryTests.cpp loads a real game library (UnitTests/GameLibrary/, CMake target TestGameLibrary, dlopen) and checks one world, the same component ids for engine and game types, the library's script made by name, values and types that outlive an unload, its log message's file name after the unload, and a second load. CMake only (MSBuild doesn't build the library); on Windows the editor and ScriptTest check the same. UnitTests/GameExecutable/ is a game executable (game code + the engine library + EngineMain, target TestGame, in x64/<Config>/TestGame/ with a 12-byte game.bin): a game script runs three frames and quits; CTest (label graphics) and ci.sh's graphics step check its log. Linux had no program linking EngineMain before, which is how unexported engine_initialize()/update()/shutdown() got through to the VM.
  • Later: a shipped game as one static executable (Unreal's monolithic build), issue #60.

Measured (before → after):

Before After
Linux, renderer test, Release, vsync off, ms per frame 1.77 1.74
The same with 6,400 extra spheres 13.95 13.77
VM, ScriptTest.dll (DebugEditor) 4.5 MB 1.4 MB
VM, first LoadGameCodeDll in a process (warm file cache) ~3 ms ~3.3 ms
VM, LoadGameCodeDll again after an unload (median of 10) 0.8 ms 0.6 ms

Calls into the engine through the library's import table cost nothing measurable in a frame. PrimalEngine.dll is 4.6 MB (DebugEditor).

Checked: Linux clang Debug + Release and GCC Debug, the test game, UnitTests 218 (+ the game library test), GraphicsTests 21 with validation, ci.sh checks, clang-tidy, ASan/UBSan; the VM: all 4 configurations + 8 EngineTest variants, UnitTests Debug + Release, the renderer test on D3D12 and Vulkan in Debug and Release, ScriptTest's game DLL in EngineDLL and its executable, the editor opening ScriptTest and loading its game code. Desktop: plan doc A42.

Found: MSVC 14.52's link-time code generation crashes on UnitTests/JobTests.cpp with the engine as a DLL (plan doc B16); that file is compiled without whole-program optimization.

18. Step 2 done: the runtime (2026-11-19)

Where: Engine/EngineAPI/Actor.h (the game API: actor::Actor, Part, Behavior, ActorOwner, ActorRef<T>, PartRef<T>, spawn(), destroy(), owner_of(), find_actors<T>()), Engine/Actors/Actor.cpp (a new layer, Actors), Engine/Actors/ActorSystem.h (the frame's calls). Tests: UnitTests/ActorTests.cpp (14 cases) and an actor class in the game library test.

As designed: every part owns one entity with ActorOwner, attached like the part tree; the actor's transform is its root's; parts and behaviors are owned by the actor and never move; destroying an actor runs its behaviors' end_play() (the last added first), then its own, detaches other actors attached to it (keeping their place in the world), removes its entities with plain entities attached to them, then deletes the objects; an actor spawned between frames begins play at the next sync point (behaviors first, then the actor); each frame, the actors that tick, in spawn order: the actor's update(), then its behaviors'; late_update() the same way. Ids have a generation: a reference to a destroyed actor stays empty when its slot is reused.

Decided while building it (within the decisions of section 16):

  • The first part added is the root; an actor whose constructor adds none gets a plain Part named "Root". The root is created at the spawn transform (its local argument is ignored). Part names are unique in an actor and not empty.
  • Which calls are immediate: spawn() builds right away between frames and at the sync point, and queues inside a frame (the returned ActorRef works from the next frame on). destroy(), remove_part() and remove_behavior() are immediate between frames and queued otherwise; one queued at a sync point runs at the next one, so a destroy() in begin_play() lets the actor play one frame. add_part()/add_behavior() are immediate only (constructor, begin_play(), between frames: asserted), and queue_add_part()/queue_add_behavior() are for inside a frame, like game_entity::create()/queue_create(). Part::attach_to(), Actor::attach_to() and detach() are immediate at the sync point too, queued inside the update phases.
  • Class identity without RTTI: part<T>(), behavior<T>(), find_actors<T>() and the references check the class with a virtual is_a(); each class says PRIMAL_ACTOR_CLASS(Self, Base) in its body (a hash of the compiler's type name, the same in every binary). Written by hand until step 4, when PRIMAL_GENERATED_BODY() writes it. Subclasses match their base classes (find_actors<Turret>() includes a HeavyTurret).
  • Ticking without the generator: whether a class overrides update()/late_update() is found at compile time (decltype(&T::update) names the class that declares it last), so classes that don't aren't ticked, and an actor is in the tick list only when it or one of its behaviors ticks. The list is rebuilt when actors or behaviors change.
  • Order in the frame: at the sync point, the entity commands, then the actor commands, then scripts' and actors' begin_play(); in the update phases, game scripts, entity scripts, then actors (until step 7 turns scripts into behaviors).
  • Removing a plain entity (game_entity::remove()) detaches another actor's root attached to it instead of removing it, and removing an actor's entity directly asserts: an actor's entities go through actor::destroy() and Actor::remove_part().
  • Classes that games derive from have no out-of-line virtual function (~Actor() = default in the header), so their vtables and type info aren't hidden in the engine library (Docs/Preferences.md).
  • References are ids, not std::weak_ptr (user asked, 2026-11-19): ActorRef<T> is the actor's 32-bit id (index and generation), PartRef<T> the part's entity id; get() looks it up and checks the class. Why not shared_ptr/weak_ptr: an actor dies when game code destroys it (at the sync point, after end_play()), and a locked shared_ptr would keep it alive past that; an id can be saved in prefabs and game.bin and edited with a picker (step 4), an address can't; and an id is plain data, so it can sit in a PRIMAL_COMPONENT. Smaller and cheaper too (4 bytes, one index and a generation compare). Unreal's TWeakObjectPtr and Unity's instance ids work the same way. An actor's own parts and behaviors are plain pointers: it owns them and they never move.
  • A pointer converts to its reference implicitly (target = turret;): both constructors carry a NOLINT for google-explicit-constructor, since the conversion loses nothing. Kept implicit (user, 2026-11-19).
  • The game's shutdown destroys every actor (actor::destroy_all()) after the game scripts end and before the game's entities are unloaded.

For later steps:

  • Step 3: the engine's part classes (MeshPart, the lights, CameraPart) and their components (done: section 19).
  • Step 4: the markers (PRIMAL_ACTOR(), PRIMAL_BEHAVIOR(), PRIMAL_PART()), ActorRef/PartRef as reflected field types, names for log helpers on actors and behaviors.
  • Step 6: before the editor unloads game code, it destroys (or saves and rebuilds) the actors and behaviors whose classes are in it: their code goes with the DLL.
  • #58 steps 1-2 (children built in code, names to find them) are add_part() and part<T>("Name").

19. Step 3 done: the engine's parts and the scene sync (2026-11-20)

Decided (user, 2026-11-20): the adapter of decision 10 runs at render time (it reads the components and makes the renderer's objects; parts never call the renderer, and #3 removes only the adapter), and the renderer test's scene is made of actors, so the adapter gets a visual check on both backends.

Where:

  • Engine/EngineAPI/RenderComponents.h (game API, namespace render): MeshRenderer (geometry content id, up to max_mesh_materials = 16 materials, visible), DirectionalLight, PointLight, SpotLight, AmbientLight (color, intensity, light_set, enabled, and each type's own values), Camera (Projection, up, field of view and aspect ratio or view size, near and far). Plain data; the entity's transform places them.
  • Engine/EngineAPI/RenderParts.h (game API, namespace actor): MeshPart, DirectionalLightPart, PointLightPart, SpotLightPart, AmbientLightPart, CameraPart. Each adds its component in its constructor (values as constructor arguments: add_part<PointLightPart>("Lamp", parent, local, render::PointLight{...})) and writes it through setters (set_mesh(), set_material(), set_visible(), set_color(), set_range(), set_light_set(), set_aspect_ratio(), ...). Header only: nothing to export, and games may derive from them.
  • Engine/Graphics/SceneSync.h/.cpp (internal, graphics::scene): sync(), clear(), render_items(), camera(entity), frame_info(camera entity), stats().
  • The ECS got two small things for it: World::structure_version() (changes with every structural change) and a since version for each_chunk() (so ChunkView::changed<T>() works outside systems).
  • Tests: UnitTests/RenderPartTests.cpp (5 cases + a skipped benchmark), two ECS cases, and the graphics test "actors are drawn through the scene sync and follow their changes" (meshes, every light kind in two light sets, two cameras; hiding, material and geometry changes, moving a light to another set, cone angles, camera projection and aspect, removing parts and actors, spawning new ones; validation and sync validation clean).

How the sync works: one renderer object per entity and component kind, with the component's value it was made from. When no entity was created or destroyed and no component added or removed since the last sync (the structure version), only chunks whose component was written since then are compared (byte for byte) and the changes applied with the renderer's setters (a light moved to another light set, an ambient light with other textures, a mesh with other geometry or materials, a camera with another projection are made again). Otherwise every entity with the component is looked at and the objects of those that lost it are removed (before new ones are made: a light set has one ambient light). Light sets are created when a light first names them and stay until clear(), which graphics::shutdown() calls. Cost: 1 µs per frame in Release with the renderer test's 16,000 lights when nothing changes structurally (8 µs in Debug); a full pass is about one hash lookup per entity with a render component (the first one, with 16,000 lights, about 27 ms in Debug). Frame times of the renderer test were unchanged (Linux Release, vsync off: 1.73 ms against 1.74-1.80 ms before).

Rules for users of the sync: call sync() once a frame in the render function before the surfaces render, and once more after destroying actors and before destroying the content they used (geometry, materials, textures): until then the renderer still holds their render items. Code that makes its own lights with graphics::create_light_set() must not use the same light set keys as light components.

Found and fixed on the way (step 1-2 code):

  • actor::destroy() of an empty ActorRef asserted in id::index() (it now does nothing, as documented); found because MSVC's Debug assert dialog blocked the renderer test's shutdown in the VM.
  • destroy_all() was quadratic (each destroy searched the spawn order from the front): 694 ms for 16,000 actors in Linux Debug, now 17 ms.
  • The Linux Release builds failed at the step 2 commit: clang 23 -Wunused-but-set-global on the assert-only flag in Entity.cpp, and GCC 16 -Walloc-size-larger-than on resize(size() - 1) there (now erase() of the last script).

Not done here (later steps): the components aren't reflected yet (step 4: a game API header with markers needs its generated header on game projects' include path), so the editor doesn't show them; plain entities with geometry components still go through the old path (geometry::create() makes render items directly), which the editor and game.bin use until steps 5-6.

20. Step 4 done: reflection (2026-11-20)

Markers: PRIMAL_ACTOR(), PRIMAL_PART(), PRIMAL_BEHAVIOR() (options: .name = "..."), with PRIMAL_GENERATED_BODY() first in the class and the generated header as the file's last include, like scripts. The generator (ReflectionTool/) now reads a class's base clause (template arguments and all) and keeps its first base: the generated body writes the class's is_a() (this class, then that base's) and class_name() (the registered name), public, and ends with private: (Unreal's GENERATED_BODY() does the same). Only PRIMAL_PROPERTY() members are fields, as for scripts. PRIMAL_ACTOR_CLASS(Self, Base) stays for classes the generator doesn't see (templates, classes inside functions; EngineTest's SinglePartActor<T>): it writes is_a() and class_name() but registers nothing. PRIMAL_SCRIPT() stays until step 7 turns scripts into behaviors.

Registry (EngineAPI/Reflection.h): TypeKind::actor, part, behavior; a TypeInfo has spawn_actor, add_part or add_behavior (nullptr for a class whose constructor needs more than its init struct) and the class's class_identity. Registration is actor::detail::register_class<Self, kind>() in Actor.h (the generated code calls it), so Reflection.h needs only forward declarations of the actor types. The engine registers actor::Actor and actor::Part itself, and its six part classes (RenderParts.h) and six render components (RenderComponents.h, with render::Projection as a PRIMAL_ENUM) through markers. A loaded game library's classes are copied like its scripts, and release_library_types() clears their creators.

Making classes by name (for prefabs and the editor): actor::spawn_by_type(type, info), actor::spawn_by_name("Turret", info), Actor::add_part_by_type(type, name, parent, local), Actor::add_behavior_by_type(type). A wrong kind or a class that can't be made by name is refused and logged. (Not overloads of spawn()/add_part(): spawn({.name = ...}) would also match a TypeInfo, which has a name.)

Field types: FieldType::actor_ref (ActorRef<T>) and part_ref (PartRef<T>), as single values, in std::arrays and in lists, in components too (they are plain data). FieldInfo::class_identity is the class referred to. In text and files both are an entity, like game_entity::Entity fields: an actor as its root part's entity, a part as its own; reading one from an entity of another class (or a plain entity) is refused (text) or reads as none (files), and a reference to an actor that is gone writes as none. So game.bin and prefab files (step 5) map them with the entity map they already have, and the editor's picker can work with entities. The reflection layer stays below the actors: the actor runtime gives it two functions at startup (reflect::set_reference_hooks()).

Names for log helpers: log_debug() ... log_error() on actors ("Turret: text") and behaviors ("Turret.Blink: text"), category script, like scripts'. class_name() gives every object its registered class name.

The render components are reflected under render:: names. (light_set was a u32 for a moment, for want of a 64-bit field type; FieldType::s64 and u64 were added the same day, user's decision, and it is a u64 again like the renderer's key. Their FieldMeta limits are approximate, being f32; text keeps every digit, so the editor must never parse them as a double.) The editor's "Add component" list leaves out render:: components until the editor draws actors (step 6); its type list now names the new kinds and field types (it shows them as text until then).

Tests: UnitTests/ActorReflectionTests.cpp (5 cases: registration and fields, making classes by name and their names, references in text, lists and binary, part and behavior fields, log names), a generator case (ReflectionToolTests.cpp: base clauses, generated code, the error without a base), and the game library test (a marked actor class in a dlopened library, spawned by name from the program, unusable after unload while the engine's part classes stay).

clang-tidy findings fixed with it (some from step 3: its tidy run was misread as clean, the exit code checked was the shell's): each_chunk() hands its function a const ChunkView & (every ChunkView member is const; each() and the sync were the only non-const users); the sync's byte comparison keeps a NOLINT with the reason; the type aliases are lower case (mirror_map, EngineTest's mesh_actor ...); the log helpers' CRTP base has a private constructor; a part whose component game code removed no longer dereferences null in Release: its setters log an error and write to a scratch value (an assert in Debug).

21. Step 5 done: prefabs and game.bin v3 (2026-11-20)

First, FieldType::s64/u64 (user, the same day; section 20) and prefab_ref.

The actor record (Engine/Actors/Prefab.h, actor::prefab::ActorRecord): the class (name hash), the actor's fields, the parts (name, class, parent by index, local transform, default or not, fields, the entity's saved components except the transform's, which local holds), the behaviors (class, fields). Parts are kept root first, each after the one it is attached to. capture(actor) makes one, write()/read() are its bytes, and field values use the field lists that moved from game.bin into the reflection runtime (reflect::write_fields()/read_fields()). Entity references inside a record go through an EntityIndex: a prefab's own parts (references to anything outside the actor are dropped), or game.bin's table of every entity in the file.

Building (spawn(record, info); actor::spawn_prefab(PrefabRef, info) in the game API): the class's constructor runs (its default parts), then build_structure() matches the record's parts to default parts by name and makes the others (by type, attached by index), adds the behaviors, and apply_values() sets the actor's, parts' (with their transforms and components) and behaviors' values. Warnings, no failure, for: a default part the class no longer makes (made as a part of its saved class), a part class the game doesn't have (a plain Part, so its children still attach), a behavior class it doesn't have (left out), an actor class it doesn't have (a plain Actor). Spawning waits for the sync point inside a frame like spawn(): a new after_build step of detail::spawn() runs once the actor is in its slot (so references to it resolve) and before the plain root is added. Actor::prefab() remembers the prefab.

Prefabs are loaded by name (prefab::add(), find(), all()); a prefab asset is magic PPFB, version 1, the name and the record (save_asset()/load_asset(), for the editor's content files in step 6). PrefabRef is a reflected field: the prefab's name in text (#<hash> when it isn't loaded), its name hash in files.

Instances (decision 6, first version): capture_overrides() keeps the actor's and its behaviors' fields that differ from the prefab, and every reference field (its meaning depends on the file). An actor whose structure or part values no longer match its prefab is saved whole instead, so nothing is lost.

game.bin v3 (Engine/Content/ContentLoader.cpp): the plain entities as in v2, then the prefabs the actors use, then the actors (name, root transform in world space, and either a record or a prefab index plus overrides). Entity indices: the plain entities, then each actor's parts in record order. Loading creates the plain entities, loads the prefabs into the registry (a built game can spawn them), builds every actor's structure, then reads the plain entities' components and scripts and the actors' values, so references may point anywhere. unload_game() destroys the loaded actors. Version 2 files are refused (rebuild the game). The editor still writes only plain entities (SaveGame), now as v3. Not yet: an actor attached to another actor's part or to a plain entity, and a plain entity attached to an actor (saved as a root, with a warning); nested prefabs and per-part overrides (decisions 6 and 7). (Since step 6 slice 4, game.bin is version 4: an actor attached to another actor's part is saved; see section 22.)

Tests: UnitTests/PrefabTests.cpp (6 cases: a record round trip with references inside, default-part matching and the warnings, spawning by name and assets, spawning inside a frame, overrides, actors in game.bin with references between an instance and a one-off actor). Layers: Actors may use the ECS (a part's components by name), Content the Actors (game.bin).

Found on the way: game.bin's append() passed a null pointer to memcpy for an empty block (UBSan); fixed.

22. Step 6: the editor (in progress, Windows desktop, 2026-11-20)

Decided (user, 2026-11-20, every recommendation):

  1. Editor scenes are actors only. Add Actor replaces "Empty Game Entity", Cube and the light/camera items; old scenes' plain entities are converted in step 7 with the game projects. Plain entities stay a code feature.
  2. The C# model holds every value as text (as script fields do since #52 step 5); the engine mirrors it, undo/redo stays on the C# side.
  3. Saving a prefab rebuilds its open instances at once (they store only overrides), not only on the next open.
  4. The new-script template is cleaned up now (f32, the copyright header, no trailing namespace comment, no empty private:); the New Behavior / New Actor class dialog is step 7.

Slices, in order: (1) EngineDLL exports for actors; (2) the editor viewport renders parts (scene sync in RenderFrame); (3) outliner, details, Add Actor, undo/redo, .primal saving; (4) SaveGame writes the actors; (5) prefabs: save as prefab, content browser, drag into the scene, instances with overrides, Edit Prefab.

Progress (end of 2026-11-20, uncommitted, desktop):

  • Slice 1 done: EngineDLL exports for actors (EngineDLL/EditorSupport.h "Actors", C exports at the end of EntityAPI.cpp): SpawnActor (with an optional root part class for an actor whose constructor adds none), DestroyActor, GetActors, GetActor (JSON), RenameActor, AttachActor, AddPart, RemovePart, RenamePart, AttachPart, AddBehavior, RemoveBehavior, GetActorField/SetActorField. Engine side: actor::system::rename() (Actors/ActorSystem.h). Test: "the editor builds and edits actors by name" (UnitTests/ActorReflectionTests.cpp); UnitTests 252/252 Debug.
  • Slice 2 done (not yet seen on screen): RenderFrame runs graphics::scene::sync() and draws the parts' render items with the editor's; CreateLightSet uses reflect::name_hash() and scene::add_light_set(); RemoveLightSet is a no-op (sets live until scene::clear()).
  • Slice 3 written, being driven: C# Components/Actor.cs (Actor, ActorPart : GameEntity, PartFields, ActorObjectFields), Scene actors (build, attach, add/remove with undo, ApplyAllFields()), ActorView (details: name, class, fields, part tree with drag-to-attach, behaviors), the outliner's actor list and Add Actor menu, game code reload destroys and rebuilds actors (Project.cs). The engine's part classes now register from the engine library (Actors/Actor.cpp includes RenderParts.h; before, only binaries that included the header had them).
  • Driven so far (automation): Add Actor > Mesh works (part "Mesh (MeshPart)", the gpass pipeline is created). Add > Point Light crashes (Debug assert D3D12Light.cpp:1023, !light_sets.count(key)): InitializeEngine (EngineAPI.cpp:223) creates light set 0 itself, and scene::sync() creates set 0 again for the new light (whose light_set is 0 until the editor sets the scene's key). Fixed (2026-11-20, later): InitializeEngine makes set 0 through scene::add_light_set(0), so the sync owns it; ShutdownEngine no longer removes it (graphics::shutdown() runs scene::clear()).
  • Slice 3 driven and passing (2026-11-20, later; user + automation, DebugEditor, D3D12): Add > Point Light, Add Part (one part per pick), part drag-attach (nests, the light keeps rendering), remove part with its children, undo/redo of add/remove, attaching actors in the outliner, save + reopen (same actors and parts), clean exit (code 0, no live D3D12 objects but the device). Not checked: Run (Ctrl+F5) with actors, which needs slice 4.
  • Slice 4 done (2026-11-20, later): save_game() already wrote the engine's actors; added: game.bin version 4, each actor's attached_to (the file entity index of the other actor's part its root is attached to); loading attaches last, keeping the world transform (roots are saved in world space). save_game(path, leave_out) skips the editor's own entities and their children: before, every game.bin from the editor held the 4 viewport cameras as plain entities (since game.bin v2). load_game() logs what it read (game.bin: N entities, P prefabs, A actors (X parts)). The editor's pre-Run warning covers mesh parts (a built game still shows no meshes, #33, and has no graphics surface yet). Tests: "actors attached to other actors' parts stay attached through game.bin" (a chain, read out of order) and "entities left out of save_game() aren't written" (UnitTests 254/254 Debug). Run driven by the user: 2 actors loaded, no warnings but the meshes one.
  • Slice 5 decided (user, 2026-11-21, every recommendation): a prefab is an .asset of a new AssetType.Prefab; Edit Prefab opens a temporary scene in the world editor; an instance changes only what decision 6 allows (name, root transform, the actor's and behaviors' fields), its parts are read-only.
  • Slice 5 done (2026-11-21, desktop, uncommitted):
    • Engine: editor::capture_prefab(), load_prefab(), remove_prefab(), spawn_prefab() (EditorSupport.h "Prefabs") and the exports CapturePrefab, LoadPrefab, RemovePrefab, SpawnPrefab (EntityAPI.cpp). Test: "the editor captures prefabs and spawns instances from them" (UnitTests 255/255 Debug).
    • The asset (PrimalEditor/Content/Prefab.cs): the usual header, the prefab's name, the engine's prefab bytes (PPFB), and the mesh parts' geometry and applied materials (the engine's record holds only content ids, which mean nothing in the next session). PrefabLibrary loads every prefab asset into the engine's registry when the project opens, so game.bin saves instances as prefab + overrides.
    • Instances (Actor.PrefabGuid): Build() spawns them from the prefab (SpawnPrefab), matches the editor's parts by name and class (so attachments and references to them stay), takes the prefab's parts, components, meshes and behaviors, then applies the instance's own values: the root transform and the fields set on it (the fields the user set are exactly the C# Fields entries). Structural edits on an instance are refused; the details panel shows the root transform, Edit Prefab and Revert (forgets the set fields), and the parts read-only.
    • Save as Prefab (details panel, one-off actors): writes the asset, loads it, and makes the actor an instance.
    • Content browser: double-click a prefab opens it (Edit Prefab); dragging prefab assets onto the outliner places instances at the origin.
    • Edit Prefab (Project.EditPrefab()): the scene is put aside (its undo history too, UndoRedo.Stash()), a temporary scene holds the prefab's actor as a one-off (its prefab values pinned as its own, DetachFromPrefab()), a bar above the outliner has Save Prefab and Close. Closing asks to save changes, then activates the scene again, which builds its instances from the prefab as it is now (decision 3). While a prefab is open: no Add Actor, no project save, no Run.
    • Driven (automation, DebugEditor, D3D12, test project with a mesh actor and a point light actor): Save as Prefab (the actor becomes an instance), drag from the content browser (a second instance), Edit Prefab + Add Part (PointLightPart) + Save Prefab + Close (both instances get the part), a root transform override on one instance, project save, Run (game.bin: 3 actors, 6 parts), clean exit (code 0, only the device alive), reopen (both instances with the new part, the override kept). The picture checked by the user the same day (two cubes with their point lights, one moved). Then with a test behavior (Spinner, field speed) in the prefab (user + automation, the same day): the prefab's value reaches both instances, an instance's own value survives Save Prefab + Close while the other instance takes the new prefab value, Revert goes back to the prefab's value, the saved scene keeps no instance fields after Revert, and game.bin has both behaviors with the prefab's value.
    • Found then: closing the editor asserted in DescriptorHeap::release() (!_size, one live texture). An AppliedMaterialInput uploaded its texture when it was constructed, so a material that was only read (from the scene file or a prefab's mesh data) and never uploaded kept a texture to the end: an instance's mesh part read from the scene gets its prefab's geometry instead, so the one from the file never loads. Fixed in PrimalEditor/Content/Material.cs: an input loads only when its material is uploaded (UploadToEngine() already loaded the inputs); changing an input reloads it only if it was loaded. Every never-loaded geometry had the leak before (for example one in an inactive scene). Also, a prefab keeps its mesh section as bytes and makes the copy for the part being built only (Prefab.MeshFor()). Clean exit afterwards (code 0, only the device alive).
    • A hang seen once while the editor ran under Tools/DebugOutput/Capture-DebugOutput.ps1 was most likely the capture script stopping (a Claude Code session ended): a debuggee blocks on OutputDebugString until its debugger answers. Not seen again with the same steps under Rider's debugger.
    • Mesh display in the editor's viewport (the user: not right even before this work) and texture inputs, which load later now: issue #63.
    • Found while driving: the editor asserted (FreeList.h contains(id)) when the first instance was built. The prefab record held the mesh part's geometry content id, the instance's mesh part got it, and the old geometry was unloaded before the new one loaded, so the scene sync handed the renderer a destroyed id. Fixed three ways: editor::capture_prefab() writes mesh parts without geometry and materials (the editor keeps the mesh assets, and content ids mean nothing in the next session), an instance's old components are unloaded only after the new ones are loaded, and DestroyResource runs scene::sync() (under the EngineDLL lock) before destroying a resource.
    • Known limits: Save as Prefab and Revert clear the undo history (their entries knew the actor as it was); a game.bin instance still compares mesh content ids with the prefab's, so an instance with a mesh is saved whole (no loss; meshes in game.bin are #33); dropping on the viewport isn't supported (outliner only); no nested prefabs (decision 7).
  • No ambient light actor yet (needs IBL textures).
  • C# rules set after the code was written (Docs/Preferences.md "C# (the editor)"): nullable is on for the whole editor project since 2026-11-20 (544 warnings in 70 files at that point, none fixed yet); the new files (Components/Actor.cs 21, Editors/WorldEditor/ActorView.xaml.cs 9) still need theirs fixed (no !).

23. Step 7: conversion (done 2026-11-21)

Decided (user, 2026-11-21):

  1. Entity scripts are removed now (script::EntityScript, PRIMAL_SCRIPT(), script components on entities and their EngineDLL exports, scripts in game.bin): behaviors are the only per-object logic. GameScript (PRIMAL_GAME_SCRIPT()) stays for game-level logic. Plain entities stay public for mass gameplay (decision 12), with ECS systems as their logic. (The recommendation was to keep entity scripts as a code-only feature.)
  2. Old scenes' plain entities are dropped on load, with a warning that names them; such scenes are rebuilt by hand. The editor's plain-entity UI goes away. (The recommendation was a conversion to one-off actors.)
  3. One "New Class" dialog with a kind (Behavior, Actor, Part, Game Script) replaces the new-script dialog; each kind writes its own header and .cpp and adds them to the game's .vcxproj.

Done (2026-11-21, desktop, uncommitted):

  • Engine: script::EntityScript, PRIMAL_SCRIPT(), EngineAPI/ScriptComponent.h, entity script storage, the entity's script()/scripts()/script<T>(), add_script()/queue_add_script() and their removal, and ComponentType::script are gone; Components/Script.* keeps the game scripts and ScriptBase. The reflection registry has no TypeKind::entity_script or create_script; the generator reports PRIMAL_SCRIPT() as an error that says to make the class a behavior. game_entity::Entity::set_position() etc. (and the local_* ones) write a plain entity's transform: what EntityScript had. game.bin is version 5: plain entities without scripts.
  • EngineDLL: the script exports (AddScript, RemoveScript, Get/SetScriptField, GetEntityScriptNames, GetScriptCreator, GetScriptNames) and the per-light exports of the old light entities (CreateLight, ..., SetLightAttenuation) are gone; the entity descriptor has no script.
  • Tests: every test of entity scripts was either converted (to behaviors: frame phases, a behavior destroying its actor, a behavior creating an entity, the benchmark; to game scripts: reflection of class fields, the log helpers) or dropped where ActorTests covers the same for behaviors. ScriptRegistryTests is TypeRegistryTests (behaviors), ScriptComponentTests is GameSystemTests, ContentLoaderTests marks its entities with a component. New: a test of the entity's transform setters and of the generator's PRIMAL_SCRIPT() message. UnitTests 238/238 (255 before, the difference being entity-script cases). EngineTest's four scripts are behaviors; GraphicsTests turns its entities between frames (not compiled on Windows).
  • Editor: scripts, the plain-entity list and the old light entities (with their views) are gone; GameEntity is the abstract base of ActorPart. Opening a project whose scene has plain entities logs which ones aren't loaded (Project.WarnAboutPlainEntities(); the serializer skips the old list); saving drops them for good. Dropping a mesh asset on the outliner makes a mesh actor. New Class (GameDev/NewClassDialog, was NewScriptDialog): Behavior, Actor, Part or Game Script, from templates that follow the step 6 decision 4 cleanup (f32, no trailing namespace comment, no empty private:). The game project upgrade warns about entity scripts and says what to do.
  • Driven (automation, DebugEditor, D3D12): the test project with one old plain entity opens with the warning, New Class writes a behavior and adds it to the .vcxproj, the game code builds with it, Run loads game.bin v5 (0 plain entities, 3 actors), clean exit (code 0, only the device alive). The test project's two entity scripts were converted to behaviors by hand.
  • Lost for now: ambient lights in editor scenes (only the old light entities had an editor for the IBL textures): issue #64. The viewports' list of plain-entity geometry is no longer filled (actors render through the scene sync).
  • Linux checks done (2026-11-21): all green after formatting, one tidy fix and the test game's game.bin version (plan doc Open items C).
  • The VM's ScriptTest (2026-11-21): PlayerScript and EnemyScript are behaviors now (same class names; the originals are next to them as *.before-behaviors); PlayerScript reads Armor, the attachment and the part count through owner().root(). The game code builds with 0 warnings (DebugEditor) and the editor (DebugEditor, D3D12 on WARP) loads it; the scene's three old plain entities (Player, Weapon, Enemy) are named in the warning. The project wasn't saved, so they're still in its file. CLAUDE.md's history keeps its dated mentions of scripts on purpose.

Pages 19

View all

Clone this repository