Skip to main content

sim_fmi/
api.rs

1//! The FMI 2.0 Co-Simulation C functions, and the instance both FMI versions drive (`api3` has the FMI 3.0 ones).
2//! The type definitions follow the FMI 2.0 headers (fmi2TypesPlatform.h, fmi2FunctionTypes.h; Copyright Modelica
3//! Association Project "FMI", BSD-2-Clause licence), written out in Rust.
4//!
5//! Supported: instantiation, setup, initialisation, `fmi2DoStep`, get and set of Real, Integer (there are none),
6//! Boolean and String variables, reset, terminate, FMU state get, set, free and (de)serialization, directional
7//! derivatives. The rest (input derivatives, asynchronous steps, status queries) return `fmi2Error`; the model
8//! description says so. A panic inside the simulation returns `fmi2Fatal` instead of taking the importing tool down.
9//!
10//! An FMU state is what the importer set, the triggers as the last step saw them, and a snapshot of the simulation
11//! (`Sim::snapshot`) with its outputs. Setting it builds a fresh simulation from the parameters and restores the snapshot
12//! into it, which takes as long as building the machine, however long the simulation ran. Serialized, the snapshot is
13//! written as bytes (`postcard`, behind a header with the format and the FMU's version), so a state from
14//! `fmi2DeSerializeFMUstate` is set as fast. Either gives bit for bit the simulation that was saved (tested). A state of
15//! another format or version of the FMU is refused by name; one that cannot be set (its config file gone, say) leaves
16//! the instance as it was.
17//!
18//! Log categories (`LOG_CATEGORIES`): `logEvents` (the commands the trigger inputs gave, states set) is on when the
19//! instance was made with logging on; `logStatusWarning` and `logStatusError` are on from the start; `SetDebugLogging`
20//! switches them, `logAll` or no category naming all.
21//! The directional derivative of an output with respect to an input is exactly zero at a communication point: the
22//! outputs are the signals at the end of the last step, and a new input acts on them only through the next step
23//! (the model description says `dependencies=""`).
24
25#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
26
27use crate::api3::fmi3LogMessageCallback;
28use crate::{Kind, LOG_CATEGORIES, Model, texts};
29use sim_components::{Command, DriveMode, Sim, Snapshot, StopCategory, load_config};
30use sim_core::Translations;
31use std::ffi::{CStr, CString, c_char, c_int, c_void};
32use std::panic::{AssertUnwindSafe, catch_unwind};
33use std::path::{Path, PathBuf};
34
35pub type fmi2Component = *mut c_void;
36pub type fmi2ComponentEnvironment = *mut c_void;
37pub type fmi2FMUstate = *mut c_void;
38pub type fmi2ValueReference = u32;
39pub type fmi2Real = f64;
40pub type fmi2Integer = c_int;
41pub type fmi2Boolean = c_int;
42pub type fmi2String = *const c_char;
43pub type fmi2Byte = c_char;
44pub type fmi2Status = c_int;
45
46pub const fmi2OK: fmi2Status = 0;
47pub const fmi2Warning: fmi2Status = 1;
48pub const fmi2Discard: fmi2Status = 2;
49pub const fmi2Error: fmi2Status = 3;
50pub const fmi2Fatal: fmi2Status = 4;
51/// `fmi2Type`: the one this FMU supports.
52pub const fmi2CoSimulation: c_int = 1;
53
54pub type fmi2CallbackLogger =
55    unsafe extern "C" fn(fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
56
57#[repr(C)]
58pub struct fmi2CallbackFunctions {
59    pub logger: Option<fmi2CallbackLogger>,
60    pub allocateMemory: Option<unsafe extern "C" fn(usize, usize) -> *mut c_void>,
61    pub freeMemory: Option<unsafe extern "C" fn(*mut c_void)>,
62    pub stepFinished: Option<unsafe extern "C" fn(fmi2ComponentEnvironment, fmi2Status)>,
63    pub componentEnvironment: fmi2ComponentEnvironment,
64}
65
66/// The state of an instance; `Stepping` is FMI 3.0's Step Mode.
67#[derive(Debug, Clone, Copy, PartialEq)]
68pub(crate) enum Mode {
69    Instantiated,
70    Initialising,
71    Stepping,
72    Terminated,
73}
74
75/// A value the importer has set.
76#[derive(Debug, Clone, PartialEq)]
77pub(crate) enum Value {
78    Real(f64),
79    Bool(bool),
80    Text(String),
81}
82
83/// A refusal: a translation key and its argument.
84pub(crate) type Fail = (&'static str, String);
85
86/// The logger of the FMI version the instance was made by. Status codes are the same numbers in both versions.
87#[derive(Clone, Copy)]
88pub(crate) enum Logger {
89    Fmi2(Option<fmi2CallbackLogger>),
90    Fmi3(Option<fmi3LogMessageCallback>),
91}
92
93/// What one communication step gives the simulation.
94struct Applied {
95    steps: u32,
96    enable: bool,
97    /// How `enable` false stops the drives.
98    category: StopCategory,
99    /// The commands the triggers gave at its start: `StartCycle`, `Stop`, `MoveTo`, and `Trajectory` with the path as
100    /// it was planned then.
101    commands: Vec<Command>,
102    /// Per axis, the setpoint input if the importer has set it.
103    setpoints: Vec<Option<f64>>,
104    /// Per motor, the mode its inputs ask for (`command.mode`, `command.torque`, `command.velocity`).
105    modes: Vec<DriveMode>,
106}
107
108/// The places in `Instance::logging` (and in `LOG_CATEGORIES`).
109const EVENTS: usize = 0;
110const WARNINGS: usize = 1;
111const ERRORS: usize = 2;
112
113/// An FMU state: what the importer set, the triggers as the last step saw them, and in step mode the simulation's
114/// snapshot with its outputs.
115#[derive(Clone)]
116pub struct FmuState {
117    guid: String,
118    mode: Mode,
119    start_time: f64,
120    set: Vec<Option<Value>>,
121    latched: [bool; 3],
122    snapshot: Option<(Snapshot, Vec<f64>)>,
123}
124
125pub struct Instance {
126    name: CString,
127    logger: Logger,
128    environment: *mut c_void,
129    tr: Translations,
130    pub(crate) model: Model,
131    /// Per variable, what the importer set; none: the start value.
132    set: Vec<Option<Value>>,
133    mode: Mode,
134    start_time: f64,
135    /// Built from the parameters when initialisation needs it, and dropped when a parameter changes before that.
136    sim: Option<Sim>,
137    sample: Vec<f64>,
138    /// What `fmi2GetString` handed out, valid until its next call.
139    strings: Vec<CString>,
140    /// The triggers `command.cycle`, `command.move`, `command.run_path` as the last communication step saw them.
141    latched: [bool; 3],
142    /// Per log category (`EVENTS`, `WARNINGS`, `ERRORS`): whether its messages go to the logger.
143    logging: [bool; 3],
144}
145
146pub(crate) fn c_text(text: &str) -> CString {
147    CString::new(text.replace('\0', "")).unwrap_or_default()
148}
149
150fn log(logger: Logger, environment: *mut c_void, name: &CStr, status: fmi2Status, category: usize, message: &str) {
151    let category = c_text(LOG_CATEGORIES[category].0);
152    match logger {
153        // FMI 2.0's message is a printf format: a per cent sign in the text is doubled, so that it is no format, and
154        // a logger that prints the format as it is (fmpy's Python callbacks) still shows the text.
155        Logger::Fmi2(Some(logger)) => unsafe {
156            let format = c_text(&message.replace('%', "%%"));
157            logger(environment, name.as_ptr(), status, category.as_ptr(), format.as_ptr())
158        },
159        Logger::Fmi3(Some(logger)) => unsafe {
160            let message = c_text(message);
161            logger(environment, status, category.as_ptr(), message.as_ptr())
162        },
163        _ => {}
164    }
165}
166
167/// The resources folder from its URI (`file:///C:/dir/resources`, `file:/dir`, or a plain path).
168fn resource_dir(uri: &str) -> PathBuf {
169    let path = uri.strip_prefix("file://").or_else(|| uri.strip_prefix("file:")).unwrap_or(uri);
170    let path = path.strip_prefix("localhost").unwrap_or(path);
171    let mut bytes = Vec::new();
172    let raw = path.as_bytes();
173    let mut i = 0;
174    while i < raw.len() {
175        let hex = |k: usize| raw.get(k).and_then(|c| (*c as char).to_digit(16));
176        match (raw[i], hex(i + 1), hex(i + 2)) {
177            (b'%', Some(high), Some(low)) => {
178                bytes.push((high * 16 + low) as u8);
179                i += 3;
180            }
181            (c, _, _) => {
182                bytes.push(c);
183                i += 1;
184            }
185        }
186    }
187    let path = String::from_utf8_lossy(&bytes).into_owned();
188    // `/C:/dir` is a Windows path with the slash of the URI in front.
189    let windows = cfg!(windows) && path.starts_with('/') && path.as_bytes().get(2) == Some(&b':');
190    PathBuf::from(if windows { &path[1..] } else { &path })
191}
192
193/// # Safety
194/// The pointer is null or points to a NUL-terminated string.
195pub(crate) unsafe fn text<'a>(p: *const c_char) -> &'a str {
196    if p.is_null() { "" } else { unsafe { CStr::from_ptr(p) }.to_str().unwrap_or("") }
197}
198
199/// `n` values at `p`; refused when `p` is null and `n` is not 0.
200///
201/// # Safety
202/// The pointer is null or points to `n` values, or `n` is 0.
203pub(crate) unsafe fn slice<'a, T>(p: *const T, n: usize) -> Result<&'a [T], Fail> {
204    match (n, p.is_null()) {
205        (0, _) => Ok(&[]),
206        (_, true) => Err(("fmi-error-null", n.to_string())),
207        _ => Ok(unsafe { std::slice::from_raw_parts(p, n) }),
208    }
209}
210
211/// # Safety
212/// As `slice`, writable.
213pub(crate) unsafe fn slice_mut<'a, T>(p: *mut T, n: usize) -> Result<&'a mut [T], Fail> {
214    match (n, p.is_null()) {
215        (0, _) => Ok(&mut []),
216        (_, true) => Err(("fmi-error-null", n.to_string())),
217        _ => Ok(unsafe { std::slice::from_raw_parts_mut(p, n) }),
218    }
219}
220
221/// The outputs: every signal, the time on the importer's clock, which starts at its start time.
222fn sample_of(sim: &Sim, start_time: f64) -> Vec<f64> {
223    let mut out = Vec::new();
224    sim.sample(&mut out);
225    out[0] += start_time;
226    out
227}
228
229/// Gives the simulation one communication step's inputs and runs its base steps; the keys of the commands the
230/// controller refused.
231fn apply(sim: &mut Sim, applied: &Applied) -> Vec<&'static str> {
232    let mut refused = Vec::new();
233    // Category 1 runs down with the drives on and ends with them off; category 2 holds with them on. Each is given
234    // once: not again while its stop runs, nor to a machine that stands.
235    let stop = match applied.category {
236        StopCategory::Zero => true,
237        StopCategory::One => !sim.control.reacting(),
238        StopCategory::Two => sim.control.busy() && !sim.control.halting(),
239    };
240    let command = if applied.enable { Command::Enable } else { Command::Halt(applied.category) };
241    if applied.enable != sim.control.enabled()
242        && (applied.enable || stop)
243        && let Err(e) = sim.command(command)
244    {
245        refused.push(e.key);
246    }
247    // The modes first: a plan command is refused while a drive is out of position mode.
248    for (k, mode) in applied.modes.iter().enumerate() {
249        if sim.control.enabled()
250            && *mode != sim.control.drives[k].mode()
251            && let Err(e) = sim.set_drive_mode(k, *mode)
252        {
253            refused.push(e.key);
254        }
255    }
256    for command in &applied.commands {
257        if let Err(e) = sim.command(command.clone()) {
258            refused.push(e.key);
259        }
260    }
261    if sim.control.enabled() {
262        // An axis the importer has not set stays at the setpoint the controller follows.
263        let mut target = sim.control.external_setpoint().to_vec();
264        for (t, s) in target.iter_mut().zip(&applied.setpoints) {
265            if let Some(s) = s {
266                *t = *s;
267            }
268        }
269        if target != sim.control.external_setpoint()
270            && let Err(e) = sim.command(Command::Setpoint(target))
271        {
272            refused.push(e.key);
273        }
274    }
275    for _ in 0..applied.steps {
276        sim.step();
277    }
278    refused
279}
280
281impl Instance {
282    pub(crate) fn fail(&self, status: fmi2Status, (key, arg): Fail) -> fmi2Status {
283        self.note(ERRORS, status, &self.tr.tr_arg(key, &arg));
284        status
285    }
286
287    /// A message to the logger, if its category is on.
288    fn note(&self, category: usize, status: fmi2Status, message: &str) {
289        if self.logging[category] {
290            log(self.logger, self.environment, &self.name, status, category, message);
291        }
292    }
293
294    /// `fmi2SetDebugLogging`, `fmi3SetDebugLogging`: the categories named switched on or off; none named, all of them.
295    /// An unknown category is refused and changes nothing.
296    pub(crate) fn set_debug_logging(&mut self, on: bool, categories: &[&str]) -> Result<fmi2Status, Fail> {
297        let mut next = if categories.is_empty() { [on; 3] } else { self.logging };
298        for name in categories {
299            match LOG_CATEGORIES.iter().position(|(n, _)| n == name) {
300                Some(i) if i <= ERRORS => next[i] = on,
301                // logAll
302                Some(_) => next = [on; 3],
303                None => return Err(("fmi-error-category", name.to_string())),
304            }
305        }
306        self.logging = next;
307        Ok(fmi2OK)
308    }
309
310    /// `call` without its prefix, which is the version's.
311    pub(crate) fn in_mode(&self, modes: &[Mode], call: &str) -> Result<(), Fail> {
312        let prefix = if matches!(self.logger, Logger::Fmi3(_)) { "fmi3" } else { "fmi2" };
313        if modes.contains(&self.mode) {
314            Ok(())
315        } else {
316            Err(("fmi-error-state", format!("{prefix}{call} ({:?})", self.mode)))
317        }
318    }
319
320    pub(crate) fn variable(&self, vr: u32, type_name: &str) -> Result<usize, Fail> {
321        match self.model.variables.get(vr as usize) {
322            Some(v) if v.type_name() == type_name => Ok(vr as usize),
323            _ => Err(("fmi-error-reference", format!("{type_name} {vr}"))),
324        }
325    }
326
327    fn start(&self, index: usize) -> &str {
328        self.model.variables[index].start.as_deref().unwrap_or("")
329    }
330
331    pub(crate) fn text_value(&self, index: usize) -> String {
332        self.text_in(&self.set, index)
333    }
334
335    fn text_in(&self, set: &[Option<Value>], index: usize) -> String {
336        match &set[index] {
337            Some(Value::Text(t)) => t.clone(),
338            _ => self.start(index).into(),
339        }
340    }
341
342    pub(crate) fn bool_value(&self, index: usize) -> bool {
343        match self.set[index] {
344            Some(Value::Bool(b)) => b,
345            _ => self.start(index) == "true",
346        }
347    }
348
349    fn real_value(&self, index: usize) -> f64 {
350        match self.set[index] {
351            Some(Value::Real(v)) => v,
352            _ => self.start(index).parse().unwrap_or(f64::NAN),
353        }
354    }
355
356    /// The place of the variable of `kind`; 0 (the time) where there is none.
357    fn find(&self, kind: &Kind) -> usize {
358        self.model.variables.iter().position(|v| &v.kind == kind).unwrap_or(0)
359    }
360
361    /// The simulation for the parameters as set, built when it is not there yet.
362    fn ensure_sim(&mut self) -> Result<(), Fail> {
363        if self.sim.is_none() {
364            self.sim = Some(self.build_sim(&self.set)?);
365            self.take_sample();
366        }
367        Ok(())
368    }
369
370    /// The simulation for the parameters in `set`: the config of the FMU or of `config_file`, with the effect switches
371    /// that were set on top. Refused when it would give other variables than the model description has.
372    fn build_sim(&self, set: &[Option<Value>]) -> Result<Sim, Fail> {
373        let find = |kind: Kind| self.find(&kind);
374        let machine = self.text_in(set, find(Kind::Machine));
375        // The FMU's own machine, which may come from a machine file; another one by its id among the registered.
376        let entry = if machine == self.model.entry.id {
377            self.model.entry
378        } else {
379            sim_machines::find(&machine).ok_or(("fmi-error-config", machine.clone()))?
380        };
381        let file = self.text_in(set, find(Kind::ConfigFile));
382        let text = if file.is_empty() {
383            self.model.config_text.clone()
384        } else {
385            std::fs::read_to_string(&file).map_err(|e| ("fmi-error-config", format!("{file}: {e}")))?
386        };
387        let refused = |e: sim_core::ConfigError| ("fmi-error-config", self.tr.tr_arg(e.key(), e.detail()));
388        let mut cfg = load_config(entry, &text).map_err(refused)?;
389        for (index, v) in self.model.variables.iter().enumerate() {
390            if let (Kind::Effect(name), Some(Value::Bool(on))) = (&v.kind, &set[index]) {
391                cfg.set_text(&format!("effects.{name} = {on}")).map_err(refused)?;
392            }
393        }
394        let sim = Sim::new(entry, &cfg).map_err(refused)?;
395        let signals = sim.signal_infos();
396        let expected: Vec<(&str, &str)> = self
397            .model
398            .variables
399            .iter()
400            .filter(|v| matches!(v.kind, Kind::Signal(_)))
401            .map(|v| (v.name.as_str(), v.unit.as_str()))
402            .collect();
403        let found: Vec<(&str, &str)> = signals.iter().map(|s| (s.id.as_str(), s.unit.as_str())).collect();
404        let setpoints = self.model.variables.iter().filter(|v| matches!(v.kind, Kind::Setpoint(_))).count();
405        if expected != found || setpoints != sim.machine.axes().len() {
406            let differing =
407                expected.iter().zip(&found).find(|(a, b)| a != b).map_or(String::new(), |(a, _)| a.0.into());
408            return Err(("fmi-error-variables", differing));
409        }
410        Ok(sim)
411    }
412
413    fn take_sample(&mut self) {
414        if let Some(sim) = &self.sim {
415            self.sample = sample_of(sim, self.start_time);
416        }
417    }
418
419    pub(crate) fn get_real(&mut self, vr: u32) -> Result<f64, Fail> {
420        // FMI allows getting values from initialisation mode on: before it the start time is not yet set up.
421        self.in_mode(&[Mode::Initialising, Mode::Stepping, Mode::Terminated], "Get")?;
422        let index = self.variable(vr, "Real")?;
423        match self.model.variables[index].kind {
424            Kind::Signal(i) => {
425                self.ensure_sim()?;
426                Ok(self.sample[i])
427            }
428            Kind::Setpoint(i) => Ok(match (&self.set[index], &self.sim) {
429                (Some(Value::Real(v)), _) => *v,
430                (_, Some(sim)) => sim.control.external_setpoint()[i],
431                _ => self.start(index).parse().unwrap_or(f64::NAN),
432            }),
433            Kind::Target(_) | Kind::Torque(_) | Kind::Velocity(_) => Ok(self.real_value(index)),
434            _ => unreachable!("only signals, setpoints, targets, torques and speeds are Real"),
435        }
436    }
437
438    pub(crate) fn set_value(&mut self, vr: u32, value: Value) -> Result<(), Fail> {
439        let type_name = match value {
440            Value::Real(_) => "Real",
441            Value::Bool(_) => "Boolean",
442            Value::Text(_) => "String",
443        };
444        let index = self.variable(vr, type_name)?;
445        let v = &self.model.variables[index];
446        match v.causality() {
447            "input" => self.in_mode(&[Mode::Instantiated, Mode::Initialising, Mode::Stepping], "Set")?,
448            "parameter" => {
449                self.in_mode(&[Mode::Instantiated, Mode::Initialising], "Set")?;
450                self.sim = None;
451            }
452            _ => return Err(("fmi-error-state", format!("Set {}", v.name))),
453        }
454        self.set[index] = Some(value);
455        Ok(())
456    }
457
458    /// `fmi2SetupExperiment`, and the experiment part of `fmi3EnterInitializationMode`.
459    pub(crate) fn setup(
460        &mut self,
461        tolerance: Option<f64>,
462        start_time: f64,
463        stop_time: Option<f64>,
464    ) -> Result<(), Fail> {
465        self.in_mode(&[Mode::Instantiated], "SetupExperiment")?;
466        // A start time that is not a number would pass every later check of the communication point.
467        if !start_time.is_finite()
468            || stop_time.is_some_and(|t| !t.is_finite())
469            || tolerance.is_some_and(|t| !t.is_finite())
470        {
471            return Err(("fmi-error-experiment", format!("{start_time:?}, {stop_time:?}, {tolerance:?}")));
472        }
473        self.start_time = start_time;
474        Ok(())
475    }
476
477    pub(crate) fn enter_initialisation(&mut self) -> Result<fmi2Status, Fail> {
478        self.in_mode(&[Mode::Instantiated], "EnterInitializationMode")?;
479        self.mode = Mode::Initialising;
480        Ok(fmi2OK)
481    }
482
483    pub(crate) fn exit_initialisation(&mut self) -> Result<fmi2Status, Fail> {
484        self.in_mode(&[Mode::Initialising], "ExitInitializationMode")?;
485        self.ensure_sim()?;
486        // A fresh sample: the outputs at the start time as it is now.
487        self.take_sample();
488        self.mode = Mode::Stepping;
489        Ok(fmi2OK)
490    }
491
492    pub(crate) fn terminate(&mut self) -> Result<fmi2Status, Fail> {
493        self.in_mode(&[Mode::Stepping], "Terminate")?;
494        self.mode = Mode::Terminated;
495        Ok(fmi2OK)
496    }
497
498    pub(crate) fn reset(&mut self) -> Result<fmi2Status, Fail> {
499        (self.mode, self.start_time, self.sim) = (Mode::Instantiated, 0.0, None);
500        self.set.iter_mut().for_each(|v| *v = None);
501        self.latched = [false; 3];
502        Ok(fmi2OK)
503    }
504
505    /// The time the simulation stands at, as the importer counts it.
506    pub(crate) fn now(&self) -> f64 {
507        self.start_time + self.sim.as_ref().map_or(0.0, |s| s.time())
508    }
509
510    pub(crate) fn do_step(&mut self, point: f64, size: f64) -> Result<fmi2Status, Fail> {
511        self.in_mode(&[Mode::Stepping], "DoStep")?;
512        // An infinite step would loop for ever, and a time that is not a number would pass every comparison.
513        if !(point.is_finite() && size.is_finite()) {
514            return Err(("fmi-error-step", format!("{point:?}, {size:?}")));
515        }
516        let now = self.now();
517        let sim = self.sim.as_ref().ok_or(("fmi-error-state", "DoStep".to_string()))?;
518        let steps = (size / sim.dt).round();
519        // More base steps than a u32 holds would run for days: refused as an importer's mistake.
520        if !(1.0..=u32::MAX as f64).contains(&steps) || (steps * sim.dt - size).abs() > 1e-9 * size.max(sim.dt) {
521            return Err(("fmi-error-step", format!("{size:?} / {:?}", sim.dt)));
522        }
523        if !((point - now).abs() <= 0.5 * sim.dt) {
524            return Err(("fmi-error-time", format!("{point:?} / {now:?}")));
525        }
526        let mut applied = Applied {
527            steps: steps as u32,
528            enable: !matches!(self.set[self.find(&Kind::Enable)], Some(Value::Bool(false))),
529            category: StopCategory::Zero,
530            commands: Vec::new(),
531            setpoints: vec![None; sim.machine.axes().len()],
532            modes: Vec::new(),
533        };
534        let mut warnings = Vec::new();
535        let category = self.text_value(self.find(&Kind::StopCategory));
536        match category.parse().ok().and_then(StopCategory::from_number) {
537            Some(c) => applied.category = c,
538            None => warnings.push(self.tr.tr_arg("fmi-error-stop-category", &category)),
539        }
540        for k in 0..sim.machine.motors().len() {
541            let mode = self.text_value(self.find(&Kind::DriveMode(k)));
542            applied.modes.push(match mode.as_str() {
543                "velocity" => DriveMode::Velocity(self.real_value(self.find(&Kind::Velocity(k)))),
544                "torque" => DriveMode::Torque(self.real_value(self.find(&Kind::Torque(k)))),
545                "position" => DriveMode::Position,
546                _ => {
547                    warnings.push(self.tr.tr_arg("fmi-error-drive-mode", &mode));
548                    sim.control.drives[k].mode()
549                }
550            });
551        }
552        for (index, v) in self.model.variables.iter().enumerate() {
553            if let (Kind::Setpoint(i), Some(Value::Real(value))) = (&v.kind, &self.set[index]) {
554                applied.setpoints[*i] = Some(*value);
555            }
556        }
557        // The triggers that changed since the last communication point.
558        let on = [Kind::Cycle, Kind::Move, Kind::RunPath].map(|kind| self.bool_value(self.find(&kind)));
559        if on[0] != self.latched[0] {
560            applied.commands.push(if on[0] { Command::StartCycle } else { Command::Stop });
561        }
562        if on[1] && !self.latched[1] {
563            let targets = (0..applied.setpoints.len()).map(|i| self.real_value(self.find(&Kind::Target(i))));
564            applied.commands.push(Command::MoveTo(targets.collect()));
565        }
566        if on[2] && !self.latched[2] {
567            match self.planned_path(sim) {
568                Ok(points) => applied.commands.push(Command::Trajectory(points)),
569                Err((key, arg)) => warnings.push(self.tr.tr_arg(key, &arg)),
570            }
571        }
572        for command in &applied.commands {
573            let what = match command {
574                Command::MoveTo(target) => format!("MoveTo {target:?}"),
575                Command::Trajectory(points) => {
576                    format!("Trajectory {} {:.4} s", points.len(), points.last().map_or(0.0, |p| p.0))
577                }
578                other => format!("{other:?}"),
579            };
580            self.note(EVENTS, fmi2OK, &self.tr.tr_arg("fmi-log-command", &format!("{now:?}: {what}")));
581        }
582        self.latched = on;
583        let refused = apply(self.sim.as_mut().expect("checked above"), &applied);
584        warnings.extend(refused.iter().map(|key| self.tr.tr_arg("fmi-refused", self.tr.tr(key))));
585        for warning in &warnings {
586            self.note(WARNINGS, fmi2Warning, warning);
587        }
588        self.take_sample();
589        Ok(if warnings.is_empty() { fmi2OK } else { fmi2Warning })
590    }
591
592    /// The poses of `command.trajectory_file` where it is not empty, else the path or program of `command.path_file`
593    /// (where it is not empty) or of `command.path`, planned from where the machine stands as `sim-cli run --path` plans
594    /// it: within the axis limits, or with `time_optimal` as fast as the motors allow.
595    fn planned_path(&self, sim: &Sim) -> Result<Vec<(f64, Vec<f64>)>, Fail> {
596        let read = |file: &str| std::fs::read_to_string(file).map_err(|e| ("fmi-error-path", format!("{file}: {e}")));
597        let trajectory = self.text_value(self.find(&Kind::TrajectoryFile));
598        if !trajectory.is_empty() {
599            return sim_components::path::parse_trajectory(&read(&trajectory)?)
600                .map_err(|line| ("fmi-error-path", format!("{trajectory}: {line}")));
601        }
602        let file = self.text_value(self.find(&Kind::PathFile));
603        let text = if file.is_empty() { self.text_value(self.find(&Kind::PathText)) } else { read(&file)? };
604        let time_optimal = self.bool_value(self.find(&Kind::TimeOptimal));
605        // The config's own `program.orientation_speed_rad_s`, as the simulator's path run reads it.
606        let machine = self.text_value(self.find(&Kind::Machine));
607        let entry = if machine == self.model.entry.id {
608            self.model.entry
609        } else {
610            sim_machines::find(&machine).ok_or(("fmi-error-config", machine.clone()))?
611        };
612        let config_file = self.text_value(self.find(&Kind::ConfigFile));
613        let config_text = if config_file.is_empty() { self.model.config_text.clone() } else { read(&config_file)? };
614        let refused = |e: sim_core::ConfigError| ("fmi-error-config", self.tr.tr_arg(e.key(), e.detail()));
615        let cfg = load_config(entry, &config_text).map_err(refused)?;
616        let speed = sim_components::program::orientation_speed_of(&cfg).map_err(refused)?;
617        let runs =
618            sim_components::program::read_with(&file, &text, sim.machine.axes(), sim.control.planned_pos(), speed)
619                .map_err(|e| ("fmi-error-path", format!("{file}:{}: {}", e.line, self.tr.tr_arg(e.key, &e.detail))))?;
620        // A program with feeds is planned run by run; one run at the axes' limits as a path file is.
621        match sim_components::program::as_path(&runs) {
622            Some(pieces) => sim.plan_path(pieces, time_optimal),
623            None => sim.plan_program(&runs, time_optimal),
624        }
625        .map_err(|e| ("fmi-error-path", self.tr.tr(e.key).to_string()))
626    }
627
628    pub(crate) fn get_state(&self) -> FmuState {
629        let stepping = matches!(self.mode, Mode::Stepping | Mode::Terminated);
630        FmuState {
631            guid: self.model.guid.clone(),
632            mode: self.mode,
633            start_time: self.start_time,
634            set: self.set.clone(),
635            latched: self.latched,
636            snapshot: self.sim.as_ref().filter(|_| stepping).map(|sim| (sim.snapshot(), self.sample.clone())),
637        }
638    }
639
640    /// Sets a state: in step mode the simulation is built from the state's parameters and its snapshot restored into
641    /// it. Everything is built before anything is changed, so a state that cannot be set leaves the instance as it was.
642    pub(crate) fn set_state(&mut self, state: &FmuState) -> Result<fmi2Status, Fail> {
643        let refused = || ("fmi-error-fmu-state", state.guid.clone());
644        if state.guid != self.model.guid || state.set.len() != self.set.len() {
645            return Err(refused());
646        }
647        let (sim, sample) = if matches!(state.mode, Mode::Stepping | Mode::Terminated) {
648            let (snapshot, sample) = state.snapshot.as_ref().ok_or_else(refused)?;
649            let mut sim = self.build_sim(&state.set)?;
650            sim.restore(snapshot).map_err(|_| refused())?;
651            (Some(sim), sample.clone())
652        } else {
653            (None, Vec::new())
654        };
655        (self.mode, self.start_time, self.set, self.sim) = (state.mode, state.start_time, state.set.clone(), sim);
656        (self.sample, self.latched) = (sample, state.latched);
657        self.note(EVENTS, fmi2OK, &self.tr.tr_arg("fmi-log-state", &format!("{:?} {:?}", self.mode, self.now())));
658        Ok(fmi2OK)
659    }
660
661    /// Checks a directional or adjoint derivative's references: unknowns are outputs, knowns inputs, both Real.
662    /// The derivative itself is zero (see the module's documentation).
663    pub(crate) fn check_derivative(&self, unknowns: &[u32], knowns: &[u32]) -> Result<(), Fail> {
664        self.in_mode(&[Mode::Initialising, Mode::Stepping], "GetDirectionalDerivative")?;
665        let is = |vr: &u32, causality: &str| {
666            self.model
667                .variables
668                .get(*vr as usize)
669                .is_some_and(|v| v.type_name() == "Real" && v.causality() == causality)
670        };
671        if let Some(vr) =
672            unknowns.iter().find(|vr| !is(vr, "output")).or_else(|| knowns.iter().find(|vr| !is(vr, "input")))
673        {
674            return Err(("fmi-error-reference", format!("Real {vr}")));
675        }
676        Ok(())
677    }
678}
679
680/// The serialized state's format; a state of another one (format 2 replayed its steps, format 3 had the snapshot layout
681/// of before 25 November) is refused by name.
682const STATE_MAGIC: &[u8] = b"sim-fmi state 4\0";
683
684impl FmuState {
685    /// The state as bytes: the format, the FMU's version, then little-endian numbers, lengths as u64, texts as UTF-8,
686    /// and the snapshot as `postcard` writes it (its layout is the version's, hence the version in front).
687    pub(crate) fn to_bytes(&self) -> Vec<u8> {
688        let mut out = STATE_MAGIC.to_vec();
689        let text = |out: &mut Vec<u8>, t: &str| {
690            out.extend((t.len() as u64).to_le_bytes());
691            out.extend(t.as_bytes());
692        };
693        text(&mut out, env!("CARGO_PKG_VERSION"));
694        text(&mut out, &self.guid);
695        out.push(self.mode as u8);
696        out.extend(self.start_time.to_le_bytes());
697        out.extend(self.latched.map(u8::from));
698        out.extend((self.set.len() as u64).to_le_bytes());
699        for value in &self.set {
700            match value {
701                None => out.push(0),
702                Some(Value::Real(v)) => {
703                    out.push(1);
704                    out.extend(v.to_le_bytes());
705                }
706                Some(Value::Bool(b)) => out.extend([2, *b as u8]),
707                Some(Value::Text(t)) => {
708                    out.push(3);
709                    text(&mut out, t);
710                }
711            }
712        }
713        match &self.snapshot {
714            None => out.push(0),
715            Some((snapshot, sample)) => {
716                out.push(1);
717                out.extend((sample.len() as u64).to_le_bytes());
718                sample.iter().for_each(|x| out.extend(x.to_le_bytes()));
719                // Numbers, vectors and enums written to a vector: nothing that can fail.
720                let bytes = postcard::to_allocvec(snapshot).expect("a snapshot is plain data");
721                out.extend((bytes.len() as u64).to_le_bytes());
722                out.extend(bytes);
723            }
724        }
725        out
726    }
727
728    /// The state from `to_bytes`. A state of another format or version is refused as such
729    /// (`fmi-error-fmu-state-version`), anything else that does not read back whole (cut off, extended) as damaged.
730    pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Self, Fail> {
731        let damaged = || ("fmi-error-fmu-state", format!("{} bytes", bytes.len()));
732        let Some(rest) = bytes.strip_prefix(STATE_MAGIC) else {
733            if !bytes.starts_with(b"sim-fmi state ") {
734                return Err(damaged());
735            }
736            let format = bytes.iter().take(STATE_MAGIC.len()).take_while(|b| **b != 0).map(|b| *b as char);
737            return Err(("fmi-error-fmu-state-version", format.collect()));
738        };
739        let mut read = Reader(rest);
740        let version = read.text().ok_or_else(damaged)?;
741        if version != env!("CARGO_PKG_VERSION") {
742            return Err(("fmi-error-fmu-state-version", version));
743        }
744        Self::read(&mut read).filter(|_| read.0.is_empty()).ok_or_else(damaged)
745    }
746
747    fn read(read: &mut Reader) -> Option<Self> {
748        let guid = read.text()?;
749        let mode = match read.u8()? {
750            0 => Mode::Instantiated,
751            1 => Mode::Initialising,
752            2 => Mode::Stepping,
753            3 => Mode::Terminated,
754            _ => return None,
755        };
756        let start_time = read.f64()?;
757        let latched = [read.u8()? != 0, read.u8()? != 0, read.u8()? != 0];
758        let mut set = Vec::new();
759        for _ in 0..read.u64()? {
760            set.push(match read.u8()? {
761                0 => None,
762                1 => Some(Value::Real(read.f64()?)),
763                2 => Some(Value::Bool(read.u8()? != 0)),
764                3 => Some(Value::Text(read.text()?)),
765                _ => return None,
766            });
767        }
768        let snapshot = match read.u8()? {
769            0 => None,
770            1 => {
771                let sample = read.numbers()?;
772                let n = usize::try_from(read.u64()?).ok()?;
773                Some((postcard::from_bytes(read.take(n)?).ok()?, sample))
774            }
775            _ => return None,
776        };
777        Some(Self { guid, mode, start_time, set, latched, snapshot })
778    }
779}
780
781/// Reads from the front of a byte slice.
782struct Reader<'a>(&'a [u8]);
783
784impl<'a> Reader<'a> {
785    fn take(&mut self, n: usize) -> Option<&'a [u8]> {
786        let (head, tail) = (self.0.get(..n)?, self.0.get(n..)?);
787        self.0 = tail;
788        Some(head)
789    }
790    fn u8(&mut self) -> Option<u8> {
791        Some(self.take(1)?[0])
792    }
793    fn u64(&mut self) -> Option<u64> {
794        Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?))
795    }
796    fn f64(&mut self) -> Option<f64> {
797        Some(f64::from_bits(self.u64()?))
798    }
799    /// A length and as many numbers; a length the bytes cannot hold is refused before anything is allocated.
800    fn numbers(&mut self) -> Option<Vec<f64>> {
801        let n = usize::try_from(self.u64()?).ok()?;
802        let bytes = self.take(n.checked_mul(8)?)?;
803        Some(bytes.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect())
804    }
805    fn text(&mut self) -> Option<String> {
806        let n = usize::try_from(self.u64()?).ok()?;
807        String::from_utf8(self.take(n)?.to_vec()).ok()
808    }
809}
810
811/// Runs `f` on the instance; a refusal is logged and returned as an error (3 in both versions), a panic as fatal (4).
812///
813/// # Safety
814/// `c` is null or an instance from `fmi2Instantiate` or `fmi3InstantiateCoSimulation` that has not been freed.
815pub(crate) unsafe fn with(c: *mut c_void, f: impl FnOnce(&mut Instance) -> Result<fmi2Status, Fail>) -> fmi2Status {
816    let Some(instance) = (unsafe { (c as *mut Instance).as_mut() }) else { return fmi2Error };
817    match catch_unwind(AssertUnwindSafe(|| f(&mut *instance))) {
818        Ok(Ok(status)) => status,
819        Ok(Err(fail)) => instance.fail(fmi2Error, fail),
820        Err(_) => fmi2Fatal,
821    }
822}
823
824/// A new instance of the FMU whose resources are in `resources`, for FMI version `fmi`; null, after a logged
825/// message, when the type is not co-simulation, the resources cannot be read or `token` (GUID or instantiation token)
826/// is not this FMU's.
827pub(crate) fn instantiate(
828    name: &str,
829    logger: Logger,
830    environment: *mut c_void,
831    resources: &Path,
832    token: &str,
833    fmi: u8,
834    co_simulation: bool,
835    logging_on: bool,
836) -> *mut c_void {
837    let name = c_text(name);
838    let made = catch_unwind(AssertUnwindSafe(|| -> Result<Instance, (Translations, Fail)> {
839        // Until the FMU's language is known, its messages are in English.
840        let mut tr = Translations::default();
841        sim_core::i18n::I18N.iter().chain(crate::I18N).filter(|(l, _)| *l == "en").for_each(|(_, t)| tr.add(t));
842        if !co_simulation {
843            return Err((tr, ("fmi-error-type", String::new())));
844        }
845        let read = |file: &str| {
846            std::fs::read_to_string(resources.join(file))
847                .map_err(|e| ("fmi-error-resources", format!("{}: {e}", resources.join(file).display())))
848        };
849        let (about, config_text) = match (read("model.txt"), read("config.toml")) {
850            (Ok(a), Ok(c)) => (a, c),
851            (Err(e), _) | (_, Err(e)) => return Err((tr, e)),
852        };
853        let mut lines = about.lines();
854        let (id, lang) = (lines.next().unwrap_or("").trim(), lines.next().unwrap_or("en").trim());
855        let Ok(entry) = crate::machine_of(resources, id) else { return Err((tr, ("fmi-error-resources", id.into()))) };
856        let tr = texts(lang, entry);
857        let model = match Model::with_fmi(entry, &config_text, lang, fmi) {
858            Ok(model) => model,
859            Err(e) => {
860                let detail = tr.tr_arg(e.key(), e.detail());
861                return Err((tr, ("fmi-error-config", detail)));
862            }
863        };
864        if model.guid != token {
865            return Err((tr, ("fmi-error-guid", token.into())));
866        }
867        let set = vec![None; model.variables.len()];
868        Ok(Instance {
869            name: name.clone(),
870            logger,
871            environment,
872            tr,
873            model,
874            set,
875            mode: Mode::Instantiated,
876            start_time: 0.0,
877            sim: None,
878            sample: Vec::new(),
879            strings: Vec::new(),
880            latched: [false; 3],
881            logging: [logging_on, true, true],
882        })
883    }));
884    match made {
885        Ok(Ok(instance)) => Box::into_raw(Box::new(instance)) as *mut c_void,
886        Ok(Err((tr, (key, arg)))) => {
887            log(logger, environment, &name, fmi2Error, ERRORS, &tr.tr_arg(key, &arg));
888            std::ptr::null_mut()
889        }
890        Err(_) => std::ptr::null_mut(),
891    }
892}
893
894/// The strings of `vr` handed out through `value`, valid until the next call on the instance.
895///
896/// # Safety
897/// See `with`; `vr` and `value` point to `n` values.
898pub(crate) unsafe fn get_strings(c: *mut c_void, vr: *const u32, n: usize, value: *mut *const c_char) -> fmi2Status {
899    unsafe {
900        with(c, |i| {
901            i.strings.clear();
902            for r in slice(vr, n)? {
903                let index = i.variable(*r, "String")?;
904                i.strings.push(c_text(&i.text_value(index)));
905            }
906            for (s, v) in i.strings.iter().zip(slice_mut(value, n)?) {
907                *v = s.as_ptr();
908            }
909            Ok(fmi2OK)
910        })
911    }
912}
913
914// The FMU state functions of both versions. A state is a `Box<FmuState>` behind the importer's pointer.
915
916/// # Safety
917/// See `with`; `slot` is null or points to null or to a state from this library.
918pub(crate) unsafe fn state_get(c: *mut c_void, slot: *mut *mut c_void) -> fmi2Status {
919    unsafe {
920        with(c, |i| {
921            let slot = slot.as_mut().ok_or(("fmi-error-fmu-state", "null".to_string()))?;
922            let state = i.get_state();
923            // A state given back is overwritten, as the standard has it.
924            match (*slot as *mut FmuState).as_mut() {
925                Some(old) => *old = state,
926                None => *slot = Box::into_raw(Box::new(state)) as *mut c_void,
927            }
928            Ok(fmi2OK)
929        })
930    }
931}
932
933/// # Safety
934/// See `state_get`; `state` is null or a state from this library.
935pub(crate) unsafe fn state_set(c: *mut c_void, state: *mut c_void) -> fmi2Status {
936    unsafe {
937        with(c, |i| {
938            i.set_state((state as *const FmuState).as_ref().ok_or(("fmi-error-fmu-state", "null".to_string()))?)
939        })
940    }
941}
942
943/// # Safety
944/// See `state_get`; the state is not used afterwards.
945pub(crate) unsafe fn state_free(c: *mut c_void, slot: *mut *mut c_void) -> fmi2Status {
946    unsafe {
947        with(c, |_| {
948            if let Some(slot) = slot.as_mut() {
949                if !slot.is_null() {
950                    drop(Box::from_raw(*slot as *mut FmuState));
951                }
952                *slot = std::ptr::null_mut();
953            }
954            Ok(fmi2OK)
955        })
956    }
957}
958
959/// # Safety
960/// See `state_set`; `size` is writable.
961pub(crate) unsafe fn state_size(c: *mut c_void, state: *mut c_void, size: *mut usize) -> fmi2Status {
962    unsafe {
963        with(c, |_| {
964            let state = (state as *const FmuState).as_ref().ok_or(("fmi-error-fmu-state", "null".to_string()))?;
965            *size.as_mut().ok_or(("fmi-error-fmu-state", "size".to_string()))? = state.to_bytes().len();
966            Ok(fmi2OK)
967        })
968    }
969}
970
971/// # Safety
972/// See `state_set`; `bytes` points to `size` writable bytes.
973pub(crate) unsafe fn state_serialize(c: *mut c_void, state: *mut c_void, bytes: *mut u8, size: usize) -> fmi2Status {
974    unsafe {
975        with(c, |_| {
976            let state = (state as *const FmuState).as_ref().ok_or(("fmi-error-fmu-state", "null".to_string()))?;
977            let data = state.to_bytes();
978            let out = slice_mut(bytes, size)?;
979            if out.len() != data.len() {
980                return Err(("fmi-error-fmu-state", format!("{size} / {}", data.len())));
981            }
982            out.copy_from_slice(&data);
983            Ok(fmi2OK)
984        })
985    }
986}
987
988/// # Safety
989/// See `state_get`; `bytes` points to `size` bytes.
990pub(crate) unsafe fn state_deserialize(
991    c: *mut c_void,
992    bytes: *const u8,
993    size: usize,
994    slot: *mut *mut c_void,
995) -> fmi2Status {
996    unsafe {
997        with(c, |i| {
998            let state = FmuState::from_bytes(slice(bytes, size)?)?;
999            if state.guid != i.model.guid || state.set.len() != i.model.variables.len() {
1000                return Err(("fmi-error-fmu-state", state.guid));
1001            }
1002            let slot = slot.as_mut().ok_or(("fmi-error-fmu-state", "null".to_string()))?;
1003            match (*slot as *mut FmuState).as_mut() {
1004                Some(old) => *old = state,
1005                None => *slot = Box::into_raw(Box::new(state)) as *mut c_void,
1006            }
1007            Ok(fmi2OK)
1008        })
1009    }
1010}
1011
1012/// A directional or adjoint derivative: the references checked, `n` zeros written to `out`.
1013///
1014/// # Safety
1015/// See `with`; the pointers point to as many values as their counts say.
1016pub(crate) unsafe fn zero_derivative(
1017    c: *mut c_void,
1018    unknowns: *const u32,
1019    n_unknowns: usize,
1020    knowns: *const u32,
1021    n_knowns: usize,
1022    out: *mut f64,
1023    n: usize,
1024) -> fmi2Status {
1025    unsafe {
1026        with(c, |i| {
1027            i.check_derivative(slice(unknowns, n_unknowns)?, slice(knowns, n_knowns)?)?;
1028            slice_mut(out, n)?.fill(0.0);
1029            Ok(fmi2OK)
1030        })
1031    }
1032}
1033
1034#[unsafe(no_mangle)]
1035pub extern "C" fn fmi2GetTypesPlatform() -> *const c_char {
1036    c"default".as_ptr()
1037}
1038
1039#[unsafe(no_mangle)]
1040pub extern "C" fn fmi2GetVersion() -> *const c_char {
1041    c"2.0".as_ptr()
1042}
1043
1044/// # Safety
1045/// As the FMI standard demands of the caller: valid strings, `functions` null or valid for the instance's life.
1046#[unsafe(no_mangle)]
1047pub unsafe extern "C" fn fmi2Instantiate(
1048    instanceName: fmi2String,
1049    fmuType: c_int,
1050    fmuGUID: fmi2String,
1051    fmuResourceLocation: fmi2String,
1052    functions: *const fmi2CallbackFunctions,
1053    _visible: fmi2Boolean,
1054    loggingOn: fmi2Boolean,
1055) -> fmi2Component {
1056    let callbacks = unsafe { functions.as_ref() };
1057    let (logger, environment) =
1058        (callbacks.and_then(|f| f.logger), callbacks.map_or(std::ptr::null_mut(), |f| f.componentEnvironment));
1059    let resources = resource_dir(unsafe { text(fmuResourceLocation) });
1060    instantiate(
1061        unsafe { text(instanceName) },
1062        Logger::Fmi2(logger),
1063        environment,
1064        &resources,
1065        unsafe { text(fmuGUID) },
1066        2,
1067        fmuType == fmi2CoSimulation,
1068        loggingOn != 0,
1069    )
1070}
1071
1072/// `fmi2SetDebugLogging` and `fmi3SetDebugLogging` alike.
1073///
1074/// # Safety
1075/// See `with`; `categories` points to `n` valid strings.
1076pub(crate) unsafe fn debug_logging(c: *mut c_void, on: bool, n: usize, categories: *const *const c_char) -> fmi2Status {
1077    unsafe {
1078        with(c, |i| {
1079            let names: Vec<&str> = slice(categories, n)?.iter().map(|p| text(*p)).collect();
1080            i.set_debug_logging(on, &names)
1081        })
1082    }
1083}
1084
1085/// # Safety
1086/// `c` is null or an instance from `fmi2Instantiate`; it is not used afterwards.
1087#[unsafe(no_mangle)]
1088pub unsafe extern "C" fn fmi2FreeInstance(c: fmi2Component) {
1089    if !c.is_null() {
1090        drop(unsafe { Box::from_raw(c as *mut Instance) });
1091    }
1092}
1093
1094/// Switches the log categories named in `categories` (all of them where `nCategories` is 0, or with `logAll`).
1095///
1096/// # Safety
1097/// See `with`; `categories` points to `nCategories` valid strings.
1098#[unsafe(no_mangle)]
1099pub unsafe extern "C" fn fmi2SetDebugLogging(
1100    c: fmi2Component,
1101    loggingOn: fmi2Boolean,
1102    nCategories: usize,
1103    categories: *const fmi2String,
1104) -> fmi2Status {
1105    unsafe { debug_logging(c, loggingOn != 0, nCategories, categories) }
1106}
1107
1108/// # Safety
1109/// See `with`.
1110#[unsafe(no_mangle)]
1111pub unsafe extern "C" fn fmi2SetupExperiment(
1112    c: fmi2Component,
1113    toleranceDefined: fmi2Boolean,
1114    tolerance: fmi2Real,
1115    startTime: fmi2Real,
1116    stopTimeDefined: fmi2Boolean,
1117    stopTime: fmi2Real,
1118) -> fmi2Status {
1119    unsafe {
1120        with(c, |i| {
1121            i.setup((toleranceDefined != 0).then_some(tolerance), startTime, (stopTimeDefined != 0).then_some(stopTime))
1122                .map(|_| fmi2OK)
1123        })
1124    }
1125}
1126
1127/// # Safety
1128/// See `with`.
1129#[unsafe(no_mangle)]
1130pub unsafe extern "C" fn fmi2EnterInitializationMode(c: fmi2Component) -> fmi2Status {
1131    unsafe { with(c, Instance::enter_initialisation) }
1132}
1133
1134/// # Safety
1135/// See `with`.
1136#[unsafe(no_mangle)]
1137pub unsafe extern "C" fn fmi2ExitInitializationMode(c: fmi2Component) -> fmi2Status {
1138    unsafe { with(c, Instance::exit_initialisation) }
1139}
1140
1141/// # Safety
1142/// See `with`.
1143#[unsafe(no_mangle)]
1144pub unsafe extern "C" fn fmi2Terminate(c: fmi2Component) -> fmi2Status {
1145    unsafe { with(c, Instance::terminate) }
1146}
1147
1148/// # Safety
1149/// See `with`.
1150#[unsafe(no_mangle)]
1151pub unsafe extern "C" fn fmi2Reset(c: fmi2Component) -> fmi2Status {
1152    unsafe { with(c, Instance::reset) }
1153}
1154
1155/// # Safety
1156/// See `with`; `vr` and `value` point to `nvr` values.
1157#[unsafe(no_mangle)]
1158pub unsafe extern "C" fn fmi2GetReal(
1159    c: fmi2Component,
1160    vr: *const fmi2ValueReference,
1161    nvr: usize,
1162    value: *mut fmi2Real,
1163) -> fmi2Status {
1164    unsafe {
1165        with(c, |i| {
1166            for (r, v) in slice(vr, nvr)?.iter().zip(slice_mut(value, nvr)?) {
1167                *v = i.get_real(*r)?;
1168            }
1169            Ok(fmi2OK)
1170        })
1171    }
1172}
1173
1174/// # Safety
1175/// See `fmi2GetReal`.
1176#[unsafe(no_mangle)]
1177pub unsafe extern "C" fn fmi2SetReal(
1178    c: fmi2Component,
1179    vr: *const fmi2ValueReference,
1180    nvr: usize,
1181    value: *const fmi2Real,
1182) -> fmi2Status {
1183    unsafe {
1184        with(c, |i| {
1185            for (r, v) in slice(vr, nvr)?.iter().zip(slice(value, nvr)?) {
1186                i.set_value(*r, Value::Real(*v))?;
1187            }
1188            Ok(fmi2OK)
1189        })
1190    }
1191}
1192
1193/// The FMU has no Integer variables: any value reference is refused.
1194///
1195/// # Safety
1196/// See `fmi2GetReal`.
1197#[unsafe(no_mangle)]
1198pub unsafe extern "C" fn fmi2GetInteger(
1199    c: fmi2Component,
1200    vr: *const fmi2ValueReference,
1201    nvr: usize,
1202    _value: *mut fmi2Integer,
1203) -> fmi2Status {
1204    unsafe { with(c, |i| slice(vr, nvr)?.first().map_or(Ok(fmi2OK), |r| i.variable(*r, "Integer").map(|_| fmi2OK))) }
1205}
1206
1207/// # Safety
1208/// See `fmi2GetReal`.
1209#[unsafe(no_mangle)]
1210pub unsafe extern "C" fn fmi2SetInteger(
1211    c: fmi2Component,
1212    vr: *const fmi2ValueReference,
1213    nvr: usize,
1214    _value: *const fmi2Integer,
1215) -> fmi2Status {
1216    unsafe { with(c, |i| slice(vr, nvr)?.first().map_or(Ok(fmi2OK), |r| i.variable(*r, "Integer").map(|_| fmi2OK))) }
1217}
1218
1219/// # Safety
1220/// See `fmi2GetReal`.
1221#[unsafe(no_mangle)]
1222pub unsafe extern "C" fn fmi2GetBoolean(
1223    c: fmi2Component,
1224    vr: *const fmi2ValueReference,
1225    nvr: usize,
1226    value: *mut fmi2Boolean,
1227) -> fmi2Status {
1228    unsafe {
1229        with(c, |i| {
1230            for (r, v) in slice(vr, nvr)?.iter().zip(slice_mut(value, nvr)?) {
1231                *v = i.bool_value(i.variable(*r, "Boolean")?) as fmi2Boolean;
1232            }
1233            Ok(fmi2OK)
1234        })
1235    }
1236}
1237
1238/// # Safety
1239/// See `fmi2GetReal`.
1240#[unsafe(no_mangle)]
1241pub unsafe extern "C" fn fmi2SetBoolean(
1242    c: fmi2Component,
1243    vr: *const fmi2ValueReference,
1244    nvr: usize,
1245    value: *const fmi2Boolean,
1246) -> fmi2Status {
1247    unsafe {
1248        with(c, |i| {
1249            for (r, v) in slice(vr, nvr)?.iter().zip(slice(value, nvr)?) {
1250                i.set_value(*r, Value::Bool(*v != 0))?;
1251            }
1252            Ok(fmi2OK)
1253        })
1254    }
1255}
1256
1257/// The strings stay valid until the next call of this function on the instance.
1258///
1259/// # Safety
1260/// See `fmi2GetReal`.
1261#[unsafe(no_mangle)]
1262pub unsafe extern "C" fn fmi2GetString(
1263    c: fmi2Component,
1264    vr: *const fmi2ValueReference,
1265    nvr: usize,
1266    value: *mut fmi2String,
1267) -> fmi2Status {
1268    unsafe { get_strings(c, vr, nvr, value) }
1269}
1270
1271/// # Safety
1272/// See `fmi2GetReal`; every string is valid.
1273#[unsafe(no_mangle)]
1274pub unsafe extern "C" fn fmi2SetString(
1275    c: fmi2Component,
1276    vr: *const fmi2ValueReference,
1277    nvr: usize,
1278    value: *const fmi2String,
1279) -> fmi2Status {
1280    unsafe {
1281        with(c, |i| {
1282            for (r, v) in slice(vr, nvr)?.iter().zip(slice(value, nvr)?) {
1283                i.set_value(*r, Value::Text(text(*v).into()))?;
1284            }
1285            Ok(fmi2OK)
1286        })
1287    }
1288}
1289
1290/// # Safety
1291/// See `with`.
1292#[unsafe(no_mangle)]
1293pub unsafe extern "C" fn fmi2DoStep(
1294    c: fmi2Component,
1295    currentCommunicationPoint: fmi2Real,
1296    communicationStepSize: fmi2Real,
1297    _noSetFMUStatePriorToCurrentPoint: fmi2Boolean,
1298) -> fmi2Status {
1299    unsafe { with(c, |i| i.do_step(currentCommunicationPoint, communicationStepSize)) }
1300}
1301
1302/// A copy of the instance's state: what was set and the simulation's snapshot.
1303///
1304/// # Safety
1305/// See `with`; `state` points to null or to a state from this library, which is then overwritten.
1306#[unsafe(no_mangle)]
1307pub unsafe extern "C" fn fmi2GetFMUstate(c: fmi2Component, state: *mut fmi2FMUstate) -> fmi2Status {
1308    unsafe { state_get(c, state) }
1309}
1310
1311/// Restores a state: a fresh simulation from its parameters, its snapshot restored into it.
1312///
1313/// # Safety
1314/// See `with`; `state` is a state from this library.
1315#[unsafe(no_mangle)]
1316pub unsafe extern "C" fn fmi2SetFMUstate(c: fmi2Component, state: fmi2FMUstate) -> fmi2Status {
1317    unsafe { state_set(c, state) }
1318}
1319
1320/// # Safety
1321/// See `fmi2GetFMUstate`.
1322#[unsafe(no_mangle)]
1323pub unsafe extern "C" fn fmi2FreeFMUstate(c: fmi2Component, state: *mut fmi2FMUstate) -> fmi2Status {
1324    unsafe { state_free(c, state) }
1325}
1326
1327/// # Safety
1328/// See `fmi2SetFMUstate`; `size` is writable.
1329#[unsafe(no_mangle)]
1330pub unsafe extern "C" fn fmi2SerializedFMUstateSize(
1331    c: fmi2Component,
1332    state: fmi2FMUstate,
1333    size: *mut usize,
1334) -> fmi2Status {
1335    unsafe { state_size(c, state, size) }
1336}
1337
1338/// # Safety
1339/// See `fmi2SetFMUstate`; `bytes` points to `size` bytes, the size `fmi2SerializedFMUstateSize` gave.
1340#[unsafe(no_mangle)]
1341pub unsafe extern "C" fn fmi2SerializeFMUstate(
1342    c: fmi2Component,
1343    state: fmi2FMUstate,
1344    bytes: *mut fmi2Byte,
1345    size: usize,
1346) -> fmi2Status {
1347    unsafe { state_serialize(c, state, bytes as *mut u8, size) }
1348}
1349
1350/// # Safety
1351/// See `fmi2GetFMUstate`; `bytes` points to `size` bytes.
1352#[unsafe(no_mangle)]
1353pub unsafe extern "C" fn fmi2DeSerializeFMUstate(
1354    c: fmi2Component,
1355    bytes: *const fmi2Byte,
1356    size: usize,
1357    state: *mut fmi2FMUstate,
1358) -> fmi2Status {
1359    unsafe { state_deserialize(c, bytes as *const u8, size, state) }
1360}
1361
1362/// The derivative of outputs with respect to inputs: zero (see the module's documentation).
1363///
1364/// # Safety
1365/// See `with`; the pointers point to as many values as their counts say.
1366#[unsafe(no_mangle)]
1367pub unsafe extern "C" fn fmi2GetDirectionalDerivative(
1368    c: fmi2Component,
1369    unknown: *const fmi2ValueReference,
1370    n_unknown: usize,
1371    known: *const fmi2ValueReference,
1372    n_known: usize,
1373    _dv_known: *const fmi2Real,
1374    dv_unknown: *mut fmi2Real,
1375) -> fmi2Status {
1376    unsafe { zero_derivative(c, unknown, n_unknown, known, n_known, dv_unknown, n_unknown) }
1377}
1378
1379/// # Safety
1380/// See `with`.
1381unsafe fn unsupported(c: fmi2Component, call: &str) -> fmi2Status {
1382    unsafe { with(c, |_| Err(("fmi-error-unsupported", call.into()))) }
1383}
1384
1385macro_rules! unsupported {
1386    ($($name:ident($($arg:ident: $ty:ty),*);)*) => {$(
1387        /// Not supported: returns `fmi2Error`.
1388        ///
1389        /// # Safety
1390        /// See `with`.
1391        #[unsafe(no_mangle)]
1392        pub unsafe extern "C" fn $name(c: fmi2Component, $($arg: $ty),*) -> fmi2Status {
1393            $(let _ = $arg;)*
1394            unsafe { unsupported(c, stringify!($name)) }
1395        }
1396    )*};
1397}
1398
1399unsupported! {
1400    fmi2SetRealInputDerivatives(vr: *const fmi2ValueReference, nvr: usize, order: *const fmi2Integer, value: *const fmi2Real);
1401    fmi2GetRealOutputDerivatives(vr: *const fmi2ValueReference, nvr: usize, order: *const fmi2Integer, value: *mut fmi2Real);
1402    fmi2CancelStep();
1403    fmi2GetStatus(kind: c_int, value: *mut fmi2Status);
1404    fmi2GetRealStatus(kind: c_int, value: *mut fmi2Real);
1405    fmi2GetIntegerStatus(kind: c_int, value: *mut fmi2Integer);
1406    fmi2GetBooleanStatus(kind: c_int, value: *mut fmi2Boolean);
1407    fmi2GetStringStatus(kind: c_int, value: *mut fmi2String);
1408}
1409
1410#[cfg(test)]
1411mod tests {
1412    use super::*;
1413
1414    /// A state of format 2 (which replayed its steps) or of another version of the FMU is refused as such, by its
1415    /// format or version, not as damaged; a whole state of this version reads back, and one byte more is damage.
1416    #[test]
1417    fn a_state_of_another_format_or_version_is_refused_by_name() {
1418        for format in [2, 3] {
1419            let old = [format!("sim-fmi state {format}\0").as_bytes(), &[0; 40]].concat();
1420            let named = Some(("fmi-error-fmu-state-version", format!("sim-fmi state {format}")));
1421            assert_eq!(FmuState::from_bytes(&old).err(), named);
1422        }
1423        let mut other = STATE_MAGIC.to_vec();
1424        other.extend(5u64.to_le_bytes());
1425        other.extend(b"0.9.0");
1426        assert_eq!(FmuState::from_bytes(&other).err(), Some(("fmi-error-fmu-state-version", "0.9.0".into())));
1427        assert_eq!(FmuState::from_bytes(b"no state at all").err().map(|e| e.0), Some("fmi-error-fmu-state"));
1428        let set = vec![None, Some(Value::Real(1.5)), Some(Value::Bool(true)), Some(Value::Text("Bahn รค".into()))];
1429        let state = FmuState {
1430            guid: "{guid}".into(),
1431            mode: Mode::Initialising,
1432            start_time: 0.25,
1433            set: set.clone(),
1434            latched: [true, false, true],
1435            snapshot: None,
1436        };
1437        let bytes = state.to_bytes();
1438        let back = FmuState::from_bytes(&bytes).unwrap();
1439        assert_eq!(
1440            (back.guid.as_str(), back.mode, back.start_time, back.set, back.latched),
1441            ("{guid}", Mode::Initialising, 0.25, set, [true, false, true])
1442        );
1443        assert!(back.snapshot.is_none());
1444        let longer = [bytes.as_slice(), &[0]].concat();
1445        assert_eq!(FmuState::from_bytes(&longer).err().map(|e| e.0), Some("fmi-error-fmu-state"));
1446    }
1447}