10. Hoverboard in C++#

For: C++ programmers (advanced). Needs: Tutorials 6, 8 and 9. You will: read how a scenario gets a running world, how a latent (multi-frame) protocol driver counts ticks of the test world, how snapshots turn physics into assertions, and how a word like forward becomes a float.

This page describes the design; the source ships in the installed plugin under Source/ZagalaSpecExamples/Public/Hoverboard/, Source/ZagalaSpecToolkit/Public/ and the matching Private/ folders.

Class map#

        flowchart LR
    subgraph Shared context extensions
        T["UZagalaSpecCESetTickLimit"]
        W["UZagalaSpecCEEnsureTestWorld"]
        SP["UZagalaSpecCESpawnHoverboard"]
    end
    SP --> DSP["UZagalaSpecDSLSpawnHoverboard<br/>(chainer)"] --> P1["UZagalaSpecPDSpawnHoverboard"] --> P2["UZagalaSpecPDQueryHoverboardState"]
    subgraph Expectations
        WH["UZagalaSpecStepWaitForHover"] --> DW["UZagalaSpecDSLWaitForTicks"] --> PW["UZagalaSpecPDWaitForTicks"]
        AT["UZagalaSpecStepApplyThrottle<br/>UZagalaSpecStepApplySteering"] --> DA["UZagalaSpecDSLApplyInputsToSut"] --> PA["UZagalaSpecPDApplyInputs"]
        AD["UZagalaSpecStepAssertDisplacement"] --> DD["UZagalaSpecDSLCheckDisplacement"] --> PD["UZagalaSpecPDCheckDisplacement<br/>: UZagalaSpecPDWaitForTicks"]
    end
    P1 --> SUT["AZagalaSpecExamplesHoverboardActor"]
    PA --> SUT
    PD --> SUT
    

Sentence

Pattern

Step

Given the tick limit is set to 500 ticks

^(?:Given |And )?the tick limit is set to (\d+) ticks$

UZagalaSpecCESetTickLimit

And a test world is ready

^(?:Given |And )?a (test world) is ready$

UZagalaSpecCEEnsureTestWorld

And the hoverboard is spawned at the origin

^(?:Given |And )?the hoverboard is spawned at the origin$

UZagalaSpecCESpawnHoverboard

When I wait 60 ticks for it to hover

^(?:When |And )I wait (\d+) ticks for it to hover$

UZagalaSpecStepWaitForHover

And I apply forward throttle

^(?:When |And )I apply (forward|backward) throttle$

UZagalaSpecStepApplyThrottle

And I steer left

^(?:When |And )I steer (left|right)$

UZagalaSpecStepApplySteering

Then the hoverboard has moved forward by more than 100 units

^(?:Then |And )the hoverboard has moved (forward|backward) by more than ([0-9.]+) units$

UZagalaSpecStepAssertDisplacement

Then the hoverboard has rotated to the left by more than 15 degrees

^(?:Then |And )the hoverboard has rotated to the (left|right) by more than ([0-9.]+) degrees$

UZagalaSpecStepAssertHeading

Then the hoverboard hovers between 140 and 160 units above the ground

^(?:Then |And )the hoverboard hovers between ([0-9.]+) and ([0-9.]+) units above the ground$

UZagalaSpecStepAssertHoverHeight

The system under test#

AZagalaSpecExamplesHoverboardActor is a physics-simulating AActor with a UBoxComponent root. Each tick it traces down, applies a hover-correction force toward HoverHeight (150 cm by default), and applies throttle and steering forces scaled by the current inputs. Its public surface is what the drivers use: SetThrottle(float), SetSteering(float) (both clamped to −1..1), GetHeightAboveGround(), GetYawDegrees(). Nothing about ZagalaSpec appears in it.

Getting a world: UZagalaSpecCEEnsureTestWorld#

This is the one step every world-based feature needs. It is latent, always gives the scenario a fresh world and has a timeout.

UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "TestWorld")
TObjectPtr<UZagalaSpecPlaySessionSettings> SettingsAsset;

virtual void InternalExecute_Implementation(const TScriptInterface<IZagalaSpecTaggedDataCacher>& AssignedCacher) override;
virtual void InternalTeardown_Implementation() override;

