Model development guide
This page explains the structure, lifecycle, and capabilities of a Model in the Sim Engine using the provided model2 sample as the reference. A Model is a logical unit that runs at a configured rate, may depend on other models, and contains state controllers that group related states (play/reset/pause).
Overview
Models encapsulate simulation behavior. Each model has a lifecycle and a collection of state controllers. Models can run in parallel with other models; dependencies between models should be expressed explicitly so the scheduler can respect ordering.
Primary responsibilities of a model:
- Register and initialize state controllers and resources
- React to engine lifecycle events (Reset, Init, Run, Stop, state changes)
- Execute time-critical logic inside
OnRun() - Trigger async actions and pass descriptors to background threads (lockless)
- Publish/subscribe to data streams and recorders
How to write a model
- Create it: APICCenter → Generate Code: model name, cores and priority (Execution Context & Threading), the capabilities you need
(LRU access, profiler reports, async operations), then Generate Source Code. It writes
Models/<name>.h/.cpp: a classC<name> : public CModelBasewith the lifecycle methods below. When you allow it to overwrite them, it also rewritesModels/ModelsProj.cpp(creates and registers every model) andModels/ModelHierarchyProj.cpp(the run order, from the models hierarchy JSON). - Build it: add
"Models/<name>.cpp"to the project'sCMakeLists.txt(the model files are listed there one by one). - Set the rate in
OnReset()(called first at start-up):SetMinorFrame(-1)= every minor frame,n= every n frames (Rates & Dependencies); reset counters and state. - Prepare in
OnInit()(called afterOnReset()): get your LRU / block pointers and driver pointers, register stream triggers and callbacks, add state controllers, allocate every buffer. Nothing inOnRun()should allocate or look anything up by name. See the order of the calls. - Work in
OnRun(): read inputs (Raw2Eng()of the LRU when raw data arrived), compute, write outputs (Eng2Raw()), run the state controllers. Keep it short and never block: the whole cycle of every model must fit in the minor frame. - Use the engine's globals when you need the frame number, the run time, the paths or the engine state: Global functions and properties.
// Models/MyModel.cpp (shape of a generated model)
CMyModel::CMyModel() : CModelBase("MyModel", "1.00", {}) // name, version, core affinity
{
}
void CMyModel::OnReset() // first at start-up, and on every Reset
{
SetMinorFrame(-1); // run every minor frame
}
void CMyModel::OnInit() // after OnReset at start-up, and on every Init
{
// pointers, triggers, callbacks, state controllers, buffers
}
void CMyModel::OnRun()
{
if (CCoreEngine::iMinorFrameCounter % 1000 == 0) // once a second at a 1 ms minor frame
CSimReports::ReportMsg(EReportType::eInfo, "MyModel alive");
// read inputs, compute, write outputs
}
Model Lifecycle Methods
The sample model defines standard overridable methods. Each is called by the engine at specific moments:
CoreEngine.cpp, Scheduler.cpp; at each step the engine calls the drivers and streams first, then the models):
- Constructor: when the program loads (the model objects are created in
Models/ModelsProj.cpp). - Start-up:
OnReset()→OnStop()→OnInit().OnReset()comes FIRST. - Run / Step:
OnStateChanged(eRunoreStep), thenOnRun()every frame at the model's rate. - Commands (keyboard, network, DIPanel): Stop =
OnStateChanged(eStop)→OnStop(); Reset =OnStateChanged(eReset)→OnReset(); Init =OnStateChanged(eInit)→OnInit(); Terminate =OnStateChanged(eTerminate)→OnStop().
OnStop() also runs at start-up, before OnInit(): never release in OnStop() what OnReset() created and OnRun() needs.
The engine converts the LRUs around each of these calls (Raw2Eng before, Eng2Raw after).
Model Constructor
Called once when the model is created. Use to:
-
Initialize one time objects. for example:
const int numOfTasks = 10; tasks = std::make_unique<CTasks>(numOfTasks); hAsyncThread = tasks->AddThread("AsyncThreadName1", [](void* pObj, void* param1, void* param2, void* param3) { ((CMyModel*)pObj)->AsyncCmd(nullptr, nullptr, nullptr); }, this); -
Configure the CPU affinity for the model. The example below sets it to use Core 0 and Core 2:
cores = { true, false, true }; -
Set the thread priority. The example below sets the thread to the highest priority level:
eThreadPriority = EThreadPriority::Highest;
Updating a Model's Version
Every model passes its name, version, and core affinity to the CModelBase base constructor:
C{{ModelName}}::C{{ModelName}}() : CModelBase("{{ModelName}}", "1.00", {{{CoreAffinityArray}}})
{
}
The version is a free-form string — there's no separate build step to keep it in sync. To "release" a new version of a model, just update that string literal. It's shown live per-model in DIPanel's Core States and System Layout's Status view, so mismatched versions across a deployment are easy to spot. Drivers work the same way — see the driver layer constructor.
OnReset()
Called FIRST at start-up (before OnInit()), and again by every Reset command. Use to:
- Set the model's minor frame frequency via
SetMinorFrame()(e.g., -1 = every simulator minor frame) - Fetch shared resources (LRUs) and initialize pointers
- Reset internal counters and state
OnInit()
Called at start-up, AFTER OnReset() (and OnStop()), and again by every Init command. Use to:
- Initialize state controllers (e.g.
CStatesController::AddController<T>("Group")) - Set initial state statuses (
SetStateStatus(...)) - Configure stream triggers and callbacks (
SetStreamTrigger,SetStreamBlockReceiveCB,SetStreamBlockPreSendCB,SetStreamBlockPostReceiveAcceptCB) - Call global initializers like
OGIInit()(only once from one model) - Register a custom keyboard handler, if this model needs to react to key presses (
KeyListener::SetCallbackHandler(...))
Custom Keyboard Handling
Register a handler once from OnInit(), then react to keys in the callback:
void C{{ModelName}}::OnInit()
{
KeyListener::SetCallbackHandler(HandleKeyEvent);
}
void HandleKeyEvent(const KeyEvent& k)
{
auto key = ::toupper(k.key);
if (key == 'X') {
// Do your logic for key 'X' pressed by the user
}
// Optional: fall through to the engine's default keyboard handler
// CCoreEngine::HandleKeyEvent(k);
}
CCoreEngine::SetupMainKeyboardHandler().
How keyboard handling works (KeyListener)
KeyListeneris a static class that owns the engine's keyboard thread. It is started at engine start-up when"Keyboard": { "active": ... }is enabled in config.json (the thread's CPU affinity and priority come from the same section) and stopped at shutdown.- The thread reads the console: on Windows it reads console key-down events (only while the CoreEngine console window is the focused one); on Linux it puts the terminal in raw mode and reads
stdinevery 100 ms. Every key press becomes aKeyEventand is passed to the current callback. KeyEventhaskey(the ASCII character, or the virtual-key code when there is no character), and the modifiersctrl,alt,shift. Compare keys with::toupper(k.key)so both cases work. On Linux the modifiers are derived from the terminal bytes: Alt = anESCprefix, Ctrl = a control character, Shift = an upper-case letter.- There is exactly one current callback. The engine installs its built-in handler first; a model replaces it with
KeyListener::SetCallbackHandler(handler)(anystd::function<void(const KeyEvent&)>: a free function, a lambda or a bound member). Setting a new one replaces the previous one; the built-in engine commands stop working until it is restored. - The engine's built-in keys: R reset, I init, U run, S stop, C record, P pause record, W write the report to a file, ? information menu (Stream setup opens streams.json, Versions, Dump memory, Back) and Ctrl+X terminate. To keep them while adding your own keys, call
CCoreEngine::HandleKeyEvent(k)for the keys you did not handle; to restore them completely callCCoreEngine::SetupMainKeyboardHandler().
OnRun(), with no synchronization. Keep it short, never block in it, and do not touch data that OnRun() uses without protection: set an std::atomic flag (or push to a lock-free queue) in the callback and act on it in OnRun(). Choose keys that do not collide with the engine's built-in keys, and remember that only the engine's console window receives the keys (a remote or service-run engine has no keyboard).
static std::atomic<bool> g_dumpRequested{false};
void CMyModel::OnInit()
{
KeyListener::SetCallbackHandler([](const KeyEvent& k) {
switch (::toupper(k.key)) {
case 'X': g_dumpRequested = true; break; // handled here
default: CCoreEngine::HandleKeyEvent(k); break; // keep the engine commands
}
});
}
void CMyModel::OnRun()
{
if (g_dumpRequested.exchange(false)) {
// do the work here, inside the model's own thread
}
}
OnStateChanged()
Called when the engine state changes: before the frames start (eRun / eStep) and before the Stop, Reset, Init and Terminate calls (eStop, eReset, eInit, eTerminate). A good place for actions at the start of a run (eRun), e.g. preparing the recording items.
OnRun()
Main per-frame execution callback. This is the hot path and must be fast and deterministic. Typical tasks:
- Execute each state controller (
CStatesController::ExecuteState("Group")) - Send or enqueue outputs to streams or drivers (
CDrivers::SendBlock) - Start async tasks without waiting for completion
- Collect lightweight profiling metrics or increment in-memory histograms
OnStop()
Called at start-up between OnReset() and OnInit(), by every Stop command and when the engine terminates. Use to quiesce resources, stop background operations,
or mark state controllers as paused. Keep what OnRun() needs: a Run after a Stop continues without OnReset() / OnInit().
OnFirstRun() and OnFreeze()
Not called by the engine. The generated model has empty OnFirstRun() and OnFreeze() functions, but CModelBase has no such
callbacks and the engine never calls them. For an action at the start of a run use OnStateChanged() with eRun, or a flag checked in the first OnRun().
States and State Controllers
Inside a model, states are grouped into logical State Controllers. Each controller manages a group of states and has its own play/pause/reset controls.
Why group states?
- Modularity: group related behaviors (communication, initialization, health checks)
- Control: pause or reset groups independently
- Sequencing: controllers allow deterministic ordering inside a model
Common operations
// Add controller and set status
CStatesController::AddController<CCommCheck>("CommChecks");
CStatesController::SetStateStatus("CommChecks", CACState::EStateStatus::ePlay);
// Execute controllers in OnRun
CStatesController::ExecuteState("CommChecks");
Step by step, with the order of the calls and a full example: How to develop a state machine.
How to develop a state machine
A state machine is a set of states (one C++ class each) run by a state controller: the controller holds exactly one current state,
runs it when the model calls it, and switches to the state its Execute() returns. Several controllers are several machines running side by side,
each played, paused and reset on its own. Framework: CoreEng/core/States/state.h (CACState, TypeFactory, REGISTER_TYPE),
statesController.h (CStatesController).
- Draw it first: the states, what each one does every time it runs, and the condition of every transition. One controller per independent machine
(e.g.
"CommChecks","NormalFlow"). - Write one class per state, derived from
CACState, inModels/states/(APICCenter Generate Code with the State type, or a copy ofSampleState.h/.cpp); include its header inModels/states/states.hand add the.cppto the project'sCMakeLists.txt. - Give it a period: the constructor passes it to
CACState(periodUs)in microseconds. The state runs when its controller is executed and the frame number is a multiple ofperiodUs / minor frame; a period of one minor frame or less (or 0) = every time the controller is executed. The class must have a default constructor (the factory creates it withstd::make_unique<T>()). - Implement the four functions:
Execute(): the work of the state; returnsnullptrto stay, or the next state (return std::make_unique<CNextState>();) to switch.OnStateEntered(): called once when the state becomes the current one (entry action).OnStateChanged(EStateStatus): called when the controller's status changes (ePlay,ePause,eReset); the return value is not used.Name(): the name shown in the states reports (DIPanel States window, StatesHub).
OnStateEntered()runs first, then the old state object is destroyed. - Register it:
REGISTER_TYPE(CMyState);in its.cpp.AddController<T>and switching by name need it. - Attach it to a model: in
OnInit()create the controller with its first state and set it to play; inOnRun()execute it. A controller runs only while its status isePlay(a new controller starts inePause), and only as often as the model runs. - Control it from outside (another state, another model, a command):
SetStateStatus(name, ePlay | ePause | eReset),SwitchState(name, std::make_unique<CState>())orSwitchState(name, "CState")(by the registered name),GetExecuteState(name)->Name(),GetStateStatus(name).
// Models/states/WaitForData.h
class CWaitForData : public CACState
{
public:
CWaitForData() : CACState(10000) {} // runs every 10 ms
const char* Name() const override { return "WaitForData"; }
void OnStateEntered() override { Report(EStateReportType::eWaitFor, "waiting for the first input"); }
bool OnStateChanged(EStateStatus eStateStatus) override { return true; }
std::unique_ptr<CACState> Execute() override;
};
// Models/states/WaitForData.cpp
REGISTER_TYPE(CWaitForData);
std::unique_ptr<CACState> CWaitForData::Execute()
{
if (!InputArrived()) // your condition
return nullptr; // stay in this state
Report(EStateReportType::eSwitchTo, "Running");
return std::make_unique<CRunning>(); // switch: CRunning::OnStateEntered() runs next
}
// The model
void CMyModel::OnInit()
{
CStatesController::AddController<CWaitForData>("NormalFlow"); // first state
CStatesController::SetStateStatus("NormalFlow", CACState::EStateStatus::ePlay);
}
void CMyModel::OnRun()
{
CStatesController::ExecuteState("NormalFlow"); // runs the current state (when in play and due)
}
| Status | Effect |
|---|---|
ePlay | ExecuteState() runs the current state. |
ePause | Not run; the current state and its data are kept. The status of a new controller. |
eReset | Not run; the current state's OnStateChanged(eReset) is called to clear its data. It does not go back to the first state:
switch to it yourself (SwitchState(name, std::make_unique<CFirstState>())), then set ePlay. |
- Each switch creates a new state object (and destroys the old one): switch on events, not every frame, if the model must not allocate while running.
Keep
Execute()short and never block: it runs inside the model'sOnRun(). - Re-init: an Init command calls
OnInit()again;AddControllerthen replaces the machine with a new one in its first state (paused until you set it to play). - Data between states: keep what several states need in the model or in the LRUs (blocks), not in a state object: it is destroyed at the switch.
- Reports:
Report(EStateReportType::eWaitFor | eSwitchTo | eInfo | eWarning | eError, text)sends a line to the states reports of the current state.
Rates & Dependencies
Each model executes at a configured minor frame rate. Rates can be:
-1— run every simulator minor frame0— disabled (does not run)- >0 — run every X simulator frames
Multiple models may run in parallel. If model A depends on model B, declare that dependency (via configuration or the scheduler) so the scheduler orders execution appropriately.
Example: a sensor model may run at 1 kHz while a heavy physics model runs at 125 Hz. The scheduler should ensure data produced by the physics model is propagated deterministically (e.g., via timestamped buffers) to the higher-rate consumer.
Streams, IO & Recording
Models can publish or subscribe to streams. Use stream triggers to run a model only when specific data arrives. Register callbacks around the raw send/receive path:
// Execute only when a block arrives on StreamName/BlockName
SetStreamTrigger("StreamName", "LRUName.BlockName");
// Called just before the raw block is sent out
SetStreamBlockPreSendCB("StreamName", "LRUName.BlockName", &Cmodel2::OnPreSendCB);
// Called just after the raw block is received, before it is accepted
SetStreamBlockPostReceiveAcceptCB("StreamName", "LRUName.BlockName", &Cmodel2::OnPostReceiveAcceptCB);
// Register receive callback
SetStreamBlockReceiveCB("StreamName", "LRUName.BlockName", &Cmodel2::OnReceiveCB);
All three callbacks share the same signature, which now includes the block name:
void Cmodel2::OnReceiveCB(const char* blockName, const uint8_t* raw, uint64_t size);
void Cmodel2::OnPreSendCB(const char* blockName, const uint8_t* raw, uint64_t size);
bool Cmodel2::OnPostReceiveAcceptCB(const char* blockName, const uint8_t* raw, uint64_t size);
- SetStreamBlockPreSendCB — called just before the raw data is sent out. Useful for calculating a CRC or otherwise finalizing the raw buffer before transmission.
- SetStreamBlockPostReceiveAcceptCB — called just after the raw data is received, before it is accepted. Useful for validating the raw message. If it returns
false, the message counter is not incremented and the registered stream trigger is not called. - SetStreamBlockReceiveCB — called after a received block has been accepted.
CDrivers::SendBlock bypasses the registered pre-send hook (and RecvBlock the receive hooks). See Stream Block Hooks in the streams manual for the exact order of events (post-receive-accept → counters → receive → model trigger), a usage example and the performance and synchronization notes.
For recording, prefer pushing small descriptors into a lockless SPSC ring in the hot path and let the recording thread serialize or write the large data off the critical path.
Raw ↔ Eng Conversion
Every ICD block generated by DBSimGenerator has a raw
form (the exact bytes on the wire) and an eng (engineering) form — the ordinary C++
value your model code reads and writes. The conversion is called once per LRU — it
converts every block belonging to that LRU in one call, not one call per block. Convert explicitly in
OnRun():
void C{{ModelName}}::OnRun()
{
// Convert Raw to Eng (after new raw data has arrived on a stream) — converts all blocks of this LRU
CLRUsProj::{{LRUName}}->Raw2Eng();
// ... read/modify the eng-side elements of any of this LRU's blocks here ...
// If you modified eng values and need them sent out, convert back before returning:
CLRUsProj::{{LRUName}}->Eng2Raw();
}
Which conversion a given block uses is a property of that block, set once in DBSimGenerator, not something you choose per call:
| Convention | Meaning |
|---|---|
NoRaw | The block has no physical/binary raw representation (e.g. purely internal/software-only data) — there is nothing to convert. |
LElsb | Little-Endian byte order, bits numbered from the Least-Significant Bit (bit 0 = LSB) — the natural C/C++ convention. |
LEmsb | Little-Endian byte order, bits numbered from the Most-Significant Bit. |
BElsb | Big-Endian byte order (network/wire order), bits numbered from the LSB. |
BEmsb | Big-Endian byte order, bits numbered from the MSB — common in avionics/MIL-STD style ICDs. |
Raw2Eng()/Eng2Raw() code for each block's chosen convention. You only need to know which convention a block uses when cross-checking its layout against an external ICD document or a driver's wire format.
Skip Unchanged Data
Use CCoreEngine::CValueChangeGate to skip processing an element that hasn't
changed since the last call — useful right after a Raw2Eng() conversion, before doing
any expensive work with the converted value.
Async Commands
Async tasks
For long-running or blocking operations (file I/O, network, complex computation), use a thread pool or async task manager. Important rules:
- Do not block the real-time
OnRun()while waiting for async work. - Check task availability before starting to avoid duplicate runs (
tasks->IsTaskBusy()). - Prefer to enqueue and forget; use status flags or callbacks to detect completion.
Syncing an async thread to the frame cycle
When an async thread needs to run in lockstep with CoreEngine frames (rather than fire-and-forget), register it
with CCoreEngine::PhaseCoordinator and wait on a barrier for its assigned phase:
void C{{ModelName}}::AsyncCmd(void* p1, void* p2, void* p3)
{
auto& barrier = CCoreEngine::PhaseCoordinator.GetBarrier({{Phase}});
barrier.Register();
uint64_t generation = 0;
while (true)
{
barrier.WaitForPhase(generation);
// ... do work for this phase ...
barrier.NotifyDone();
}
barrier.Unregister();
}
Guarding against multiple calls per minor frame
A model can have several stream triggers or callbacks that all funnel into the same shared logic. If more than one of them can fire within the same minor frame, guard the shared code with CCoreEngine::CMinorFrameGate so it only executes once per frame no matter how many times it's called:
static CCoreEngine::CMinorFrameGate frameGate;
if (!frameGate.ShouldRun())
return;
// this code runs at most once per CoreEngine minor frame
Profiling
Keep profiling lightweight in the hot path: use scope profilers or running averages. Avoid heavy logging. Examples from the sample:
// scope profiler
{
static CRunningAverage runningAverage;
CSimScopeProfiler simScopeProfiler("profilingTaskName", &runningAverage);
}
// manual timing
auto startT = std::chrono::high_resolution_clock::now();
// ... work ...
runningAverage.add(std::chrono::duration_cast(
std::chrono::high_resolution_clock::now() - startT).count());
Global functions and properties (CCoreEngine)
The engine's static members can be used from any model, state, driver or thread: CCoreEngine::<name>
(CoreEng/core/CoreEngine.h, included through core/ModelsBase.h). Older projects and pages call the class CSimEngine.
Read them freely; the engine writes them, except where the table says otherwise.
Properties
| Name | Type | Meaning |
|---|---|---|
bRunning | bool | true while the engine runs, false when it terminates. A loop in a thread of your own should end when it becomes false. |
iMinorFrameCounter | int | Number of the current minor frame of the run (the first frame is 1; 0 after Stop, Reset and Init). Frame-based timing, once-per-frame checks. |
eCoreEngineState | ECoreEngineState | The engine state: eUndef, eReset, eInit, eStop, eRun, eStep, eTerminate.
Writing it asks the engine to change state, as the keyboard and the network commands do (e.g. CCoreEngine::eCoreEngineState = CCoreEngine::ECoreEngineState::eTerminate;).
A model is told about changes in OnStateChanged(). |
projectId | std::string | The project name given to the engine at start-up. |
AppVersion | CVersion | The application version: m_productName, m_version, m_company, m_vendor (and the compatible CoreEngine versions). |
BootConfig | CBootConfig | config.json as read at start-up: BootConfig.Get().folders, .realtime (affinity, priority, bTimingFixTime), .keyboard, .reflector,
.startup, .EngineSync, .crashdump, .recorder (see config.json). |
timingMode | EFrameTimingMode | How the frame period is kept: FromLastFrame (from the end of the previous frame) or FromFixedClock (aligned to the start of the run, no drift); config.json RealTime bTimingFixTime. |
systemStartNANOSec | steady_clock::time_point | Start of the run (set again by Reset and Init). The ElapseSinceStart...() functions measure from it. |
bLowLatency | bool | Linux: a low-latency kernel was found. |
lowLatencyCores | int | Number of cores in the real-time setup (config.json RealTime affinity). |
pEngineSync | IEngineSync* | External frame sync (config.json EngineSync); nullptr = the engine paces the frames with its own clock. |
PhaseCoordinator | CPhaseCoordinator | Barriers that run an async thread in step with the frames: PhaseCoordinator.GetBarrier(phase), see Syncing an async thread. |
ThreadPool | std::unique_ptr<CThreadPool> | The engine's thread pool (the models and streams run on it). For your own background work use CTasks (Async tasks). |
eRecordState | std::atomic<ECoreEngineRecorderState> | The recorder state (eUndefPlayback, eRecord, eInitPlayback, eStopPlayback, eRunPlayback, eStepPlayback). Change it through CRecorder, not directly. |
recordingItemsMutex | std::recursive_mutex | Internal: guards the recorder's item list (taken by the CRecorder functions). Never in OnRun(). |
Functions
| Function | Returns | Meaning |
|---|---|---|
ElapseSinceStartSec(), ElapseSinceStartMilliSec(), ElapseSinceStartMicroSec(), ElapseSinceStartNanoSec() | double | Time since the start of the run (systemStartNANOSec), steady clock. No system call beyond reading the clock: fine in OnRun(). |
GetMinorFrameUSec() | int | The minor frame period in microseconds (the LRU refresh rate set in DBSimGenerator). |
GetMinorFramesFromTimeUSec(double timeUs) | int | Whole minor frames in a time (never negative): GetMinorFramesFromTimeUSec(100000) = 100 at a 1 ms frame. |
GetDBSimPath() | const char* | The setups folder (streams.json, the LRU file): for files of your own next to them. |
GetAppPath() | const char* | The folder of the executable, with a trailing /. |
GetTestPath() | const char* | The tests folder (config.json folders tests), or nullptr when there is none. |
SetDBSimPath(path, testPath) | Set by the engine at start-up from the command line / config.json; not for models. | |
SetupRecording(const std::string& json) | Replaces the recording items with a JSON object and starts recording, as the network record: command does. Allocates: call it outside OnRun(). Usually CRecorder is simpler. | |
RecordingFlushFrames() | int | The recorder's flushAfterFrames value. |
HandleKeyEvent(const KeyEvent&), SetupMainKeyboardHandler() | The engine's keyboard commands: call the first for keys your own handler does not use, the second to restore the engine's handler (keyboard handling). |
Helper classes
| Class | Meaning |
|---|---|
CCoreEngine::CMinorFrameGate | ShouldRun() is true once per minor frame: code reached several times in one frame (several triggers / callbacks) runs once (example). |
CCoreEngine::CValueChangeGate<T> | Watches a variable: ShouldRun() is true when its value changed since the last call (Skip Unchanged Data). |
void CMyModel::OnRun()
{
// every 100 ms, whatever the minor frame is
static const int every = CCoreEngine::GetMinorFramesFromTimeUSec(100000);
if (every > 0 && CCoreEngine::iMinorFrameCounter % every == 0)
CSimReports::ReportMsg(EReportType::eInfo, "100 ms tick");
if (CCoreEngine::ElapseSinceStartSec() > 60.0) // stop the run after a minute
CCoreEngine::eCoreEngineState = CCoreEngine::ECoreEngineState::eStop;
}
Setup(), Start(), SetupArguments() and the Print...() functions are used by the application's main() to create and start the engine, not by models.Typical Model Flow (Example)
OnReset(): (start-up: first)
- Set minor frame using SetMinorFrame()
- Reset state controllers and counters
OnInit(): (start-up: after OnReset and OnStop)
- Initialize states and controllers
- Set stream triggers and callbacks
- Pre-allocate buffers
OnStateChanged(eRun): (before the first frame of a run)
- One-time start tasks (timers, warm-up)
OnRun():
- Execute state controllers (fast, deterministic)
- Enqueue record descriptors into ring buffer
- Optionally start async tasks (non-blocking)
OnStop(): (also at start-up, before OnInit)
- Quiesce background threads, flush buffers (keep what OnRun needs)
Integration & Best Practices
- Pre-allocate all model-local buffers and structures in
OnInit(). - Avoid blocking operations in
OnRun(). Use lockless handoffs to background threads. - Set
SetMinorFrame()appropriately inOnReset()depending on how often the model should run. - Use state controllers to group related functionality and to enable/disable features at runtime.
- Prefer descriptive, small messages to the recorder (pointer or index) rather than raw blobs in the hot path.
- Document cross-model dependencies and ensure the scheduler respects ordering.