Learn / Architecture case study
Nebula Lance: Real-Time Project Anatomy
A blocked graphical build with instructive state and collision structure
What you will learn
- Named value records and grouped stateLearn conceptRecords, enumerations, and classes
- Finite iteration domains and termination conditionsDecisions and repetitionProgram-local teaching concept
- Aliases for mutable or read-only existing objectsLearn conceptPointers and references
- Sorting, predicates and library algorithmsTemplates, lambdas, and library awarenessProgram-local teaching concept
- Persistent values and explicit state transitionsState, edges, and debouncingProgram-local teaching concept
- Dynamic collections with size, capacity and ownershipTemplates, lambdas, and library awarenessProgram-local teaching concept
- Container element lifetime and invalidationLearn conceptScope, lifetime, and storage
Source anatomy excerpt
nebula-anatomy.cpp.txt
Limited historical anatomy excerpt. This is not a complete or verified runnable game.
// HISTORICAL PROJECT ANATOMY EXCERPT; NOT A CANONICAL RUNNABLE PROGRAM.
// Original lines 8-45: Object records and circle hit
struct Bullet {
Vector2 pos{};
float speed = 0.0f;
bool active = false;
bool fromPlayer = true;
float radius = 4.0f;
};
struct Enemy {
Vector2 pos{};
Vector2 vel{};
float radius = 18.0f;
int health = 1;
float shootTimer = 0.0f;
bool active = true;
bool zigzag = false;
float zigzagPhase = 0.0f;
};
struct Explosion {
Vector2 pos{};
float time = 0.0f;
float maxTime = 0.35f;
bool active = true;
};
static bool CircleHit(Vector2 a, float ar, Vector2 b, float br) {
const float dx = a.x - b.x;
const float dy = a.y - b.y;
const float rr = ar + br;
return dx * dx + dy * dy <= rr * rr;
}
static Rectangle MakePlayerRect(Vector2 pos, float w, float h) {
return Rectangle{pos.x - w * 0.5f, pos.y - h * 0.5f, w, h};
}
// Original lines 53-63: Audio creation and cleanup
// Tiny generated sound effects so the game has juice without external files.
Wave shootWave = GenWaveSquare(0.08f, 880.0f, 0.25f);
Wave boomWave = GenWaveNoise(0.18f, 0.22f);
Sound shootSound = LoadSoundFromWave(shootWave);
Sound boomSound = LoadSoundFromWave(boomWave);
UnloadWave(shootWave);
UnloadWave(boomWave);
SetSoundVolume(shootSound, 0.25f);
SetSoundVolume(boomSound, 0.45f);
// Original lines 210-225: Collision pass
for (auto& e : enemies) {
if (!e.active) continue;
for (auto& b : bullets) {
if (!b.active || !b.fromPlayer) continue;
if (CircleHit(e.pos, e.radius, b.pos, b.radius)) {
b.active = false;
e.health -= 1;
if (e.health <= 0) {
e.active = false;
game.score += 100;
spawnExplosion(e.pos);
}
}
}
}
// Original lines 262-264: Deferred erasure
bullets.erase(std::remove_if(bullets.begin(), bullets.end(), [](const Bullet& b) { return !b.active; }), bullets.end());
enemies.erase(std::remove_if(enemies.begin(), enemies.end(), [](const Enemy& e) { return !e.active; }), enemies.end());
explosions.erase(std::remove_if(explosions.begin(), explosions.end(), [](const Explosion& ex) { return !ex.active; }), explosions.end());
Source integrity
SHA-256 1b388500da99dc24775cc11c1d1df477747178ec5c7e0fb56a36381b53dfb1cc. Display, copy and approved download use the same source.
What the source is trying to do
The game owns player, wave, score, life and pause state, plus collections of bullets, enemies and explosions. Input changes player movement and shooting. Frame updates move entities, spawn enemies and enemy bullets, resolve overlaps, remove inactive objects, and render a new frame. This larger example makes C++ external libraries and stateful simulation visible after the smaller console programs. Its value comes from those mechanisms and the defects they expose, rather than from its size or graphics alone.
Raylib supplies window, drawing, keyboard, timing, random and audio operations. Standard C++ supplies structs, vectors, references, branching and algorithms. A declaration in a header permits compilation; an installed library provides definitions for linking; a display and device permit runtime observation. These are separate verification stages. The historical CMake file requests a discoverable Raylib installation. The project archive does not provide a portable installed dependency.
Confirmed build blocker
The fresh ordinary build cannot find raylib.h. A second check supplied the exact official Raylib 6.0 header for syntax checking only. That check rejects GenWaveSquare at original line 55 and GenWaveNoise at line 56: neither name is declared in the examined header. Its SHA-256 is recorded in the evidence. No replacement API was invented, no Raylib stub was used to claim a working game, and no installed library was linked. CMake is also unavailable in this environment.
The intended ownership sequence creates a temporary Wave, makes a Sound from it, and unloads the Wave; Sounds are later unloaded before the audio device closes. That sequence expresses useful staged resource ownership, but the missing generators prevent it from executing. A future repair can first remove generated audio and its dependent sound calls, establish a real pinned build, and then add supported audio assets or implement a generator with correct allocation and release semantics. Such a repair needs actual linked compilation and audio testing before publication as runnable code.
State and frame order
During running play, input and delta time influence movement, spawning and timers. A paused frame still draws the scene. Restart clears bullets, enemies and explosions and restores the game state. These are static observations, not observed interactions with a launched window. The supplied diagram is an architecture sketch of the frame phases and branches, not an assertion that the loop has been tested graphically.
Delta time helps make movement proportional to elapsed time, but it does not by itself guarantee stable collision detection. The collision function samples circular overlap at the current positions. A fast bullet can cross an enemy between samples. A long frame can amplify movement, timers and skipped overlap. Continuous or swept collision, or bounded fixed update steps, would be meaningful later improvements. Diagonal input also deserves a speed check because independently adding horizontal and vertical motion can produce a larger diagonal magnitude. These are limitations and review questions, not runtime measurements.
Confirmed repeated reward logic
Original lines 210–225 skip an inactive enemy before entering its bullet loop. A hit deactivates a bullet and decreases enemy health. If health reaches zero, the code deactivates the enemy, adds 100 points and spawns an explosion. The inner loop continues without breaking or checking the enemy's new inactive state. A second overlapping active player bullet can therefore reduce the dead enemy's health again and grant another reward.
The isolated C++ reconstruction fixes geometry to two overlapping bullets and one enemy with health 1. It runs the historical transition order and a version that stops after death. The actual output is 200 points for the historical loop and 100 for the corrected loop. data/nebula-collision-test.json binds that test to its own source hash. This is a controlled reconstruction of a logic defect, not gameplay observation or a full-game patch. It does not establish how often the condition occurs during ordinary play.
Enemy bullets and contact collisions can each subtract lives in a single frame; there is no demonstrated invulnerability window. Once a game-over flag is set, remaining same-frame work also deserves review. Whether one hit per frame or a grace period is intended requires a gameplay design decision and real interactive testing.
Vector references and deferred deletion
The source marks objects inactive and calls erase/remove_if after traversal. This avoids directly erasing the vector being traversed by its range-for loop. When an enemy fires, the code appends to the bullet vector while traversing the enemy vector. Explosion creation appends to another collection. Those operations do not inherently invalidate the enemy reference, because they modify different owning containers.
Calling reserve is a capacity optimization, not a guarantee of reference safety. Appending to the vector currently being traversed can invalidate references if allocation changes, and erase changes element positions and lifetimes. The useful teaching rule is to identify the owning container for every reference and the exact operations that mutate it. A future refactor should preserve the staged update/collision/deletion structure, and can introduce separate spawn queues when same-container append would otherwise occur.
Evidence and next gate
Source inspection, fresh dependency failure, exact-header syntax failure and isolated collision reproduction are complete. Linked CMake build, window launch, keyboard behavior, pause/resume, restart, difficulty progression, high-frame-time behavior and audio creation/playback/cleanup remain NOT_OBSERVED. They must be performed with an installed pinned library and a suitable graphical/audio environment before changing the classification.
The package intentionally provides limited source excerpts with original-to-excerpt line mapping, annotations, dependency findings and a repeatable diagnostic. It provides no complete replacement game. The case study connects to Functionator through shared state and update invariants, and to the vector autopsy through ownership and invalidation. No remembered role-selector program has been inferred from Nebula's presence.
Official dependency reference examined: https://raw.githubusercontent.com/raysan5/raylib/6.0/src/raylib.h. Raylib API overview: https://www.raylib.com/cheatsheet/cheatsheet.html.
Mechanism diagrams
- Read frame input→Game state
- Game staterunning→Move and spawn
- Game statepaused→Render
- Game stategame over→Restart pressed?
- Restart pressed?yes→Reset state and clear vectors
- Restart pressed?no→Render
- Reset state and clear vectors→Render
- Move and spawn→Collision passes
- Collision passes→Erase inactive objects
- Erase inactive objects→Render
- Render→Read frame input
Inspect the supplied Mermaid specification
flowchart TD
Input["Read frame input"] --> State{"Game state"}
State -->|running| Update["Move and spawn"]
State -->|paused| Render["Render"]
State -->|game over| Reset{"Restart pressed?"}
Reset -->|yes| Clear["Reset state and clear vectors"]
Reset -->|no| Render
Clear --> Render
Update --> Collision["Collision passes"]
Collision --> Prune["Erase inactive objects"]
Prune --> Render
Render --> InputSource-linked explanations
Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.
Object records and circle hit
nebula-anatomy.cpp.txt, lines 4–41 →Bullet, Enemy and Explosion records group transient simulation state.
- Technical explanation
- Bullet, Enemy and Explosion records group transient simulation state. Position and radius belong to a library type and collision model, while health and active flags belong to the game. CircleHit compares squared center distance with squared summed radii, avoiding a square root. This proves an overlap decision at the sampled instant, not continuous collision along a fast bullet trajectory.
- Syntax
- Bullet, Enemy and Explosion records group transient simulation state. Position and radius belong to a library type and collision model, while health and active flags belong to the game. CircleHit compares squared center distance with squared summed radii, avoiding a square root. This proves an overlap decision at the sampled instant, not continuous collision along a fast bullet trajectory.
- Effect on the program
- The original source remains unverified at linked build and graphical runtime. These excerpts explain source structure and detected blockers.
- Common mistake
- Do not infer full gameplay correctness from readable architecture, successful reservation, or a syntax-only test.
- Deeper connection
- Real-time update order and ownership determine both invalidation safety and whether state transitions happen once.
Audio creation and cleanup
nebula-anatomy.cpp.txt, lines 44–54 →GenWaveSquare and GenWaveNoise are not declared by the examined official raylib 6.0 header.
- Technical explanation
- GenWaveSquare and GenWaveNoise are not declared by the examined official raylib 6.0 header. Header-only compilation rejects these calls, even before linking or launch. LoadSoundFromWave and UnloadWave express a sensible staged ownership idea, but that idea does not supply the missing generators. Wave cleanup would release temporary sample data after Sound creation if initialization were made valid.
- Syntax
- GenWaveSquare and GenWaveNoise are not declared by the examined official raylib 6.0 header. Header-only compilation rejects these calls, even before linking or launch. LoadSoundFromWave and UnloadWave express a sensible staged ownership idea, but that idea does not supply the missing generators. Wave cleanup would release temporary sample data after Sound creation if initialization were made valid.
- Effect on the program
- The original source remains unverified at linked build and graphical runtime. These excerpts explain source structure and detected blockers.
- Common mistake
- Do not infer full gameplay correctness from readable architecture, successful reservation, or a syntax-only test.
- Deeper connection
- Real-time update order and ownership determine both invalidation safety and whether state transitions happen once.
Collision pass
nebula-anatomy.cpp.txt, lines 57–72 →The outer loop checks enemy.active before entering the bullet loop.
- Technical explanation
- The outer loop checks enemy.active before entering the bullet loop. After a bullet kills the enemy, active becomes false, but the inner loop continues and does not break or re-check enemy.active. Another overlapping active player bullet can reduce dead-enemy health again and award another 100 points. This is a static logic finding; a focused reconstruction of the same loop demonstrates two rewards for one enemy.
- Syntax
- The outer loop checks enemy.active before entering the bullet loop. After a bullet kills the enemy, active becomes false, but the inner loop continues and does not break or re-check enemy.active. Another overlapping active player bullet can reduce dead-enemy health again and award another 100 points. This is a static logic finding; a focused reconstruction of the same loop demonstrates two rewards for one enemy.
- Effect on the program
- The original source remains unverified at linked build and graphical runtime. These excerpts explain source structure and detected blockers.
- Common mistake
- Do not infer full gameplay correctness from readable architecture, successful reservation, or a syntax-only test.
- Deeper connection
- Real-time update order and ownership determine both invalidation safety and whether state transitions happen once.
Deferred erasure
nebula-anatomy.cpp.txt, lines 75–77 →erase-remove_if compacts inactive objects after iteration rather than erasing the iterated vector during its range-for.
- Technical explanation
- erase-remove_if compacts inactive objects after iteration rather than erasing the iterated vector during its range-for. Enemy firing appends to bullets while iterating enemies, not while iterating bullets; explosion creation likewise appends to a separate collection. reserve is a performance hint and is not the reason references are safe. If future code appends to the vector currently being traversed, reallocation can invalidate references.
- Syntax
- erase-remove_if compacts inactive objects after iteration rather than erasing the iterated vector during its range-for. Enemy firing appends to bullets while iterating enemies, not while iterating bullets; explosion creation likewise appends to a separate collection. reserve is a performance hint and is not the reason references are safe. If future code appends to the vector currently being traversed, reallocation can invalidate references.
- Effect on the program
- The original source remains unverified at linked build and graphical runtime. These excerpts explain source structure and detected blockers.
- Common mistake
- Do not infer full gameplay correctness from readable architecture, successful reservation, or a syntax-only test.
- Deeper connection
- Real-time update order and ownership determine both invalidation safety and whether state transitions happen once.
Verification and provenance
- Source inspected
- External dependency required
- Broken
- Graphical runtime unverified
No full-game compile, linked Raylib build, graphical gameplay, or audio verification is claimed. The isolated collision reproduction supports only the specific logic defect discussed above.
Source origin and publication treatment
User supplied graphical project
Authorship not independently proved; user supplied archive.
Limited anatomy excerpt only; original full project not republished
No new license is asserted by this publication.