What InternalExecute does, in order:

  1. Remembers the cacher’s owner (the context) and resets its elapsed-time counter.

  2. Calls AddLocalSetupDataToCache, which turns the (test world) capture group into a UZagalaSpecDataPlaySessionSettings, then loads the UZagalaSpecPlaySessionSettings asset it references. A missing asset is a failure.

  3. Editor builds: starts an FTSTicker timeout. If GEditor->PlayWorld already exists (typically the previous scenario’s session, still ending), it calls GEditor->RequestEndPlayMap() unless an end is already queued, and waits on that ticker until PlayWorld is gone; a running session is never reused. It then subscribes to FEditorDelegates::PostPIEStarted, fills an FRequestPlaySessionParams from the settings asset (map override; a ULevelEditorPlaySettings with fixed FPS when bUseFixedTimeStep and with net mode, player count and single-process play when bListenServer) and calls GEditor->RequestPlaySession.

  4. Packaged builds: subscribes to FCoreUObjectDelegates::PostLoadMapWithWorld, starts the same timeout and calls UGameplayStatics::OpenLevel with the configured map; with no map and an active game world it reuses that world.

Points to copy:

  • The world comes from a capture group. a (test world) is ready captures the words test world; the capture group’s Group Value Class is a Blueprint subclass of UZagalaSpecDataPlaySessionSettings (BP_Hoverboard_Data_PlaySettings) whose default points at a UZagalaSpecPlaySessionSettings asset (DA_Hoverboard_PlaySettings: map, timeouts, fixed time step). The step itself has no hard-coded map.

  • Latent steps do not return a result. InternalExecute returns after requesting play. The PIE-started handler writes UZagalaSpecDataPlaySessionWorld to the cache (the listen server world when the session is networked) and calls BroadcastSuccess(); the timeout tick accumulates DeltaTime and calls BroadcastFailure() after StartupTimeoutSeconds, naming the phase that stalled (EnsureTestWorld: the previous PIE session did not end within %.1f seconds. or EnsureTestWorld: PIE did not start within %.1f seconds.). Whichever fires first removes the other’s handle so the link broadcasts exactly once.

  • Teardown ends what it started. InternalTeardown_Implementation calls GEditor->RequestEndPlayMap() and removes both handles. Because the feature puts this step in Shared Context Extensions, every scenario gets a fresh PIE session.

  • Fixed time step is what makes 60 ticks deterministic across machines and in -nullrhi runs. In the editor it is applied through ClientFixedFPS, which PIE reads for every non-dedicated instance; ServerFixedFPS only affects dedicated servers.

  • The timeout uses FTSTicker because no play world exists while PIE or the map is starting. Everything that runs inside the world counts world ticks instead (see below).

UZagalaSpecCESetTickLimit is the trivial companion: AddLocalSetupDataToCache (the (\d+) becomes UZagalaSpecDataTickLimit) then BroadcastSuccess().

Spawning and snapshotting#

UZagalaSpecCESpawnHoverboard hands off to UZagalaSpecDSLSpawnHoverboard, which builds a UZagalaSpecDefaultExecutionChainer with two links via AddLinkT<>(): UZagalaSpecPDSpawnHoverboard then UZagalaSpecPDQueryHoverboardState.

UZagalaSpecPDSpawnHoverboard gets the world through FZagalaSpecWorldHelper::GetWorldFromCache(Cacher) (which reads UZagalaSpecDataPlaySessionWorld), spawns the actor at the origin with AlwaysSpawn collision handling, and writes UZagalaSpecDataHoverboardRef. UZagalaSpecPDQueryHoverboardState then fills a UZagalaSpecDataHoverboardSnapshot from the actor: Location, Velocity, ForwardVector, RightVector, Height (from GetHeightAboveGround()) and YawDegrees.

The snapshot is the baseline every later assertion compares against. Taking it in the same chain as the spawn guarantees it exists before any expectation runs. UZagalaSpecDSLSnapshotSut reuses the query driver when a step wants a fresh baseline mid-scenario.

The latent driver pattern: UZagalaSpecPDWaitForTicks#

Every wait and every “until” assertion in the examples derives from this one class.

UENUM(BlueprintType)
enum class EZagalaSpecTickCheckResult : uint8 { Continue, Succeed, Fail };

class ZAGALASPECTOOLKIT_API UZagalaSpecPDWaitForTicks : public UZagalaSpecDefaultChainLink
{
protected:
    virtual void InternalExecute_Implementation(const TScriptInterface<IZagalaSpecTaggedDataCacher>& AssignedCacher) override;
    virtual void InternalTeardown_Implementation() override;

    /** Called each tick of the play session world; subclasses poll their condition here. Base returns Continue. */
    virtual EZagalaSpecTickCheckResult OnTickCheck(IZagalaSpecTaggedDataCacher* Cacher, int32 TicksSoFar, FString& OutFailureReason);
};

