Files
FluidSimCpp/docs/MECHANICAL_BUILDER_PLAN.md

622 lines
44 KiB
Markdown

# Machine systems roadmap: mechanics, pneumatics, logic and ECU sensors
Planning draft, 2026-11-01. This describes proposed work, not implemented features.
Implementation has started; see [component progress](COMPONENT_IMPLEMENTATION.md)
for completed foundations and the remaining delivery backlog.
## Goal
Build machines from explicit gas, mechanical and signal connections. Engines,
pumps and actuators exchange physical work; sensors measure named locations;
logic and ECUs control declared targets. The workshop should make those paths
easy to connect, inspect and diagnose.
Originally cylinders and piston pumps used one implicit machine-wide crankshaft.
Explicit shaft, flywheel, drive and brake parts are now implemented, with migrated
legacy layouts and targeted instruments. Six basic sensor assemblies and their
physical bindings/live inspector are also implemented. The basic logic runtime
and 3D/Logic/Split editor, sensor-driven ignition/Alpha-N presets and explicit
intake injector attachments are integrated and verified. Stage 4 now also has a
working speed-density preset using actual MAP/IAT signals and calibrated VE.
Advanced graph UX, the stage-4 pneumatic valves and the later physical systems
remain on the delivery backlog.
## Agreed design rules
- Boolean signals are red; Number signals are green. Directed inputs are hollow
rings and outputs filled circles. Physical ports such as gas/pressure remain
bidirectional and use distinct neutral domain symbols.
- Establish typed ports, stable identities and validation before adding parts
that depend on them. Types must exist in the document and runtime, not only UI.
- Use one machine document across 3D Build, Logic and Test. Canvas references,
sensors and instruments do not create duplicate physical machines.
- Sensor attachments belong at named physical locations. Readouts may fan out
to ECUs, logic and instruments. Controllers use connected measurements and
explicit calibration/defaults rather than hidden access to unrelated state.
- Provide simple starting presets with few mandatory connections; expand their
visible optional inputs as features are enabled. Missing and invalid data
have explicit, different behavior.
- Preserve legacy machines through versioned migrations and labeled compatibility
controllers. Keep their operating behavior reviewable before changing models.
- UI work prioritizes consistent appearance, responsive layout and preventing
text/control overlap at the primary 1920x1080 desktop target. Test starts running
in the existing workspace; panels resize/collapse and retain their widths.
## Integrated delivery order
This is the authoritative implementation order. The track sections below detail
their own parts and acceptance targets; their local numbering is not a separate
release schedule.
| Stage | Deliverable | Completion example |
| --- | --- | --- |
| 0 | Shared port descriptors, quantity/reference types, stable keys, validation and migration scaffolding | Every connection path rejects the same incompatible types; existing machines still load. |
| 1 | Explicit shafts, flywheel, drive/load, basic sensor attachments and targeted instruments | Two independent engines; one shaft driving a loaded piston pump. |
| 2 | Logic canvas, manual controls, gates, thresholds, live values and valve/motor command ownership | Sensor -> threshold -> enable switch -> drive, with red/green signal wiring. |
| 3 | Sensor-driven ignition ECU and Alpha-N EFI, crank sensing and ECU connector UI | Carbureted ignition control and minimal EFI both run from explicit sensors; missing crank stops controlled combustion. |
| 4 | MAP/IAT sensors, speed-density ECU, regulator/relief/shutoff valves and pressure-switch preset | Sensor-driven engine and automatic regulated air supply bench. |
| 5 | Gears, clutch, starter; directional valves, linear actuators and loads; stateful logic | Geared pump, clutched load and timed pneumatic actuator circuits. |
| 6 | MAF/sequential ECU options, air motor, rotary compressor, acoustic assemblies and remaining UI refinement | Stored-air motor and richer sensor/actuator examples. |
| Later | Thermal parts, belt detail, ejector, turbine/turbocharger and general linkages | Add only with a defined physical model and acceptance cases. |
Ship small usable slices within each stage. Stage 3 depends on defining sensor
timing and explicit fuel delivery, not merely drawing extra ECU input pins.
## Proposed parts
| Part | Purpose and editable properties | Delivery |
| --- | --- | --- |
| Shaft / crankshaft | Named rotational node; angle, initial RPM, base inertia and friction. Cylinders and pumps attach with individual phase offsets. | First release |
| Flywheel | Adds inertia to its connected shaft; explicit inertia initially, with geometry-derived inertia as a later option. | First release |
| Drive motor | Ideal speed-controlled bench drive or torque-controlled motor; target speed or torque and direction. Report required drive torque and power in speed mode. | First release |
| Brake / load | Applies a constant opposing torque and optional speed-dependent drag; reports absorbed power. | First release |
| Gear pair | Fixed signed speed ratio between two shafts, with an explicit efficiency/loss model. Tooth counts determine the ratio. | Second release |
| Clutch | Connects two shafts through a torque-limited friction coupling; engagement, torque capacity, slip and dissipated power. | Second release |
| Starter | Torque-limited drive with a one-way coupling and hold-to-start input. Initially uses a specified torque curve. | Second release |
| Belt / pulley drive | Same-direction or crossed drive with pulley ratio; an ideal fixed-ratio model first, slip/tension later. | Later |
| Rotary compressor / pump | Continuous shaft load coupled to gas flow; requires a defined displacement or performance-map model. | Later |
Existing cylinders and piston pumps gain mechanical attachment ports. Their
phase is relative to the attached shaft. A shaft can have multiple attachments;
there is no automatic connection because parts happen to be nearby.
For the initial release, one shaft part represents a rigid rotational node.
Its visible length helps placement; it does not introduce torsional flexibility.
Base shaft inertia and attached flywheel inertia are counted once. Separate
shafts rotate independently until connected by a supported coupling.
## Connection and simulation rules
- Distinguish gas ports, control pins and rotational ports by shape, label and
color. Preview compatibility and explain rejected connections before clicking.
- Mechanical attachment lines identify the shaft association. They do not
silently move cylinders or imply a physically supported bent driveshaft.
- Keep shaft angle/speed per shaft. Route cylinder torque, pump torque, losses,
drives and loads to the correct shaft; sample its RPM for each attached ECU.
- Initially require cylinders controlled by one ECU to share a shaft. Diagnose
mixed-shaft assignments until explicit speed-reference selection is added.
- Ideal gears impose a speed/angle relationship. Solve connected rigid groups
with inertia reflected through their ratios; do not use competing independent
RPM updates or stiff penalty torques to approximate a rigid connection.
- Validate contradictory ratios, incompatible prescribed speeds and unsupported
constraint loops. Start with tree-shaped gear networks and reject loops with
actionable diagnostics until a general constraint solver is available.
- Friction and brake torque oppose motion, and must not push a stopped shaft
into reverse. Drive torque can select direction. Check existing cylinder/cam
assumptions before enabling reverse engine operation.
- Track external work, rotational kinetic energy and coupling losses. Clutch
slip dissipates energy; an ideal prescribed-speed drive supplies or absorbs
whatever work is required and reports it.
- Connection changes and initial state changes require Build. Safe torque,
speed-target and engagement tuning can remain available during Test.
## Workshop UI
The [workshop UI rework](WORKSHOP_UI_PLAN.md) specifies the workspace layout,
interaction conventions and user-selected preferences in more detail.
### First release: connecting and understanding the machine
- Searchable parts picker with Gas, Engine, Mechanical and Control categories.
- Connection filters for Gas, Mechanical and Control; fade unrelated links.
- Larger screen-space port targets, hover labels, endpoint highlighting and
candidate cycling where ports overlap. Preserve existing gas connection rules.
- Mechanical overview listing each shaft, its attached parts and its drive/load.
Selecting a row selects and focuses the corresponding assembly in 3D.
- Shaft inspector groups Initial state, Inertia and losses, and Connections.
Show total connected inertia separately from editable base inertia.
- Cylinder/pump inspector shows the named shaft and phase offset, with an action
to select the shaft. Unattached mechanical parts receive a navigable check.
- RPM, torque and power instruments require a named target. Torque readings
identify what is measured, such as cylinder output, motor input or load torque;
a shaft network has no single universal transmitted-torque value.
- Test overlay shows the selected shaft's RPM and operating state. With several
shafts, let the user pin the main readout instead of silently choosing one.
### Second release: coupled machines and editing feedback
- Gear connection preview shows input/output shafts, ratio and rotation direction.
- Clutch control and instruments show engagement, slip RPM and lost power.
- A compact power-path view highlights the selected shaft's connected network.
- Group inspector shows selection count, pivot and mixed property values;
offer only edits applicable to the selected parts.
- Add concise property help with units, physical meaning and Build/Test status.
- Add named saved visibility groups for dense assemblies. Hiding a part only
affects editing visibility, never simulation membership.
Adjustable gas port placement is a separate follow-up. Ports represent physical
openings, so editing them must update connected geometry and preserve validation;
they should not be freely dragged as purely cosmetic connection markers.
## Save files, imports and assemblies
- Introduce a new machine format version with explicit shaft references and
mechanical connections, using stable IDs.
- Upgrade older files to one visible shaft with their existing inertia, losses,
initial speed, drive and load settings. Create drive/load parts as needed and
attach all existing cylinders and pumps with their original phase offsets.
- Preserve existing starter behavior during migration; replace it with an
explicit starter when the starter model is available.
- Retarget legacy shaft instruments to the migrated shaft. Retain the existing
torque metric's meaning and label it explicitly during the transition.
- Engine imports create explicit mechanical parts. Copy/paste and assemblies
remap internal shaft references and retain external attachments as visibly
unresolved; they must never attach to a destination shaft by coincidence.
## Mechanical track scope and acceptance
Before these implementation stages, deliver the typed port foundation described
in the logic section below. Mechanical and pneumatic additions should use that
shared contract from their first implementation.
1. **Explicit shaft foundation:** document/serialization migration, independent
shaft runtime state, cylinder/pump attachment, rendering and selection.
Acceptance: two disconnected engines can run at different speeds; existing
imported machines retain their operating behavior and phase relationships.
2. **Usable mechanical bench:** flywheel, drive motor and brake/load; connection
filters, port picking, shaft inspector and targeted instruments.
Acceptance: assemble and inspect an engine driving a loaded piston pump;
disconnected attachments and fuel/control problems are easy to locate.
3. **Coupled shafts:** fixed gears, clutch and explicit starter, with ratio and
power-path feedback. Acceptance: accelerate a second inertia through a clutch,
observe slip losses, and drive a pump at a different speed through gears.
4. **Broader machines:** belt drives and a rotary compressor/pump after choosing
and validating their physical models; adjustable gas ports and visibility
groups as workshop follow-ups.
Validation should cover legacy migration, assembly ID remapping, independent
shafts, phase continuity, inertia response, gear direction/ratio and reflected
inertia, prescribed-drive work, clutch losses and stop/reversal behavior.
Use focused simulation and builder checks as each stage is implemented.
The first mechanical slice covers the shaft foundation and usable bench above.
Detailed electrical motors,
batteries, gear contact dynamics, shaft flex and belt tension need separate models
and are outside that milestone.
## Pneumatic and fluid-powered expansion
Extend the current compressible-gas system with useful circuits: store compressed
air, regulate it, switch it, and convert its pressure into linear or shaft work.
Existing chambers already serve as finite tanks, and the piston pump can form a
reciprocating compressor with external check valves. Add useful presets and
assemblies for these before introducing redundant part types.
This roadmap initially targets gas. Liquid hydraulics would need a separately
defined fluid model, including compressibility, cavitation and appropriate
boundary treatment, before the same UI could promise hydraulic behavior.
### Proposed fluid parts
| Part | Behavior and properties | Priority |
| --- | --- | --- |
| Adjustable restriction / needle valve | Two-port metering with editable opening and effective flow area; supports reverse flow and choking through the shared gas boundary model. | A: basic circuits |
| Shutoff / solenoid valve | Two-port on/off valve; normally open/closed state, commanded opening and finite actuation time. | A |
| Pressure relief valve | Opens from a protected node to an explicit outlet above a differential-pressure setting; reseat behavior prevents chatter. | A |
| Pressure regulator | Reduces downstream pressure using a bounded inlet restriction with response dynamics; cannot increase pressure or hold a target without supply capacity. Non-relieving initially. | A |
| Pressure switch | Senses a chosen pressure and emits a Boolean signal with separate on/off thresholds; starts/stops a compressor or operates a valve. | A |
| Directional valve | 3/2 first, then 5/2; named supply, work and exhaust ports, explicit internal paths and transition behavior. | B: actuators |
| Pneumatic actuator | Single-acting spring-return first, then double-acting; bore, rod, stroke, moving mass, friction, dead volumes and end stops. | B |
| Linear load / spring | Opposing force, attached mass, spring and damping for an actuator's translational port. | B |
| Quick-exhaust valve | Vents an actuator locally through its own outlet when the supply path depressurizes. | B |
| Air motor | Positive-displacement gas motor with inlet, outlet and shaft port; displacement, leakage and mechanical losses. | C: shaft power |
| Rotary compressor | Shaft-driven gas compression with displacement/map, leakage and losses; load arises from gas work. | C |
| Nozzle / venturi | Converging/diverging pipe profile preset first; a later ejector adds a suction port and a validated entrainment/mixing model. | C |
| Filter / porous restriction | Calibrated pressure loss and optional gas storage; acoustic attenuation requires an additional defined model. | C |
| Silencer / resonator | Pipe/chamber assemblies first: expansion chamber, side branch and Helmholtz-style resonator. Absorptive silencers need an explicit loss model. | C |
| Cooler / heated chamber | Defined wall temperature or thermal mass and gas-wall heat transfer; report heat flow alongside gas state. | Later |
| Turbine / turbocharger | Map-based turbine and compressor on explicit shaft nodes; requires performance data and operating-range handling. | Later |
Priority letters describe the pneumatic track, not a promise to finish it before
the mechanical milestones. Prioritize A alongside the shaft foundation, B next,
and C once independent shafts and component coupling are established.
### Physical behavior and scope
- Valves transfer conserved mass, species and energy through actual ports.
A regulator must not overwrite a chamber pressure to enforce its setpoint.
- Supply and exhaust are visible connections. An unconnected outlet remains
sealed under the current builder rule; warn when a valve needs an exhaust path.
- Regulator and switch inspectors state whether settings are absolute, gauge or
differential pressure. Store physical pressures in SI and define the reference.
- Actuator force uses the pressures on both piston faces and their effective
areas. Each chamber volume follows piston motion, with positive dead volume;
gas work and mechanical work must balance.
- Add translational mechanical ports for actuators and linear loads. An actuator
is distinct from the existing crank-driven piston pump. A general linkage
mechanism can connect translation to rotation in a later milestone.
- Resolve moving valves, actuator stops and small chambers with appropriate
component timesteps. The existing pipe CFL limit alone is insufficient.
- Air motors and compressors exchange torque/work with the attached shaft.
Their models define starting, stall, reversal and off-design behavior rather
than extrapolating efficiency formulas through zero speed.
- Pressure switches and solenoids use typed signal ports. Add a manual switch
and a simple hysteretic controller; define their update order. Keep ECU
assignments intact while extending the control connection system.
### Fluid UI and instruments
- Add Supply/storage, Valves, Actuators, Rotating machines and Thermal/acoustic
subcategories, plus searchable saved circuit assemblies.
- Label valve ports P (supply), A/B (work), and R/S (exhaust), with tooltips in
plain language. Show connected paths and moving valve state during Test.
- Preview actuator stroke limits and current rod position in 3D. Its inspector
shows chamber pressures, net force, position and velocity.
- Add differential pressure, actuator force/travel/velocity, valve state and
switch output instruments. Flow probes must identify the measured port and
direction; show mass flow by default and label volumetric reference conditions.
- Highlight a selected supply path and its exhaust route; distinguish blocked
flow from disconnected parts. Add checks for missing exhausts, absent supply,
unattached mechanical loads and incompatible signal connections.
- Show regulator target beside actual pressure, tank stored gas state, and
absorbed/delivered shaft power. Keep invalid or out-of-range readings explicit.
### Playable circuit milestones
1. **Air supply bench:** existing piston pump + check valves + tank, pressure
switch, relief valve and regulator. Charge a finite tank, cycle the drive
between pressure thresholds and feed a restricted downstream branch.
2. **Actuator bench:** regulated supply + 3/2 valve + spring-return actuator;
follow with a 5/2 valve and double-acting actuator driving a linear load.
3. **Stored-air motor:** charge the tank, disconnect the compressor drive, and
run an air motor connected to a flywheel and brake until pressure falls.
4. **Acoustic bench:** interchangeable resonator/silencer assemblies with inlet
and outlet pressure traces and source captures. Compare pressure loss and
acoustic response at consistent operating points.
5. **Boost system:** shaft compressor first, then a map-based turbine/compressor
assembly with intake and exhaust connections once those models are ready.
Acceptance checks should include sealed-system mass/energy accounting, choking
and reverse flow, relief opening/reseating, regulator response and insufficient
supply, switch hysteresis, valve port states, actuator force/work and end stops,
and motor/compressor gas-work-to-shaft-work balance. These belong to the future
implementation stages; this document adds planning only.
## Typed signals and logic nodes
### Confirmed current implementation
The shared typed-port foundation, physical sensor attachments and a general
signal-graph runtime are now implemented. `MachineDocument::logic` stores nodes
and named typed wires separately from physical connections. Runtime nodes include
controls, gates, thresholds, numeric operations, sensor/command references,
readouts and explicit delays. See [component progress](COMPONENT_IMPLEMENTATION.md)
for the verified scope. The basic Logic canvas, shared 3D/Logic/split workspace,
typed wire editing, interactive controls and graph inspectors are now integrated.
Advanced graph UX, operator panels and the later component stages remain planned.
`MachineConnectionKind::Control` remains legacy ECU assignment. Those blue wires
assign a controller; the new Boolean/Number graph does not reinterpret them.
### Shared port contract: implement first
- Give each port an explicit domain: Gas, Rotational, Translational, Boolean,
Number, or the existing ECU assignment domain during migration. Domain and
signal direction must be data, not inferred from a part kind or rendered color.
- Define ports through a shared descriptor with a stable key, display name,
domain, input/output direction for signals, cardinality, and typed defaults.
Number ports also declare quantity/unit, supported range and any required
pressure reference. Physical ports retain their domain-specific behavior.
- Use stable serialized port keys, versioned migration for old numeric indices,
and stable part/node kind keys. Adding a port or reordering an enum must not
silently reconnect an existing saved machine to a different function.
- Store signal values as Boolean or finite numeric values with explicit validity.
Do not encode Booleans as arbitrary floating-point values or use NaN as truth.
- Only connect matching signal types from output to input. One output may feed
multiple inputs; one input accepts one driver. No automatic Bool/Number cast.
Explicit conversion nodes handle thresholding and Boolean-to-number selection.
- For numbers, also validate quantity compatibility. Pressure, RPM and opening
fraction must not connect interchangeably because all are numeric. Store SI
values; present convenient units, and require explicit scaling/mapping where
a quantity changes. Enforce arithmetic quantity rules and configure constants
with a quantity. Infer polymorphic node ports consistently when compiling.
- Required unwired inputs produce a navigable check and block Test; optional
inputs show a declared default in the UI. Invalid sensor/math output remains
visibly invalid and follows a documented per-consumer fallback; actuator
command inputs default to a declared inactive state, not a previous command.
- Use the same descriptors and compatibility checks for connection previews,
actual edits, loading, validation, compilation and runtime binding. Keep
signal links out of gas connectivity walks, pipe snapping and fuel searches.
- Preserve existing ECU assignments as their own relation; migrate them through
explicit adapters or dedicated ports when individual ECU commands are exposed.
Never reinterpret old ECU links as Boolean or Number links.
### Color and node editing
- **Boolean ports and wires: red. Number ports and wires: green.** These hues
identify the type consistently in 3D, node view, picker, inspector and legend.
- **Inputs are hollow rings; outputs are filled circles.** Apply this convention
consistently to directed ports on every node and part in both 3D and Logic
views. Shape communicates direction; red/green communicates Boolean/Number
type. Labels and hover text identify both type and direction without color.
- Physical ports without an input/output direction, such as pressure/gas
connections, remain bidirectional and use a distinct neutral physical connector
symbol. Their appearance must not imply one-way flow. A pressure sensor's gas
connection is bidirectional; its numeric measurement output is a filled green
circle. Rotational and translational attachments likewise use their physical
domain symbol rather than suggesting a fixed power-flow direction.
- Bright/dim styling and true/false text show Boolean state while retaining the
red type color and input-ring/output-circle silhouette. Number hover labels
show value, units and validity.
- Replace green as the gas identity with neutral gas markers. Connection validity
uses a separate checkmark or cross/message so success/error feedback cannot be
mistaken for a signal type or input/output direction.
- Add a **Logic** view: a pannable, zoomable node canvas for the same machine.
Logic nodes have saved canvas positions; sensors and actuators appear as
references to their existing physical parts, not duplicated simulated parts.
- Inputs appear on the left, outputs on the right. Drag to connect, branch from
outputs, reroute wires, disconnect and undo. Filter compatible nodes when
dragging from a pin. Label incompatible targets with a rejection reason.
- Keep 3D part placement separate from canvas layout. Selecting a sensor or
actuator reference can focus its physical part, and vice versa. Logic nodes
need no gas storage or physical 3D housing to function.
- Add live pin values, Boolean state and compact number traces during Test.
Pause freezes logic with physics; stepping advances both. A control panel can
pin buttons, switches, sliders and readouts for use without opening the graph.
### Initial node library
| Group | Nodes | Defined behavior |
| --- | --- | --- |
| Manual Boolean controls | Toggle switch, momentary button, Boolean constant | Switch retains its state; button is true while held. Release on focus loss, view close or Test stop. |
| Manual numeric controls | Number constant, slider, numeric input | Quantity, unit, range and initial value are explicit; user edits arrive at simulation boundaries. |
| Boolean gates | AND, OR, NOT, XOR, NAND, NOR | AND/OR start with two inputs and can add inputs; named, deterministic truth tables. |
| Threshold and comparison | Greater than, less than, equal within tolerance, range/window, hysteresis threshold | Number inputs produce Boolean outputs; comparisons use compatible quantities. Hysteresis has separate on/off thresholds and an initial state. |
| Numeric arithmetic | Add, subtract, multiply, divide, min, max, absolute value, clamp | Compatible quantity rules; division by zero produces an invalid value and a diagnostic. |
| Mapping and selection | Gain/offset, map range, Boolean-controlled number selector, Bool-to-number | Selector chooses between two compatible numbers; Bool-to-number emits configured false/true values. Mapping declares quantities and clamping behavior. |
| State and timing | Set/reset latch, rising/falling edge, on-delay, off-delay, pulse timer | Reset wins if set and reset coincide. Timers use simulation time. Edge nodes initialize from their input without emitting a false startup edge. |
| Number memory | One-tick delay, sample-and-hold | Explicit initial value; held quantities remain typed. Delay separates feedback across ticks. |
| Sensors | Pressure, differential pressure, temperature, mass flow, shaft RPM, actuator position, limit switch | Attach to a physical target/port without changing its gas volume. Supply validity and quantity metadata. |
| Outputs and commands | Valve enable, valve opening, motor enable/target, clutch engagement, starter command | Each target exposes its supported type, units/range and fallback. Explicit manual, signal or existing-controller ownership prevents competing commands. |
| Displays | Boolean lamp, numeric readout, trace | Observe a typed signal without changing its evaluation. |
Starter nodes are switches, buttons, constants/sliders, AND/OR/NOT, thresholds
with hysteresis, number selection, pressure/RPM sensors, command inputs and
displays. Add the rest after the core graph and timing semantics are established.
### Evaluation, feedback and persistence
- Initially evaluate the compiled signal graph once per audio sample, using the
configured sample period (currently typically 1/44100 s). Sample physical
sensors at the boundary, evaluate the graph, latch actuator commands, then
advance physics. Fluid CFL substeps hold those commands. Slower playback does
not change control time relative to simulated time.
- Topologically evaluate combinational nodes. Treat memory/delay outputs as
stored state, then commit their next state simultaneously after evaluation.
Reject combinational cycles with a highlighted cycle path; explicit state
permits feedback. Physical sensor/actuator feedback crosses a physics step.
- Consume manual-input events in order at a simulation boundary. Preserve a
press/release pair between boundaries for one tick; edge outputs last one
tick, and delayed output validity/initialization is defined explicitly.
- Save graph topology, port keys, node parameters, canvas layout and configured
initial states. Each fresh Test resets to those initial states; transient
button presses, timer state and latch state do not silently become defaults.
- Topology edits require Build. Allow validated constants, thresholds and manual
controls during Test at synchronized boundaries. Copy/paste and assemblies
remap internal references and expose unresolved external sensor/target bindings.
### Foundation acceptance and delivery order
1. **Typed ports:** shared descriptors, typed links, stable serialization keys,
validation and legacy migration. Confirm all declared domains are represented
before mechanical and pneumatic nodes depend on them.
2. **Basic logic:** red Boolean and green Number pins/wires, node canvas, manual
controls, gates, thresholds, sensors, commands and live values.
3. **Stateful control:** timers, latch, edge detection, memory and numeric mapping,
followed by reusable control assemblies and pinned control panels.
Required implementation checks: Bool-to-Bool and Number-to-compatible-Number
connections succeed; Bool/Number mismatches, quantity mismatches, reversed
direction and multiple drivers fail consistently in preview, load and compile.
Also verify fan-out, defaults, unknown port keys, save/load and copy/paste,
ECU migration, invalid math, graph ordering, cycle rejection, delayed feedback,
pause/step behavior and momentary-button release. Core runtime checks now cover
types, wiring validation, evaluation, persistence, faults, delayed feedback and
button-event release/reset. Canvas interactions, live inspector edits, focus/view-
close release, shared selection, pause/step and split layouts now have interaction
and rendered checks. Pinned operator panels and the remaining UI refinements still
need their own acceptance work.
First demonstration: pressure sensor -> hysteresis threshold -> AND with a
manual enable switch -> compressor drive enable. Show tank pressure as a green
Number wire and compressor demand as a red Boolean wire. Follow with a button
and timer driving a pneumatic valve, and a slider commanding a proportional
valve through an explicit range mapping.
## Sensor-driven ECUs
### Current behavior and intended boundary
The current `Ecu::step` receives pedal and the implicit shaft RPM directly.
`Ecu::fuel_for_air` doses fuel from cylinder air mass, and cylinder code supplies
the timing context. There are no general wired MAP, TPS, crank or IAT inputs.
Existing AFR/lambda instruments are ideal transported fuel-origin measurements,
not oxygen-sensor or heater models.
Retain a labeled **Legacy ideal ECU** for migrated machines until equivalent
sensor-driven examples are established. New ECU presets use explicit sensor
inputs, controller calibration and declared actuator targets. Do not disguise
direct cylinder-air-mass access as speed-density or MAF fuel estimation.
### ECU family and minimum connections
Use one shared ECU runtime with selectable strategy/capability presets. Different
picker entries can provide the desired ECU types without duplicating validation,
sensor binding and fault handling. Keep calibration separate from measurements.
| ECU preset | Required measurements in its basic mode | Optional features and their added requirements |
| --- | --- | --- |
| Ignition / carburetor | Crank speed and crank position | MAP or TPS for load-based spark; TPS/driver demand and a commanded throttle for electronic idle. Fuel remains physically supplied by the carburetor. |
| Alpha-N EFI | Crank speed/position and throttle position (TPS) | IAT, engine temperature and barometric corrections; lambda trim; cam phase for sequential operation. Basic mode uses a calibrated RPM/TPS fuel table. |
| Speed-density EFI | Crank speed/position, manifold absolute pressure (MAP), intake air temperature (IAT) | TPS for acceleration enrichment/overrun logic, temperature warm-up correction, barometric correction, lambda trim and cam phase. Requires displacement and volumetric-efficiency calibration. |
| MAF EFI | Crank speed/position and fresh-air mass flow | TPS, MAP, temperature corrections, lambda trim and cam phase. Requires a stated manifold-filling/charge-allocation model; inlet flow is not automatically trapped cylinder charge. |
| Advanced / custom | Required set of the explicitly selected base strategy | Configure supported feature modules; each declares added sensors, targets and fallback behavior. Initially no arbitrary scripting. |
All presets also need declared controlled cylinders/ignition targets; EFI needs
explicit enabled fuel-delivery targets. These are configuration/actuator bindings,
not extra sensor inputs. Engine geometry, firing order, trigger offset, fuel
properties and maps are calibration, not wires.
Basic crank-only modes use supported batch injection and wasted-spark or
distributor timing. Four-stroke sequential injection/individual-cycle ignition
requires cam phase or another explicit cycle-synchronization source. Do not
silently read the simulated cylinder's 720-degree phase to remove that requirement.
Temperature, lambda, TPS and other optional inputs are not universally mandatory.
Features activate their requirements: no TPS means no TPS-based enrichment;
no lambda means open-loop fueling. Fixed reference values are editable and labeled
where a preset supports them. Required base-strategy inputs cannot silently fall
back to hidden physics values. A manual throttle can be used without driver-demand
or throttle-actuation wires; electronic throttle adds its own demand/feedback needs.
The strategy split follows the Speeduino manual's MAP/speed-density and
TPS/Alpha-N distinction. MegaSquirt documentation provides trigger/cam examples
for batch/wasted-spark versus sequential operation. The exact minimum sets above
are proposed simulation presets, not a claim about a particular hardware ECU.
### Sensor placement and representation
| Sensor | Attachment / physical representation | Outputs and scope |
| --- | --- | --- |
| Crank position/speed | Attach to a named shaft, with visible pickup marker and reference offset | Number speed and crank angle; explicit synchronized/valid status. One sensor assembly supplies both. |
| Cam phase | Attach to an explicit cam drive when available; initially a configured phase pickup associated with the engine shaft | Number cycle phase and Boolean synchronized status. The initial pickup is an ideal cycle-reference abstraction, not simulated cam gearing. |
| MAP / pressure | Tap a pipe at normalized arclength or attach to a chamber/plenum | Number absolute pressure. Select the manifold downstream of the throttle; support per-runner or configured combined readings for individual throttles. |
| Differential pressure | Reference two named gas taps | Number pressure difference with labeled positive/reference sides. |
| IAT / gas temperature | Pipe tap or chamber gas attachment | Number temperature; ideal gas reading first, optional lag later. |
| TPS | Attach to throttle/carburetor mechanism | Number actual opening fraction, distinct from commanded opening or pedal demand. |
| Driver demand / pedal | Standalone manual/control part | Number demand fraction; optional for manual-throttle engines. |
| MAF | Pipe tap for an ideal mass-flow sensor; later an inline body if its restriction/storage is modeled | Number signed fresh-air mass flow, with declared reverse-flow behavior. Preserve total-flow instruments as a separate quantity. |
| Lambda | Exhaust pipe/collector attachment | Number lambda plus validity. Start with a labeled ideal mixture tracer; defer wideband oxygen chemistry, heater and response modeling. Closed-loop use requires explicit opt-in to that approximation. |
| Engine/head temperature | Attach to a cylinder/head thermal node when implemented | Number material temperature. Until then use a declared fixed calibration input; cylinder gas temperature is not coolant/head temperature. |
| Barometric pressure | Standalone ambient sensor or tap of an explicitly selected environment boundary | Number absolute pressure; never substitute manifold pressure during running. |
| Fuel pressure | Attach to a fuel rail/circuit once one exists | Number pressure; until then injector pressure is a declared calibration, not a pretend sensor reading. |
| Knock, oil pressure, battery voltage | Future dedicated physical models | Expose only after their state/model exists; do not synthesize plausible readings from unrelated gas variables. |
Sensors are saved entities with stable IDs and host references; their Logic view
nodes refer to those same entities. Store pipe locations by arclength fraction,
not mesh cell index, and chamber/shaft targets by stable identity. Placement must
survive mesh rebuilds, transforms and valid geometry edits. Invalid/deleted hosts
leave visible unresolved bindings rather than silently retargeting another part.
Use **Add sensor** on the selected part or pipe location, then offer only supported
measurements. Attached taps do not consume a gas connection, create storage or
alter flow. A standalone hose-connected pressure sensor has a bidirectional gas
port and real hose/dead volume if included; its Number output is still a filled
green circle. Flow sensors that add a body must explicitly add its losses/volume.
Each sensor exposes measured quantity, units, location, sample time, validity and
optional response/filter settings. Ideal sensors come first; lag, noise, range
limits and fault injection are later options with deterministic initialization.
Existing probes may share sampling code; ECU inputs must not depend on the
instrument UI's eight-channel limit or its lower-rate recording samples.
### Numeric timing inputs and synchronization
ECU measurement inputs are Number rings, including speed, crank angle, MAP,
TPS and temperature. Crank speed and position are separate typed quantities,
not a single overloaded number. Optional Boolean sync/run/kill inputs are red.
An ideal crank pickup outputs phase in a declared 360-degree reference frame and
speed from the same timestamp. Cam reference resolves the four-stroke cycle.
Keep unwrapped rotation/crossing information in the timing subsystem so wraparound
or a crossing within one simulation step cannot lose an ignition/injection event.
Validate coherent sensor provenance and phase offsets against controlled shafts.
A constant RPM or an unrelated shaft sensor is not sufficient timing authority.
The declared ideal timing channel may supply synchronization metadata alongside
the numeric reading; it is not an invisible additional physics-state lookup.
Raw Hall/VR tooth waveforms and missing-tooth decoders are a later fidelity mode.
They need timestamped edge delivery and a decoder that outputs these same typed
measurements; sampling a Boolean once per audio sample must not be assumed to
capture every tooth at high speed. General logic may process speed and angle,
but transformations used for timing must preserve or explicitly invalidate the
phase/time reference. Ordinary stale or incoherent values cause a visible fault.
### Actuation and fuel estimation
- EFI computes fuel demand from the selected sensor strategy and calibration.
Account explicitly for speed-density charge estimates, Alpha-N table meaning,
or MAF manifold filling before assigning fuel to cylinders.
- Initially allow labeled per-cylinder ideal injector targets with explicit fuel
mass commands and delivery timing. Fuel mass/energy enters through that modeled
injection boundary; do not call the old `fuel_for_air` path behind the new ECU.
Separate injector/rail parts can replace that abstraction later.
- Expose per-cylinder fuel dose, spark advance and enable/cut commands with clear
units and scheduling semantics. Numeric advance is an angle before TDC, not an
arbitrary instantaneous spark pulse. Cylinder phase offsets remain calibrated
mechanical relationships used by the timing scheduler.
- ECU outputs and standalone logic must not simultaneously drive an actuator
input. Use an explicit selector/command owner. Multiple sensor consumers are
allowed. Each ECU initially controls cylinders on one crankshaft.
- Loss of required crank synchronization cuts its controlled fuel and spark;
missing optional lambda disables trim. Define preset-specific responses to MAP,
IAT, TPS and MAF faults. Never automatically switch fuel strategy unless an
explicit configured fallback has the required sensors and calibration.
### ECU connector UI and diagnostics
- Show Required, Connected and Optional input groups, with expandable Timing,
Air/load, Temperatures, Mixture and Auxiliary sections. Keep every connected
pin visible; show more optional pins on demand to avoid a wall of connectors.
- Every input displays required/optional status, quantity/unit, current value,
source sensor and any active fallback. Feature selection updates requirements
immediately; hiding a pin does not disconnect it or disable its validation.
- Add an ECU setup checklist: choose preset, assign cylinders/shaft, place required
sensors, connect measurements, assign actuators, verify timing and enable Test.
Offer sensor creation at a selected physical location; never guess a plenum.
- Highlight a sensor's physical marker and its wire when selecting an ECU input.
Show named ports and connection lists for dense ECU layouts; support reroutes
and saved harness groups without merging distinct signals into an untyped bus.
- Diagnose missing input, invalid measurement, synchronization loss, wrong shaft,
incorrect measurement kind/location, target conflicts and uncalibrated maps.
A valid zero RPM while stopped is not a missing sensor or a sensor failure.
- Provide compact status: stopped/cranking/running, synchronized, fueling strategy,
open/closed-loop mixture, active cuts and fallback reason. Retain ring/filled
circle direction shapes and red Boolean/green Number colors throughout.
### Migration and acceptance
Legacy imports initially retain Legacy ideal ECU behavior. Offer a deliberate
**Convert to sensor ECU** workflow that creates/reuses named shaft sensors and
selected TPS/MAP/IAT attachments, preserves geometry, and reports calibration that
cannot be converted. Do not promise an existing ideal-air-mass fuel calibration
will produce equivalent behavior from a newly invented VE or Alpha-N table.
Demonstrations: minimal crank-driven ignition with carburetor; Alpha-N with crank
and TPS; speed-density with crank, MAP and IAT; optional lambda correction using
the declared ideal tracer; independent ECUs for two shafts. Add sequential and
MAF examples only after their prerequisites are complete.
Acceptance includes required/optional input matrices, sensor positioning after
mesh/geometry changes, assembly remapping and host deletion, zero-RPM startup,
phase wrap and event crossings, cam loss, wrong-shaft rejection, stale input and
fault recovery, deterministic pause/step, explicit fuel-mass accounting, actuator
ownership and optional-feature degradation. Compare controller estimates against
physical state diagnostically without feeding that ground truth back secretly.
Planning references:
- [Speeduino overview: supported strategies and trigger inputs](https://wiki.speeduino.com/en/Overview)
- [Speeduino tuning: MAP and air-density/load estimation](https://wiki.speeduino.com/en/tuning/Tuning)
- [MegaSquirt MS3 hardware guide: crank/cam triggering examples](https://www.msextra.com/doc/pdf/MS3XV30_Hardware-1.4.pdf)