C++ API#
A C++ station includes one header, <paperboat/sdk.hpp>, which brings everything below
into namespace paperboat (paperboat::Block, paperboat::define_block,
paperboat::main…). Headers it doesn’t include may change. Link paperboat::core.
The SDK#
A station builds against the engine in one of two ways:
From a checkout:
add_subdirectory(<paperboat>/engine paperboat EXCLUDE_FROM_ALL).From an installed package:
find_package(Paperboat 0.1 CONFIG REQUIRED). The SDK is thelib/,include/andlib/cmake/Paperboatparts of the.tar.gzand the.zip. Its libraries are Release builds (shared on Linux and macOS, static on Windows), so nothing is rebuilt and nothing is downloaded at configure time. Toolkits installed withpaperboat toolkit installcome with it aspaperboat::toolkit_<name>.
Either way the targets are paperboat::core (links paperboat::toolkit) and paperboat::warnings
(the engine’s warning flags). The version check is SameMinorVersion: a station that asks for 0.1
needs a 0.1.x SDK. On Windows the SDK uses the static runtime (/MT); its config sets
CMAKE_MSVC_RUNTIME_LIBRARY to match unless you set it.
Optional toolkits (control, opencv, optimization) stay source-only: paperboat toolkit install <name> --repo <url>
(or --path <dir>) compiles one into the engine, so it needs a checkout. The SDK holds the built-in
packages only. The manifest’s repo is a suggested source, not an automatic download.
API Quick Reference#
Category |
Symbol |
Description |
|---|---|---|
Definitions |
Input/output port configuration (id, type, vector units). |
|
Named component channel within an ordered vector port. |
||
Parameter or property definition (number, key, enum, file). |
||
Complete declarative block definition (type, ports, params, kind). |
||
Station object template definition, properties, and link slots. |
||
Values & Context |
Map of string keys to typed values (numbers, vectors, tables, handles). |
|
Safe parameter or signal extraction helper with fallback default. |
||
Execution context providing clock time |
||
Block Subclasses |
Base computational block owning state and implementing |
|
Signal generator computing \(f(t)\) from time and parameters. |
||
Procedural step block implementing |
||
Timed step block executing for a fixed duration. |
||
Fast mathematical expression evaluator over named variables. |
||
Station & Geometry |
Equipment object providing |
|
Geometry entity rendered in 3D/2D on the Station page. |
||
|
3D and 2D visual geometry entity construction helpers. |
|
Solvers & Physics |
Continuous ODE physics model with state derivatives. |
|
Abstract numerical differential equation solver interface. |
||
Advance state vector across one time step using an ODE solver (e.g. RK4). |
||
Domain & Server |
Domain-wide shared state updated after topological passes. |
|
Repository of block and station object definitions. |
||
Factory helper binding C++ |
||
Factory helper binding C++ |
||
Reads and validates |
||
|
Standard CLI entrypoint launching station server processes. |
|
|
High-performance WebSocket and HTTP server loop. |
|
Schedulers |
|
Abstract graph execution engine runner. |
|
Active run execution lifecycle and telemetry emitter. |
Definitions#
What the UI shows and descriptors refer to. All fields have defaults, so designated initializers may leave any out.
-
struct PortDef#
A block’s input or output.
-
std::string id#
-
std::string type = "signal"#
"signal"(a value),"step"(control, in a Step flow) or a shape:"image","points","vector"… A wire joins ports of one type. Lists (#24):"numbers"is a list of numbers (any length; it joins"vector"ports, a vector being a list of fixed length) and"points"a list of points (aTable, one row per point). Make them withnumbers_port()andpoints_port(); see the list package. A matrix is a rectangularTable(rows of columns) on an ordinary"signal"port with thematrixflag set; make one withmatrix_port().
-
std::string unit#
A shared unit, or the fallback unit for vector components without their own.
-
std::optional<std::size_t> dimension#
A vector’s fixed length. Absent: dynamic length; component metadata also fixes it. On a
"points"port, the coordinates of each point (the list’s own length is never declared).
-
std::vector<VectorComponent> components#
Optional ordered component labels and units. Names are descriptive; dimensions and units, not labels, decide whether two vector ports fit.
-
bool broadcast = false#
Set on the signal ports of an
elementwiseblock (seewith_broadcast()): the port also joins a vector port. The engine sets it; a block author never does.
-
std::string type = "signal"#
-
std::string id#
-
struct VectorComponent#
-
std::string id#
The component’s label, in vector order.
-
std::string unit#
Its optional unit.
-
std::string id#
-
PortDef vector_port(std::string id, std::vector<VectorComponent> components)#
Make a
"vector"port. For example,vector_port("state", {{"x", "m"}, {"angle", "rad"}})puts a mixed-unit state on one wire while retaining the names and units of its components.
-
PortDef points_port(std::string id, std::vector<VectorComponent> coordinates = {})#
-
PortDef matrix_port(std::string id)#
Make a list port (#24):
"numbers", a list of numbers in oneunit, or"points", a list of points;points_port("profile", {{"x", "m"}, {"z", "m"}})fixes each point’s coordinates and their units. A block gives a list of numbers as aVectorand a list of points as aTable.matrix_port("a")carries a rectangularTable; the math package’s matrix blocks check its shape.
-
struct ParamDef#
A setting on a block (or a property of a station object), edited in the UI.
-
std::string id#
-
double default_value = 0.0#
-
std::string type = "number"#
Number types (to the block as
Values):"number","boolean"(a checkbox; 1 or 0). Text types (throughConfig):"text","matrix"(MATLAB-style matrix rows,"1 2; 3 4"),"key"(aKeyboardEvent.code, picked by pressing it),"file"(a path, relative to the descriptor’s folder),"enum"(one ofoptions, a dropdown; the block also gets its index inValues),"variable"(the name of a project variable, a picker; forContext::set_variable()).
-
std::vector<std::string> options#
An enum’s choices.
-
std::string default_text#
The default of a text param.
-
bool is_number() const#
-
std::string id#
-
enum class Kind#
-
enumerator Source#
Pushes into the domain.
-
enumerator Probe#
Reads it.
-
enumerator Function#
Computes.
-
enumerator Monitor#
Shows a value on the Board as an instrument.
-
enumerator Source#
-
struct BlockDef#
-
std::string type#
Unique within a catalog (
"pid","pid-theta").
-
std::vector<std::string> flows#
The flow types it works in (
signal,step,state,model): the palette offers it on those sheets only, and a run refuses it on another (#9). Empty: every type.
-
std::string label#
-
std::string instrument#
A monitor’s instrument:
"graph","display"or"image".
-
std::string description#
One line in plain words: what the block does. Shown on its card in the block browser. Optional; the built-in templates have one, and a descriptor may set
description.
-
View view#
How the UI draws the block: a hint, so a block without it is the normal card.
compactdraws a small plate with aglyph(a few characters drawn as text; a curve is anicon) and a caption with the name andvalue(an expression of the params,"{k}");icon(an opaquenlohmann::jsonobject,nullwhen absent) supplies a token-quantised vector icon ({w, h, g, ports}) rendered on the plate without raw colours or SVG path strings. Every key is optional: a definition inherits its parent’sviewand overrides single keys (View::overridden_by()). The built-in simple maths and logic templates have one; a descriptor may setview.
-
bool feedthrough = true#
falsefor a block whose outputs this step don’t depend on its inputs this step (an integrator, a delay). ItsBlockgivesoutputs()during the pass and takes its inputs instep()after it, so a feedback loop may pass through it. A loop with no such block is an algebraic loop: the run solves it each pass (seeBlock::outputs_for()), or fails naming a block in it.
-
std::vector<Form> forms#
A magic block’s forms. Its
inputsandoutputsare the first form’s; its enum paramformpicks one (seemagic_def()).
-
std::string ports_from#
The id of a text param that decides the inputs: one per sign character in it (
"+-+":a,b,c; seeparse_signs()), of the first input’s type. Empty: the inputs are the definition’s. Sum’ssigns. A wire to an input that no longer exists is dropped.
-
std::string inputs_from#
The id of a text param whose expression’s free names are the inputs: one per identifier in it (other than
pi,eand built-in functions, in order of first appearance; seewith_inputs()), of the first input’s type. Empty: the inputs are the definition’s. f(t)’sf. A wire to an input that is removed or renamed is dropped.
-
std::string outputs_from#
The id of a text param of names (
"x v theta", seeparse_names()) that are the outputs, ids in that order. The first vector input gets one component per name, and aunitsparam ("m m/s rad") gives each a unit by position. Demux’snames.ports_from = "names"does the same for the inputs (Mux), giving the first vector output the components.
-
bool elementwise = false#
The block works on one number at a time and the engine lifts it to vectors (#164). Its signal ports also take a vector wire. With only numbers in, nothing changes. With any vector in, all vectors must be one length N (else the run fails naming the block and port), numbers broadcast to every element, and the block runs as N instances, lanes, each fed its element and keeping its own state (one integral per element); its outputs are vectors of N, labelled like the vector that came in. A param change reaches every lane. N is found from the wires when the graph is compiled, so a block without feedthrough in a loop knows it before its first step; if the length is known only at run time (a vector port with no
dimension) such a block fails at compile, and any other takes N from its first step. The built-in pointwisemathblocks, f(t) and the generators, Integrator, Lag and PID are elementwise; Delay is not (it moves whole values). A block that needs the whole vector (a norm, a dot product) declaresvector_port()ports instead.
-
std::optional<bool> cacheable#
Whether a run that evaluates once may reuse this block’s outputs from an earlier run (see
RunCache) instead of calling it, when nothing it depends on changed: its type, params, text, the values on its wires and the variables it read throughContext::variable().true: it is a pure function of those (no clock, keys, domain state, randomness, files other than itsfileparams, or side effects): the text, conversion, logic, If and Variable blocks.false: it is always called (Random Number, Key, Now). Unset: as its instance says,Block::stateless()(Constant, Gain, Sum, Mux… are reused). Runs on a clock and Step flows never reuse outputs.
-
std::string type#
-
struct Form#
One form of a magic block: the ports it has in that form, such as
"signal"(values in and out) or"step"(a step on a Step flow’s path).-
std::string name#
-
std::string name#
-
std::vector<int> parse_signs(std::string_view text)#
The signs in
text, one per input:+is 1,-(or−) is -1; anything else is skipped. At most 26; none at all reads as"++".
-
std::vector<std::string> parse_names(std::string_view text, const std::vector<std::string> &reserved = {})#
The names in
text, split on spaces and commas: what anamesparam makes ports of. Throwsstd::invalid_argumenton none, a name used twice, one that isn’t an identifier, one inreserved(the block’s other ports) or more than 64; in a run the block fails.
-
BlockDef with_broadcast(const BlockDef &def)#
defwithbroadcastset on its signal ports if it is elementwise (what the catalog sends), elsedef.
-
BlockDef with_signs(const BlockDef &def, std::string_view text)#
The definition with the inputs its
ports_fromparam (text) gives: idsa,b,c… of the first input’s type.defitself if it has noports_from.
-
BlockDef with_inputs(const BlockDef &def, std::string_view text)#
The definition with the inputs its
inputs_fromexpression param (text) gives: one per free name intext, in order of first appearance, of the first input’s type.defitself if it has noinputs_from. A wire to a removed or renamed input is dropped.
-
BlockDef in_form(const BlockDef &def, std::string_view form)#
The definition in form
form: that form’s ports.defitself if it has no forms, or no form of that name.
Values#
-
struct Value : std::variant<double, Vector, Table, std::string, Handle>#
What a wire carries: a number, a vector of numbers, a table (rows, such as points as
[x, z]), text, or a handle. Any arithmetic type converts todouble.
-
using Vector = std::vector<double>#
Ordered numeric data. The port’s type (
"vector"), optional dimension and component metadata describe its wire contract.
-
using Table = std::vector<std::vector<double>>#
-
using Values = std::map<std::string, Value>#
Port or param id → value (with a transparent comparator).
-
using Config = std::map<std::string, std::string>#
Text settings: a template’s config, and every text param by id.
-
struct Handle#
Data the engine passes along without knowing what it is (an image, a mesh). Shared and immutable, so one output can feed many inputs.
-
std::string kind#
Agreed between packages; matches the ports’ type (
"image").
-
std::shared_ptr<const void> data#
-
std::string kind#
-
double get_or(const Values &values, std::string_view id, double fallback = 0.0)#
The number at
id, orfallbackwhen absent or not a number (an unconnected input reads as 0).
-
template<class T>
const T *get_if(const Values &values, std::string_view id)# The vector/list, table or text at
id, or null.
-
const Vector *get_vector(const Values &values, std::string_view id)#
The numeric vector at
id, or null. A Python block reads the same value as a list.
-
Vector as_vector(const Values &values, std::string_view id)#
The numbers at
idas a vector: a vector as it is, a number as one element, otherwise (absent, text…) empty. For a block with avector_port()input that should also take a plain number.
What runs#
-
struct Context#
What a block sees on each call.
-
double t = 0.0#
The run clock, s (0 in a run that evaluates once).
-
double dt = 0.0#
The clock step, s.
-
const KeySet *keys_down = nullptr#
Keys held down in the UI (
KeyboardEvent.codevalues).
-
DomainState *state = nullptr#
The domain’s shared state for this run, if it has one.
-
std::string_view node#
The id of the block (or station object) being called.
-
const Values *variables = nullptr#
The run’s variables by name: a number, a boolean as 1 or 0, text for the rest. A variable marked
tunablemay change between steps (#75); any other is constant for the run.
-
const Value *variable(std::string_view name) const#
A variable’s value now, or null if there is none of that name. The run records the read (
variable_read_fn), so a run-once’s cache knows which variables a block’s result depends on.
-
bool set_variable(std::string_view name, const Value &value) const#
Set the tunable variable
name(#166), as an autotuner or a calibration does: a number for a number or boolean variable, text for an enum, text or file one. It takes effect at the end of the pass, so every block in a pass sees the same variables; formulas over it and params bound to it follow (a block that takes no live change is told once in the Console), and the UI keeps the value in the project. Returns false, with a warning in the Console, if the variable is unknown, nottunable, a formula, of another type, or the value is outside itsmin/max.
-
void log(std::string_view text, std::string_view level = "info") const#
Write a line to the Console (
info,warn,error), tagged withnode.
-
void progress(double fraction) const#
How far a long step has got, 0 to 1 (a filter over a big image, a solve): the UI shows it on the block. Optional; call it as often as is useful, the run sends at most ~20 a second.
-
void metric(std::string_view series, double y, std::string_view unit = {}) const#
-
void metric(std::string_view series, double x, double y, std::string_view unit = {}) const#
A point of a series that isn’t on the run clock (#17): a solver’s residual against its iteration, a sweep’s cost against its case. The run sends a
metricevent. Withoutxthe point is the series’ next index (0, 1, 2…);unitis y’s. A NaN or infinite point is dropped.
-
void monitor_state(MonitorState now, double value, std::string_view port = {}) const#
What a monitor says about its input now (
MonitorState::Ok,WarnorTrip; a Lamp) and the value that put it there. Call it every step: the run sendsmonitor.stateonly when it changes (perport, for a monitor of several inputs), and every monitor starts a run atOk.
-
void frame(const Frame &picture) const#
A live picture (#17):
Frameholds an optionalview([xmin, ymin, xmax, ymax], y up),shapes(FrameShape:tline,poly,circleortext; pointsp;r;s; tokenstrokeandfill) and an optionalfield(FrameField:w×hvaluesvrow by row from the top, NaN for no value,min/max). The run sends at most ~20 a second per block and always the latest at the end of a block in a run-once and of the run; one it can’t send (an unknown token, a point that isn’t finite, more than 65536 cells or 2000 shapes) warns once in the Console and is dropped.tk::Frame f{.view = std::array<double, 4>{-1.2, -1.2, 1.2, 1.2}}; f.shapes.push_back({.t = "line", .p = {{0, 0}, {std::sin(a), -std::cos(a)}}}); f.shapes.push_back({.t = "circle", .p = {{std::sin(a), -std::cos(a)}}, .r = 0.08, .fill = "signal"}); ctx.frame(f);
-
double t = 0.0#
-
class Block#
One instance of a block in a running graph. It owns its state; two instances never share anything.
-
virtual Values step(const Context &ctx, const Values &in) = 0#
Outputs from inputs. An unconnected input is absent from
in. Throw to fail the run; the error names this block. For a block without feedthrough it is called after the pass, to take the step’s inputs; others readoutputs().
-
virtual Values outputs() const#
A block without feedthrough (
BlockDef::feedthroughfalse): what it outputs now, from its state alone. Unused for other blocks.
-
virtual std::vector<Entity> entities() const#
What it draws on the Station after a step (a result to show). Default: nothing.
-
virtual bool set_param(std::string_view id, double value)#
The number param
idchanged during the run (#75): atunablevariable it is bound to has a new value. Take it and return true. The default returns false: the block reads its params only when made. Keep your state: a PID takes new gains and carries on with its integral.
-
virtual bool stateless() const#
True for a block whose outputs depend on its inputs and the clock alone. When
set_paramreturns false the run then makes it again with the new params. A block that is neither takes the change with the next run (the Console says so, once). Unless itsBlockDef::cacheablesays otherwise, a run-once may reuse a stateless block’s outputs from an earlier run. In an algebraic loop the run calls a stateless block’sstepmany times per pass to solve it.
-
virtual bool feedthrough() const#
falsefor an instance whose outputs this step don’t depend on its inputs this step though itsBlockDef::feedthroughistrue(a strictly proper transfer function). The run then readsoutputs()during the pass and callsstepafter it, so a feedback loop through it is not an algebraic loop. Asked once, when the graph is made.
-
virtual std::optional<Values> outputs_for(const Context &ctx, const Values &in) const#
What
stepwould return forinnow, without changing the block’s state (Simulink’s output function, apart from its update). A block with state and feedthrough implements it to sit in an algebraic loop: the run calls it while it solves the loop, thensteponce with the solution. The default returns none, and such a block in an algebraic loop fails the run.
-
virtual Values step(const Context &ctx, const Values &in) = 0#
-
class Step#
One instance of a block on a Step flow’s path (a block with step ports).
-
virtual std::string tick(const Context &ctx, const Values &in) = 0#
Each clock step while the path is here: the step output to leave by, or
""to stay (a wait, a move). A hat (step outputs, no step input) is ticked while idle and starts a path when it names an output.
-
virtual bool may_start() const#
For a hat: whether it may still start a path.
-
virtual bool ends_run() const#
True for a block that ends the whole run when a path arrives (Stop).
-
virtual std::string tick(const Context &ctx, const Values &in) = 0#
-
class StationObject#
One station object in a run: owns its state and properties.
-
virtual void step(const Context &ctx, const Values &in) = 0#
Advance one clock step under the linked block’s inputs.
-
virtual std::vector<Entity> entities(const std::string &id, double z) const = 0#
Its shapes, ids prefixed with
id + "/", at depthz.
-
virtual void link(std::string_view slot, StationObject &other)#
Another object fills one of its link slots; called once, after every object of the station is made.
-
virtual void step(const Context &ctx, const Values &in) = 0#
-
class DomainState#
What a domain’s blocks share during a run (a game, a document, a physical system). The engine makes one per run (
Station::state), hands it to blocks inContext::state, steps it after each clocked pass and draws it.-
virtual std::vector<Entity> patch() const#
The entities that change (for
scene.patch). Default: all.
-
virtual std::optional<std::string> step(const Context &ctx)#
Advance after a clocked pass. A message ends the run.
-
virtual std::optional<std::string> summary() const#
Logged when a run ends.
-
virtual std::vector<Entity> patch() const#
-
struct Entity#
One shape on the scene.
-
std::string id#
-
std::string shape = "box"#
"box","sphere"(size[0]= radius),"cylinder"(size[0]= radius,size[1]= length along y),"line"(pos→to) or"image".
-
std::array<double, 3> pos#
-
std::array<double, 3> size#
-
std::array<double, 3> rot#
Radians, applied in x, y, z order.
-
std::string color = "#888888"#
-
std::array<double, 3> scale#
-
std::array<double, 3> to#
A line’s end.
-
std::string src#
An image’s picture: a URL or a
data:URL.
-
std::string id#
Kinds of block#
Base classes in <paperboat/toolkit/bases.hpp>: derive and implement only what is
particular. Python has the same (paperboat.Generator, paperboat.Timed).
-
class Generator : public Block#
A signal f(t).
tis the inputtwhen wired (a step’sprogress), else the run clock; it outputsvalue(t).-
explicit Generator(std::string output = "y")#
-
virtual double value(double t) const = 0#
-
explicit Generator(std::string output = "y")#
-
BlockDef generator_def(std::string type, std::string label, std::vector<ParamDef> params = {}, std::string output = "y")#
-
class Timed : public Step#
A step that does its work over
seconds. Each clock step the work moves to thecurveinput’s value (clamped to 0–1; the first frame stays at 0) or, unwired, to the share ofsecondsgone; the last frame goes to 1 and leaves bynext. A steady 0.5 jumps to half at once, holds, and ends at 1. Outputsprogress(the share of time gone), to feed a curve.-
explicit Timed(double seconds)#
-
explicit Timed(double seconds)#
-
BlockDef timed_def(std::string type, std::string label, std::vector<ParamDef> params = {}, Kind kind = Kind::Function)#
Ports
in,curve→next,progress; addsseconds(1) ifparamslacks it.
-
BlockDef magic_def(std::string type, std::string label, std::vector<Form> forms, std::vector<ParamDef> params = {})#
A magic block: one block type that changes its ports with its
formparam, an enum of the forms’ names (the first is the default) added in front ofparams. Its template sets bothmake(for a form of signal ports) andmake_step(for a form with step ports); the engine makes the one the node’s form needs. Thebaselogic blocks are built this way:Template t; t.name = "base/if"; t.def = magic_def("if", "If", { {.name = "signal", .inputs = {{"cond"}, {"a"}, {"b"}}, .outputs = {{"y"}}}, {.name = "step", .inputs = {{"in", "step"}, {"cond"}}, .outputs = {{"yes", "step"}, {"no", "step"}}}, }); t.make = [](const Values&, const Config&) { return std::make_unique<Choose>(); }; t.make_step = [](const Values& p, const Config&) { return std::make_unique<Branch>(p); }; registry.add(std::move(t));
-
class Expression#
An expression over named numbers, compiled once (
<paperboat/toolkit/expression.hpp>).-
Expression(std::string_view text, std::vector<std::string> variables)#
Throws
ExpressionErrorsaying where (at 5: unknown function "sinn").
-
double operator()(std::span<const double> values) const#
Values in
variablesorder.
-
Expression(std::string_view text, std::vector<std::string> variables)#
Domain tools#
What domain code writes with, so it gives its equations and its look, never the stepping
or the entity fields (paperboat/toolkit/solve.hpp, model.hpp, scene.hpp, all
through sdk.hpp).
Solvers#
-
using solve::State = std::vector<double>#
A state of any size, known at run time.
-
using solve::Deriv = std::function<State(double t, const State &x)>#
dx/dtat(t, x); fordiscrete, the next state.
-
struct solve::Options#
The error control of
rk45,cvodeandida:rtol(1e-6),atol(1e-9) per component,min_step(0: automatic; it gives up below it),max_step(0: the clock step) andmax_steps(100000) sub-steps in one clock step before it gives up. The fixed-step solvers (rk4,rk2,euler) takesub_steps(1) steps ofdt / sub_stepsper clock step.
-
struct solve::Defaults#
The run’s solver:
name("rk4") andoptions, fromgraph.run’s settings (the Run menu’s solver and Solver settings) over the station’s (station.toml[run]). A run sets them on its own thread before it makes its blocks and objects.
-
class solve::Solver#
-
virtual void step(State &x, double t, double dt, const Deriv &f) = 0#
Advance
xfromttot + dt. Throwsstd::runtime_errorwhenfreturns a state of another size, orrk45,cvodeoridacan’t meet its tolerances inmax_stepssub-steps (an exceptionfthrows comes through as it was).
-
void restart()#
Forget what it carries between clock steps (
rk45’s step size,cvode’s andida’s history): call it after the equations change (a parameter tuned, a switch).cvodeandidaalso start afresh on their own when a step doesn’t begin where the last one ended, from the state it left (a bounce, a reset, a new run).
-
virtual void step(State &x, double t, double dt, const Deriv &f) = 0#
-
std::unique_ptr<solve::Solver> solve::make(std::string_view name, Options options)#
A solver by name, with the run’s options unless given.
auto(or"") is the run’s solver (solve::Defaults);rk4(classic Runge–Kutta, the default),rk45(Dormand–Prince, MATLAB’sode45: adaptive, it sub-steps inside the clock step to meet its tolerance, so signals still arrive on the clock),rk2(Heun),euler,discrete(a difference equationx[k+1] = f(t, x[k])), and the implicitcvodeandidafor stiff systems. Throwsstd::invalid_argumentnaming them, or for an option out of range.cvodeis SUNDIALS CVODE (variable-order BDF, Newton iterations on a dense Jacobian it estimates by difference quotients);idais SUNDIALS IDA, the same family of methods on the residualx' - f(t, x) = 0(the form a DAE solver takes;x'(t0) = f(t0, x0)makes it consistent from the start). Both choose their own step and order inside the clock step, stop exactly at its end (a stop time: the inputs change there), and keep their history for the next one, so keep one solver between steps (aModeldoes) rather thansolve::step()’s fresh one each time. They takertol,atol,min_step,max_stepandmax_steps(internal steps per clock step). They are there when the engine is built with SUNDIALS (CMake optionPAPERBOAT_WITH_SUNDIALS, on by default);solve::names()lists them then.
-
void solve::step(std::string_view solver, State &x, double t, double dt, const Deriv &f, Options options)#
One step with a fresh solver of that name.
Without
options: the run’s.
-
template<std::size_t N>
void solve::step(std::string_view solver, std::array<double, N> &x, double t, double dt, const std::function<std::array<double, N>(double, const std::array<double, N>&)> &f, Options options)# Fixed-size state overload for stepping with a fresh solver of that name.
-
const std::vector<std::string> &solve::names()#
The solvers, the default first:
rk4,rk45,rk2,euler,discrete, thencvodeandidawhen the engine has SUNDIALS.
-
ParamDef solve::param(std::string fallback = "auto")#
An enum param or prop
solver:auto(the run’s, set in the Run menu) or one ofsolve::names(), so the user may pick one for this block or object only.
paperboat::solve::State x = {1.0, 0.0};
auto rk45 = paperboat::solve::make("rk45", {.rtol = 1e-8});
rk45->step(x, ctx.t, ctx.dt, [&](double, const paperboat::solve::State& s) {
return paperboat::solve::State{s[1], -k / m * s[0]};
});
Model#
-
class Model : public StationObject#
A station object that is a system of differential equations. It gives its initial state and
derivatives(); the solver advances it each clock step, with the linked block’s inputs held through the step. It still implementsread()andentities().-
Model(solve::State initial, std::string_view solver, solve::Options options)#
auto: the run’s solver and options.
-
void set_solver(std::string_view solver)#
-
void set_solver(std::string_view solver, solve::Options options)#
Configure or switch the numerical solver for the model.
-
void restart()#
Start the solver afresh (
solve::Solver::restart()): call it after the equations change (a parameter tuned, a switch).
-
Model(solve::State initial, std::string_view solver, solve::Options options)#
struct Mass final : paperboat::Model {
explicit Mass(const paperboat::Values& p)
: Model({paperboat::get_or(p, "x0"), 0.0}, paperboat::get_text(p, "solver", "auto")),
k(paperboat::get_or(p, "k")) {}
paperboat::solve::State derivatives(double, const paperboat::solve::State& x,
const paperboat::Values& in) const override {
return {x[1], paperboat::get_or(in, "force") - k * x[0]};
}
paperboat::Values read() const override { return {{"x", x()[0]}, {"v", x()[1]}}; }
std::vector<paperboat::Entity> entities(const std::string& id, double z) const override {
return {paperboat::scene::rect(id + "/mass", x()[0], 0, 0.4, 0.4, "#2f5d62", 0, z)};
}
double k;
};
Scene builders#
Each returns an Entity. Points are scene::Vec (std::array<double, 3>),
y up; the 2D helpers lie in the x–y plane at depth z, which the 2D view shows.
-
Entity scene::box(std::string id, Vec pos, Vec size, std::string color = "#888888", Vec rot = {})#
Centred at
pos, turned byrot(radians, about x, then y, then z).
-
Entity scene::rect(std::string id, double x, double y, double width, double height, std::string color = "#888888", double angle = 0, double z = 0)#
-
Entity scene::circle(std::string id, double x, double y, double radius, std::string color = "#888888", double z = 0)#
Registering#
-
struct Template#
A reusable block: a definition and a factory. Named
"<package>/<block>".-
std::string name#
-
std::function<std::unique_ptr<Step>(const Values&, const Config&)> make_step#
…or for a block on a Step flow’s path.
-
bool extendable = false#
A parent for TOML definitions: a
useof it may add params and set any config.
-
bool abstract = false#
Only a parent:
importleaves it out.
-
std::string name#
-
template<class B>
Template define_block(const std::string &package, BlockDef def, Config config = {})# A template for
B(derived fromBlockorStep), constructed from(params, config),(params)or nothing. Namedpackage + "/" + def.type.registry.add(paperboat::define_block<Count>("parts", { .type = "count", .label = "Count parts", .inputs = {{"mask", "image"}, {"photo", "image"}}, .outputs = {{"total"}, {"marked", "image"}}, .params = {{"min_area", 150.0}}}));
-
template<class O>
StationTemplate define_object(const std::string &package, ObjectDef def)# A station template for
O(derived fromStationObject), constructed from(props)or nothing.
-
class Registry#
Templates and station templates by name.
-
void add(StationTemplate t)#
-
void add_connector(std::string package, std::string name, nlohmann::json def)#
Registers a Modelica connector definition (such as
"RealInput"or"Pin") underpackageso descriptors importingpackage(or whosedomainispackage) carry it incatalog.connectors.
-
std::vector<std::string> packages() const#
-
void add(StationTemplate t)#
-
const Registry &builtins()#
Every built-in template (packages
base,signal,math,board,step). Copy it and add the domain’s own; optional external toolkits such ascontrol(paperboat-toolkit-control),opencv(paperboat-toolkit-opencv) andoptimization(paperboat-toolkit-optimization) register withpaperboat::toolkit::control::register_control,paperboat::toolkit::opencv::register_opencvandpaperboat::toolkit::optimization::register_optimization.
Toolkit plugins#
With the engine built as shared libraries (-DPAPERBOAT_SHARED_LIBS=ON), a toolkit can also be a
plugin that a host loads at runtime, so installing it needs no engine rebuild (pb#352). A plugin is a
shared library named libpaperboat_plugin_<name> with one line of C++:
#include <paperboat/toolkit/plugin.hpp>
PAPERBOAT_TOOLKIT_PLUGIN(paperboat::toolkit::opencv::register_opencv)
The engine build makes one for every toolkit under engine/toolkit/<name>. A host calls
paperboat::toolkit::load_plugins(registry) after builtins(); the CLI and the scratchpad do. It
searches $PAPERBOAT_TOOLKIT_PATH, $PAPERBOAT_HOME/toolkits, the running binary’s build tree and
an installed lib/paperboat/plugins, skips a package the registry already has, and refuses a plugin
built for another paperboat version or C++ standard library (PAPERBOAT_PLUGIN_ABI) with a message
instead of loading it.
Loading#
-
struct Catalog#
A descriptor loaded against a registry: the app’s blocks and station objects, its top-level
connectorstable (passed unchanged intocatalog), its starters (graph,station, as protocol JSON text) and its Station view (station_view,station_page,station_visible). Its entries point into the registry, which must outlive it.
-
Catalog load_descriptor_file(const std::filesystem::path &path, const Registry ®istry = builtins())#
Throws
DescriptorErrorwith where the mistake is.
-
void define_blocks(Registry ®istry, const std::string &package, std::string_view toml_text)#
Blocks defined in TOML on parents in
registry, added as"<package>/<type>": how a package ships blocks that are only a definition.
-
std::string descriptor_domain(std::string_view toml_text)#
The
domainname, before loading (a host that registers the domain’s templates needs the package name first).
Serving#
-
struct RunSettings#
-
enum class Mode#
-
enumerator Clock#
Step everything on a clock (a Signal flow; a Step flow always does).
-
enumerator Once#
Evaluate a Signal flow once (a build, a query, an image pipeline).
-
enumerator Clock#
-
double dt = 0.01#
-
double duration = 10.0#
Run length (a Step flow: its limit), s.
-
int emit_every = 4#
Send signals and scene patches every N steps.
-
bool real_time = true#
Pace at wall-clock speed (
--runand tests turn it off).
-
double speed = 1.0#
Times real time when paced; 0: as fast as it can. The UI may change it per run, with
durationanddt(graph.run’ssettings), and during one (run.speed): pacing then goes on from where the run is, at the new speed.
-
enum class Mode#
-
RunSettings with_overrides(RunSettings base, const json &settings)#
basewith agraph.run’ssettingson top (any butmode). Throwsstd::invalid_argumentfor a value out of range; a run with one fails before it starts.
-
struct Station#
What a station is made of.
-
std::string engine#
Its name in
hello.
-
std::function<std::unique_ptr<toolkit::DomainState>()> state#
A fresh domain state per run (and one for the opening scene); empty if none.
-
json view#
The scene’s camera hint, e.g.
{"mode": "2d", "center": [0, 0], "height": 6}.
-
RunSettings run#
-
std::function<std::unique_ptr<Executor>(const Graph&, const RunSettings&)> executor#
Optional: a run style of the station’s own for this graph (return
nullptrto leave it todefault_executor()). Most stations leave it empty.
-
std::string engine#
-
int main(const Station &station, int argc, char **argv, int default_port)#
What a station’s
main()returns:--port Nserves the protocol (and a web station) there until the process ends;--runruns the starter once, headless, and prints every message as a JSON line (exit 0 when done, 1 when failed).
-
class Server#
The server, started and stopped by its owner (a host with its own main loop, such as the Python bindings):
start()returns""when listening, else why not;stop().
-
std::string run(const std::string &id, const json &graph, const json &station, const Station &cfg, const Emit &emit, const KeysNow &keys, const std::stop_token &stop)#
One run, without sockets: every event goes to
emit. Returns"done","failed"or"cancelled". For tests (withreal_time = false). Its last parameters (optional) are the run settings’ overrides, the variables, where it looks for tuned variables, where it finds a new speed (SpeedNow, run.speed, read between frames), and aRunCache: a run that evaluates once reuses the outputs of blocks nothing changed for since an earlier run with the same cache.
-
class RunCache#
<paperboat/core/cache.hpp>. What runs that evaluate once keep between runs: each block’s last good result by node id, with what it was computed from (its type, ports, params, text, lanes, the run’sdtand solver, itsfileparams’ files; the values on its wires; the variables it read). A later run reuses it only when all of these are the same, comparing values exactly (numbers bit for bit, a handle by the object it holds). Comparing values rather than the graph upstream invalidates exactly what a change reaches: a station object changed reaches only the blocks its linked block feeds, and an upstream change that gives the same values stops there. Only blocks that may be reused (BlockDef::cacheable) are kept; a block that set a variable, or was still being computed when the run was cancelled, is not. A session keeps one per connection. Thread-safe.-
std::size_t size() const#
-
bool contains(std::string_view node) const#
-
void clear()#
-
std::size_t size() const#
Run styles#
<paperboat/core/executor.hpp>. A station needn’t know about these: the core picks the
executor for each graph (default_executor()). They are for a station whose runs
fit none of the three, such as an event-driven one or an external solver. Its executor
drives the same Run, so blocks, monitors, the station and the UI work as
always.
-
class Executor#
-
std::unique_ptr<Executor> clock_executor()#
A Signal flow on a clock: every block once per
dt, forduration.
-
std::unique_ptr<Executor> step_executor()#
A Step flow: hats start paths, each path is at one block.
-
std::unique_ptr<Executor> default_executor(const Graph &graph, const RunSettings &settings)#
Steps if the graph has step blocks or stories, else once or clock by
settings.mode.
-
class Run#
A run in progress, as an executor sees it: the graph made, the station, the domain state and the outputs so far.
-
void at_time(double t)#
Sets the run clock and reads the keys held in the UI now.
-
json pass()#
Every signal block once, in order. Returns the monitors’ samples, for
frame.
-
json evaluate(const std::string &id)#
One block of a run that evaluates once: its outputs from the run’s
RunCachewhen nothing it depends on changed (node.statecached, with norunningbefore it; the logs, metrics, monitor states and last frame it sent are sent again), else called (running, thendone) and, if it may be reused, kept for the next run. Returns its samples. What the once executor calls for each block in order, after it has reported every blockqueued.
-
std::optional<std::string> advance()#
Station objects, then the domain state, move on. A message if the domain ends the run.
-
void frame(const json &samples, std::optional<double> progress)#
Sends samples, the scene’s changes and the run’s progress; waits to keep real time, at the speed the UI asked for last (
run.speed): a custom executor that calls it gets speed changes during a run for free.
-
bool cancelled()#
-
void log(std::string_view level, std::string_view text)#
-
void node_state(std::string_view node, std::string_view state)#
-
const RunSettings &settings() const#
A minimal executor:
class TenPasses final : public paperboat::Executor { public: std::string execute(paperboat::Run& run) override { for (int k = 0; k < 10; ++k) { if (run.cancelled()) return "cancelled"; run.at_time(k * 0.5); run.frame(run.pass(), k / 9.0); } return "done"; } };
-
void at_time(double t)#