Cache contract: reads UZagalaSpecDataWaitTicks (how long to wait), UZagalaSpecDataTickLimit (deadline) and UZagalaSpecDataPlaySessionWorld (whose ticks are counted). Wait and limit both missing is a failure; a missing limit defaults to twice the wait so it never fires; a missing wait means “until the condition holds or the limit”. A missing world fails with ProtocolDriver_WaitForTicks: PlaySessionWorld not found in chain cache.

InternalExecute caches the values, resets the tick counter and subscribes to FWorldDelegates::OnWorldPostActorTick, ignoring every world except the cached one. A tick therefore means “the test world ran its actors and physics once”. The application-wide FTSTicker is not used because, in the editor, it keeps running while the PIE world is skipped (Slate throttling, pause) or ticked several times in one frame (fixed time step), so the count drifts and physics scenarios become intermittent. FTimerManager is not used either: it ticks at most once per engine frame. On every tick of the test world the driver:

  1. calls OnTickCheck; Fail broadcasts the returned reason, Succeed broadcasts success;

  2. otherwise, if the tick limit is reached, broadcasts WaitForTicks: tick limit %d exceeded without satisfying condition.;

  3. otherwise, if the wait count is reached, broadcasts success;

  4. otherwise keeps ticking.

Each terminal branch unsubscribes before broadcasting, so every outcome both broadcasts and stops, and a following wait started by a subscriber begins counting on the next world tick. If the test world is cleaned up mid-wait the driver fails with WaitForTicks: PlaySessionWorld was cleaned up after %d ticks. instead of hanging. InternalTeardown_Implementation unsubscribes if the chain is torn down mid-wait (for example because a sibling link failed). The plain wait (UZagalaSpecStepWaitForHover → UZagalaSpecDSLWaitForTicks) uses the base behaviour; conditional waits subclass and override OnTickCheck.

Assertions that wait: UZagalaSpecPDCheckDisplacement#

UZagalaSpecStepAssertDisplacement converts two capture groups (UZagalaSpecDataExpectedDirection, UZagalaSpecDataExpectedRelativeDisplacement) and runs UZagalaSpecDSLCheckDisplacement → UZagalaSpecPDCheckDisplacement, a UZagalaSpecPDWaitForTicks subclass that overrides both InternalExecute_Implementation and OnTickCheck.

  • In InternalExecute it calls Super (which starts listening for world ticks) and returns if Super already failed (IsWaitingForTicks() is false), then reads and validates everything it will need: the tick limit, the hoverboard ref, the baseline snapshot, the expected direction and the expected distance. Each missing input is its own failure string (HoverboardSnapshot missing in chain cache. and so on), reported through FinishWithFailure so the tick subscription is removed too. It copies the snapshot’s location and forward vector into members so the tick check never touches the cache again.

  • In OnTickCheck it computes the displacement vector from the baseline, projects it onto the baseline forward vector to decide whether the board is moving forward or backward, and compares the distance against the expected minimum. Both conditions true → Succeed. At the tick limit it returns Fail with a composed reason that names which part failed: wrong direction (listing the allowed words) and/or Displacement %f is not > %f. Otherwise it defers to Super::OnTickCheck.

UZagalaSpecPDCheckHeading and UZagalaSpecPDCheckHoverHeightRange follow the same shape with yaw and height.

Words as values: UZagalaSpecDataThrottleInput#

UZagalaSpecDataThrottleInput extends UZagalaSpecDataString and adds a float Throttle. Its StoreValue_Implementation keeps the raw text and maps it: forward → +1, backward → -1, anything else → 0, comparing case-insensitively against UZagalaSpecDataExpectedDirection::DirectionForward() and DirectionBackward(). UZagalaSpecDataSteeringInput does the same for left/right.

Because the word is parsed at conversion time, UZagalaSpecPDApplyInputs just reads both inputs from the cache (either may be absent and defaults to 0) and calls SetThrottle and SetSteering on the actor. The vocabulary lives in one place, so the regex alternatives, the parser and the assertion agree.

What to copy#

  • UZagalaSpecCEEnsureTestWorld + a play-settings asset as the first shared extension of any world feature; start from a fresh session and give it a timeout.

  • UZagalaSpecPDWaitForTicks as the base for anything that spans frames; override OnTickCheck, never block.

  • Spawn-then-snapshot in one chainer so assertions always have a baseline.

  • Parse words into numbers in StoreValue_Implementation, not in drivers.

Next: 11. Checkpoint in C++ adds a second actor, tuned Blueprint data classes and repeatable activations.