Initial commit: Fabrilis docs, rules and deterministic core
Docs (architecture, decisions, coupling, determinism, UI, references), code rules enforced by tools/limits, deterministic core with units, time, math, sched, snapshot, vec and rng, plus smoke tests. ref/ stays out of git.
This commit is contained in:
commit
878d144b77
221 changed files with 5316 additions and 0 deletions
6
.githooks/pre-commit
Executable file
6
.githooks/pre-commit
Executable file
|
|
@ -0,0 +1,6 @@
|
|||
#!/usr/bin/env bash
|
||||
# Включить: git config core.hooksPath .githooks
|
||||
set -euo pipefail
|
||||
cargo run -q -p fabrilis-limits
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
target/
|
||||
*.snap.tmp
|
||||
ref/
|
||||
fabrilis-docs.zip
|
||||
240
Cargo.lock
generated
Normal file
240
Cargo.lock
generated
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-actuators"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-aero"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-analog"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-analysis"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-app"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-modes",
|
||||
"fabrilis-platform",
|
||||
"fabrilis-render",
|
||||
"fabrilis-storage",
|
||||
"fabrilis-ui",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-bridge"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-actuators",
|
||||
"fabrilis-analog",
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-physics",
|
||||
"fabrilis-soc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-core"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-limits",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-cpu"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-limits"
|
||||
version = "0.0.1"
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-materials"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-modes"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-actuators",
|
||||
"fabrilis-aero",
|
||||
"fabrilis-analog",
|
||||
"fabrilis-bridge",
|
||||
"fabrilis-core",
|
||||
"fabrilis-cpu",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-parts",
|
||||
"fabrilis-physics",
|
||||
"fabrilis-platform",
|
||||
"fabrilis-scene",
|
||||
"fabrilis-scripting",
|
||||
"fabrilis-soc",
|
||||
"fabrilis-storage",
|
||||
"fabrilis-structure",
|
||||
"fabrilis-thermal",
|
||||
"fabrilis-wiring",
|
||||
"fabrilis-worldgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-parts"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-materials",
|
||||
"fabrilis-scene",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-physics"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-platform"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-render"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-scene"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-materials",
|
||||
"fabrilis-storage",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-scripting"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-sensors"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-soc"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-cpu",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-storage"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-structure"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-materials",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-thermal"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-materials",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-ui"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-render",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-wiring"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-analog",
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
"fabrilis-thermal",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fabrilis-worldgen"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"fabrilis-core",
|
||||
"fabrilis-limits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
26
Cargo.toml
Normal file
26
Cargo.toml
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
[workspace]
|
||||
members = ["crates/*", "tools/limits"]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.1"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
authors = ["loki"]
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
disallowed_methods = "warn"
|
||||
disallowed_types = "warn"
|
||||
unwrap_used = "warn"
|
||||
expect_used = "warn"
|
||||
panic = "warn"
|
||||
todo = "warn"
|
||||
unimplemented = "warn"
|
||||
dbg_macro = "warn"
|
||||
too_many_lines = "warn"
|
||||
too_many_arguments = "warn"
|
||||
cognitive_complexity = "warn"
|
||||
allow_attributes_without_reason = "warn"
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 loki
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
42
README.md
Normal file
42
README.md
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
# Fabrilis
|
||||
|
||||
Платформа проектирования и виртуальных испытаний механизмов: механика, материалы,
|
||||
электроника, прошивка и управление в одной детерминированной симуляции.
|
||||
|
||||
Название — от лат. *fabrilis*, «относящийся к мастеру, ремесленнику».
|
||||
|
||||
Цель: спроектировать конструкцию целиком, проверить её на сценариях (нагрузки,
|
||||
отказы, тепло, устойчивость), получить отчёт и BOM, а затем собрать в реальности.
|
||||
Эталонный проект — мех-паук в `examples/`; в движке нет кода под конкретную
|
||||
конструкцию.
|
||||
|
||||
## Состояние
|
||||
|
||||
| Этап | Что готово |
|
||||
|---|---|
|
||||
| M0 | workspace, правила кода (`tools/limits`), pre-commit, CI |
|
||||
| M1 | ядро: СИ-единицы, целое время, детерминированная математика, планировщик, снимки |
|
||||
| M2 | в работе: своя векторная математика, RNG, один шарнир с мотором и датчиками |
|
||||
|
||||
План и критерии готовности: [TODO.md](TODO.md).
|
||||
|
||||
## Сборка
|
||||
|
||||
```sh
|
||||
cargo test --workspace # тесты
|
||||
cargo run -p fabrilis-limits # проверка правил репозитория
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
```
|
||||
|
||||
Версия компилятора зафиксирована в `rust-toolchain.toml`. Правила кода
|
||||
проверяются в `build.rs` каждого crate'а, поэтому их нарушение ломает сборку.
|
||||
|
||||
## Документация
|
||||
|
||||
Начать с [docs/README.md](docs/README.md): архитектура, решения, режимы, детерминизм,
|
||||
связь подсистем, тесты и зависимости.
|
||||
|
||||
## Лицензия
|
||||
|
||||
MIT, см. [LICENSE](LICENSE). Код можно брать и менять, но нужно сохранять
|
||||
упоминание автора: Copyright (c) 2026 loki.
|
||||
97
TODO.md
Normal file
97
TODO.md
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
# TODO
|
||||
|
||||
Этапы — вертикальные срезы, а не слои. Каждый срез заканчивается тем, что можно
|
||||
показать и проверить, а не набором готовых подсистем. Порядок можно менять.
|
||||
Подробности: [docs/](docs/README.md).
|
||||
|
||||
## Готово
|
||||
- **M0 — Скелет.** docs, workspace, `fabrilis-limits`, pre-commit, CI.
|
||||
- **M1 — Детерминированное ядро.** `core::units`, `core::time` (u64 нс),
|
||||
`core::math` поверх `libm`, `core::sched` (эпохи, точки синхронизации),
|
||||
`core::fidelity`, `core::snapshot`, `core::id`, golden-тест детерминизма.
|
||||
|
||||
## M2 — Один шарнир
|
||||
Цель: замкнутый контур «сценарий → мотор → шарнир → датчик → регулятор» без мира,
|
||||
рендера и электроники. Это проверка того, что ядро, физика и мост данных стыкуются.
|
||||
- [x] `core::vec`: `Vec3`, `Mat3`, `Quat`, `Transform` (f64, через `core::math`)
|
||||
- [x] `core::units`: `Radians`; `RadiansPerSecond` и `NewtonMeters` — вместе с шарниром
|
||||
- [x] `core::rng`: seeded генератор (xoshiro256** через SplitMix64) для тестов и Monte Carlo
|
||||
- [ ] `physics`: трейт `PhysicsBackend` + Rapier, один шарнир с мотором
|
||||
- [ ] `sensors`: энкодер и IMU (минимум: шум, задержка, дискретизация)
|
||||
- [ ] сценарий на Rust (Rhai позже): PD-регулятор по энкодеру
|
||||
- **DoD:** headless-тест поднимает звено в заданный угол, ошибка < 2 %, golden-хеш
|
||||
состояния; работает без окна и GPU.
|
||||
|
||||
## M3 — Деталь и конструкция
|
||||
Цель: собрать конструкцию из настоящих мешей и сохранить её.
|
||||
- [ ] импорт STL и OBJ, проверка меша (замкнутость, ориентация, единицы)
|
||||
- [ ] масса, COM, тензор инерции по мешу (+ property-тесты на сферах и кубах)
|
||||
- [ ] материалы (плотность, прочность, теплопроводность)
|
||||
- [ ] формат сцены и конструкции (RON), `storage` с миграциями
|
||||
- [ ] `parts`: библиотека деталей, минимальный BOM
|
||||
- **DoD:** тележка из трёх STL-деталей собирается, сохраняется и загружается;
|
||||
масса сходится с аналитикой в пределах 1 %.
|
||||
|
||||
## M4 — Мир и картинка
|
||||
Цель: та же конструкция едет по террейну в окне.
|
||||
- [ ] `worldgen`: высотная карта, чанки, коллайдеры
|
||||
- [ ] `render`: wgpu, clipmap, инстансинг
|
||||
- [ ] `ui`: список команд рисования, glyph atlas, event-driven redraw, оверлей отладки
|
||||
(текст через `fontdue`, прямоугольники, линии, клип)
|
||||
- [ ] `app`: winit, главный цикл, режим World
|
||||
- **DoD:** тележка едет по склону; RTF ≥ 1 на эталонной сцене (см. бюджет в
|
||||
ARCHITECTURE.md); картинка не влияет на результат симуляции.
|
||||
|
||||
## M5 — Паук стоит и ходит
|
||||
Цель: эталонный механизм, ради которого всё строится.
|
||||
- [ ] `examples/spider`: конструкция, приводы, контроллер (без прошивки на МК)
|
||||
- [ ] контакт стопы с землёй, трение, устойчивость
|
||||
- [ ] метрики: нагрузки на шарниры, потребление, опрокидывание
|
||||
- **DoD:** паук стоит и делает 10 шагов без падения; лог и видео; повтор
|
||||
бит-в-бит при 1/2/8 потоках.
|
||||
|
||||
## M6 — Тепло и электроника
|
||||
- [ ] `analog`: MNA, нелинейные элементы (Newton), сходимость (gmin/source stepping)
|
||||
- [ ] `thermal`: тепло и вентиляция, `wiring`: провода как элементы
|
||||
- [ ] очередь событий в планировщике (фронты PWM, прерывания, отказы)
|
||||
- **DoD:** RC-цепь совпадает с экспонентой; провод греется по `I²R`; просадка
|
||||
питания от тока мотора видна в сценарии.
|
||||
|
||||
## M7 — Мост и приводы
|
||||
- [ ] `actuators`: моторы, серво, мышцы (Хилл, McKibben, SMA)
|
||||
- [ ] `bridge`: пины ↔ схема ↔ приводы ↔ физика, сильные связи (COUPLING.md)
|
||||
- **DoD:** контроллер через PWM/ADC крутит мотор с обратной ЭДС; сильная связь
|
||||
сходится, откат шага воспроизводим.
|
||||
|
||||
## M8 — RISC-V и Bench
|
||||
- [ ] RV32IMAC, `soc` (UART, GPIO, PWM, ADC, таймеры), `riscv-tests`
|
||||
- [ ] режим Bench, точность по тактам
|
||||
- **DoD:** `riscv-tests` проходят; та же прошивка, что на реальной плате, ходит
|
||||
паука в Fabrilis.
|
||||
|
||||
## M9 — Структура
|
||||
- [ ] балки и FEM, поле напряжений, режимы вида
|
||||
- [ ] разрушение и усталость (модель «узлы и хрупкие балки»)
|
||||
- **DoD:** консоль даёт `δ = PL³/3EI` с ошибкой < 1 %; рама паука держит ходьбу,
|
||||
а при заданной перегрузке ломается предсказуемо.
|
||||
|
||||
## M10 — Сценарии, анализ, Lab
|
||||
- [ ] `scripting`: Rhai с нашим `core::math`
|
||||
- [ ] `analysis`: развёртки, Monte Carlo, метрики устойчивости, отказы
|
||||
- [ ] режим Lab, редактор конструкций и схем: панели, дерево, таблица свойств,
|
||||
графики, 3D-вид; shaping и IME для полей ввода (UI.md)
|
||||
- **DoD:** отчёт по сценарию воспроизводим с тем же seed; при 1/8/24 потоках
|
||||
метрики совпадают.
|
||||
|
||||
## M11 — Linux
|
||||
- [ ] RV64GC, MMU Sv39, device tree из карты памяти, virtio
|
||||
- [ ] загрузка Linux, реальные драйверы
|
||||
- **DoD:** Linux грузится и видит периферию симулированной платы.
|
||||
|
||||
## M12 — Железо и ISA
|
||||
- [ ] `platform`: P/E-ядра, GPU-профиль, регулятор нагрузки
|
||||
- [ ] управление временем: замедление, перемотка
|
||||
- [ ] arm/avr через трейт `Cpu`
|
||||
|
||||
## Открытые вопросы
|
||||
См. docs/DECISIONS.md.
|
||||
69
clippy.toml
Normal file
69
clippy.toml
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
# Детерминизм: запрет системных трансцендентных функций. Используй fabrilis_core::math (docs/DETERMINISM.md).
|
||||
disallowed-methods = [
|
||||
{ path = "f32::sin", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::cos", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::tan", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::asin", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::acos", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::atan", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::atan2", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::sinh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::cosh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::tanh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::asinh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::acosh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::atanh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::exp", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::exp2", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::exp_m1", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::ln", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::ln_1p", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::log", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::log2", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::log10", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::powf", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::powi", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::cbrt", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::hypot", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f32::sin_cos", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::sin", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::cos", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::tan", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::asin", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::acos", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::atan", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::atan2", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::sinh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::cosh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::tanh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::asinh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::acosh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::atanh", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::exp", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::exp2", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::exp_m1", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::ln", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::ln_1p", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::log", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::log2", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::log10", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::powf", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::powi", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::cbrt", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::hypot", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "f64::sin_cos", reason = "используй fabrilis_core::math (детерминизм)" },
|
||||
{ path = "std::time::Instant::now", reason = "wall-clock time breaks determinism: use SimTime (allowed only in platform/app)" },
|
||||
{ path = "std::time::SystemTime::now", reason = "wall-clock time breaks determinism: use SimTime (allowed only in platform/app)" },
|
||||
]
|
||||
disallowed-types = [
|
||||
{ path = "std::collections::HashMap", reason = "порядок обхода недетерминирован: используй BTreeMap или IndexMap" },
|
||||
{ path = "std::collections::HashSet", reason = "порядок обхода недетерминирован: используй BTreeSet" },
|
||||
]
|
||||
|
||||
# Code quality thresholds
|
||||
too-many-lines-threshold = 60
|
||||
too-many-arguments-threshold = 5
|
||||
cognitive-complexity-threshold = 15
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
16
crates/actuators/Cargo.toml
Normal file
16
crates/actuators/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-actuators"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/actuators/build.rs
Normal file
5
crates/actuators/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
4
crates/actuators/src/lib.rs
Normal file
4
crates/actuators/src/lib.rs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
//! Muscles (Hill, McKibben, SMA), servos, motors
|
||||
pub mod motor;
|
||||
pub mod muscle;
|
||||
pub mod servo;
|
||||
1
crates/actuators/src/motor/mod.rs
Normal file
1
crates/actuators/src/motor/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-actuators :: motor - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/actuators/src/muscle/mod.rs
Normal file
1
crates/actuators/src/muscle/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-actuators :: muscle - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/actuators/src/servo/mod.rs
Normal file
1
crates/actuators/src/servo/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-actuators :: servo - stub (see docs/ARCHITECTURE.md)
|
||||
16
crates/aero/Cargo.toml
Normal file
16
crates/aero/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-aero"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/aero/build.rs
Normal file
5
crates/aero/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
3
crates/aero/src/lib.rs
Normal file
3
crates/aero/src/lib.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
//! Aerodynamics: panel method, wind
|
||||
pub mod panel;
|
||||
pub mod wind;
|
||||
1
crates/aero/src/panel/mod.rs
Normal file
1
crates/aero/src/panel/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-aero :: panel - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/aero/src/wind/mod.rs
Normal file
1
crates/aero/src/wind/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-aero :: wind - stub (see docs/ARCHITECTURE.md)
|
||||
16
crates/analog/Cargo.toml
Normal file
16
crates/analog/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-analog"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/analog/build.rs
Normal file
5
crates/analog/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
1
crates/analog/src/elements/mod.rs
Normal file
1
crates/analog/src/elements/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-analog :: elements - stub (see docs/ARCHITECTURE.md)
|
||||
4
crates/analog/src/lib.rs
Normal file
4
crates/analog/src/lib.rs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
//! SPICE-like circuit solver (MNA): elements, stepping, Newton
|
||||
pub mod elements;
|
||||
pub mod mna;
|
||||
pub mod solver;
|
||||
1
crates/analog/src/mna/mod.rs
Normal file
1
crates/analog/src/mna/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-analog :: mna - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/analog/src/solver/mod.rs
Normal file
1
crates/analog/src/solver/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-analog :: solver - stub (see docs/ARCHITECTURE.md)
|
||||
16
crates/analysis/Cargo.toml
Normal file
16
crates/analysis/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-analysis"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/analysis/build.rs
Normal file
5
crates/analysis/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
1
crates/analysis/src/faults/mod.rs
Normal file
1
crates/analysis/src/faults/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-analysis :: faults - stub (see docs/ARCHITECTURE.md)
|
||||
5
crates/analysis/src/lib.rs
Normal file
5
crates/analysis/src/lib.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Parameter sweeps, Monte Carlo, stability metrics, fault injection
|
||||
pub mod faults;
|
||||
pub mod metrics;
|
||||
pub mod montecarlo;
|
||||
pub mod sweep;
|
||||
1
crates/analysis/src/metrics/mod.rs
Normal file
1
crates/analysis/src/metrics/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-analysis :: metrics - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/analysis/src/montecarlo/mod.rs
Normal file
1
crates/analysis/src/montecarlo/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-analysis :: montecarlo - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/analysis/src/sweep/mod.rs
Normal file
1
crates/analysis/src/sweep/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-analysis :: sweep - stub (see docs/ARCHITECTURE.md)
|
||||
21
crates/app/Cargo.toml
Normal file
21
crates/app/Cargo.toml
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
[package]
|
||||
name = "fabrilis-app"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
fabrilis-platform = { path = "../platform" }
|
||||
fabrilis-storage = { path = "../storage" }
|
||||
fabrilis-modes = { path = "../modes" }
|
||||
fabrilis-render = { path = "../render" }
|
||||
fabrilis-ui = { path = "../ui" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/app/build.rs
Normal file
5
crates/app/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
2
crates/app/src/lib.rs
Normal file
2
crates/app/src/lib.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
//! Binary: winit, main loop, mode wiring
|
||||
pub mod runtime;
|
||||
3
crates/app/src/main.rs
Normal file
3
crates/app/src/main.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
println!("fabrilis: скелет проекта, см. TODO.md");
|
||||
}
|
||||
1
crates/app/src/runtime/mod.rs
Normal file
1
crates/app/src/runtime/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-app :: runtime - stub (see docs/ARCHITECTURE.md)
|
||||
20
crates/bridge/Cargo.toml
Normal file
20
crates/bridge/Cargo.toml
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
[package]
|
||||
name = "fabrilis-bridge"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
fabrilis-soc = { path = "../soc" }
|
||||
fabrilis-analog = { path = "../analog" }
|
||||
fabrilis-actuators = { path = "../actuators" }
|
||||
fabrilis-physics = { path = "../physics" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/bridge/build.rs
Normal file
5
crates/bridge/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
3
crates/bridge/src/lib.rs
Normal file
3
crates/bridge/src/lib.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
//! Bridge: SoC pins <-> circuit nodes <-> actuators <-> physics, sync points
|
||||
pub mod pins;
|
||||
pub mod sync;
|
||||
1
crates/bridge/src/pins/mod.rs
Normal file
1
crates/bridge/src/pins/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-bridge :: pins - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/bridge/src/sync/mod.rs
Normal file
1
crates/bridge/src/sync/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-bridge :: sync - stub (see docs/ARCHITECTURE.md)
|
||||
16
crates/core/Cargo.toml
Normal file
16
crates/core/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
libm = "0.2.16"
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/core/build.rs
Normal file
5
crates/core/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
88
crates/core/src/fidelity/mod.rs
Normal file
88
crates/core/src/fidelity/mod.rs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
//! Fidelity: per-subsystem accuracy profile. Modes are presets (docs/MODES.md).
|
||||
|
||||
use crate::time::SimDelta;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Bench,
|
||||
Lab,
|
||||
World,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CpuAccuracy {
|
||||
CycleAccurate,
|
||||
/// Batched: this many cycles per quantum, interrupts are quantized.
|
||||
Batched {
|
||||
cycles: u32,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MuscleModel {
|
||||
Simple,
|
||||
Hill,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MechanicsModel {
|
||||
RigidBody,
|
||||
BeamFem,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AeroModel {
|
||||
Coefficients,
|
||||
Panel,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Fidelity {
|
||||
pub physics_step: SimDelta,
|
||||
pub analog_step: SimDelta,
|
||||
pub cpu: CpuAccuracy,
|
||||
pub muscle: MuscleModel,
|
||||
pub mechanics: MechanicsModel,
|
||||
pub aero: AeroModel,
|
||||
}
|
||||
|
||||
impl Fidelity {
|
||||
#[must_use]
|
||||
pub const fn for_mode(mode: Mode) -> Self {
|
||||
match mode {
|
||||
Mode::Bench => Self {
|
||||
physics_step: SimDelta::from_millis(1),
|
||||
analog_step: SimDelta::from_micros(1),
|
||||
cpu: CpuAccuracy::CycleAccurate,
|
||||
muscle: MuscleModel::Simple,
|
||||
mechanics: MechanicsModel::RigidBody,
|
||||
aero: AeroModel::Coefficients,
|
||||
},
|
||||
Mode::Lab => Self {
|
||||
physics_step: SimDelta::from_micros(100),
|
||||
analog_step: SimDelta::from_micros(1),
|
||||
cpu: CpuAccuracy::CycleAccurate,
|
||||
muscle: MuscleModel::Hill,
|
||||
mechanics: MechanicsModel::BeamFem,
|
||||
aero: AeroModel::Panel,
|
||||
},
|
||||
Mode::World => Self {
|
||||
physics_step: SimDelta::from_millis(4),
|
||||
analog_step: SimDelta::from_micros(40),
|
||||
cpu: CpuAccuracy::Batched { cycles: 1000 },
|
||||
muscle: MuscleModel::Simple,
|
||||
mechanics: MechanicsModel::RigidBody,
|
||||
aero: AeroModel::Coefficients,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Scheduler epoch length: the longest of the periods.
|
||||
#[must_use]
|
||||
pub fn epoch(&self) -> SimDelta {
|
||||
self.physics_step.max(self.analog_step)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
22
crates/core/src/fidelity/tests.rs
Normal file
22
crates/core/src/fidelity/tests.rs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_period_divides_the_epoch() {
|
||||
for mode in [Mode::Bench, Mode::Lab, Mode::World] {
|
||||
let f = Fidelity::for_mode(mode);
|
||||
assert!(f.epoch().is_multiple_of(f.physics_step), "{mode:?}");
|
||||
assert!(f.epoch().is_multiple_of(f.analog_step), "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_and_lab_never_batch_the_cpu() {
|
||||
assert_eq!(
|
||||
Fidelity::for_mode(Mode::Bench).cpu,
|
||||
CpuAccuracy::CycleAccurate
|
||||
);
|
||||
assert_eq!(
|
||||
Fidelity::for_mode(Mode::Lab).cpu,
|
||||
CpuAccuracy::CycleAccurate
|
||||
);
|
||||
}
|
||||
90
crates/core/src/id/mod.rs
Normal file
90
crates/core/src/id/mod.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
//! Typed identifiers: an `Id<Part>` cannot be confused with an `Id<Joint>`.
|
||||
|
||||
use core::cmp::Ordering;
|
||||
use core::fmt;
|
||||
use core::hash::{Hash, Hasher};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
pub struct Id<T> {
|
||||
raw: u32,
|
||||
_marker: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> Id<T> {
|
||||
#[must_use]
|
||||
pub const fn from_raw(raw: u32) -> Self {
|
||||
Self {
|
||||
raw,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn raw(self) -> u32 {
|
||||
self.raw
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn index(self) -> usize {
|
||||
self.raw as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Id<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
impl<T> Copy for Id<T> {}
|
||||
impl<T> PartialEq for Id<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.raw == other.raw
|
||||
}
|
||||
}
|
||||
impl<T> Eq for Id<T> {}
|
||||
impl<T> PartialOrd for Id<T> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
impl<T> Ord for Id<T> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.raw.cmp(&other.raw)
|
||||
}
|
||||
}
|
||||
impl<T> Hash for Id<T> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.raw.hash(state);
|
||||
}
|
||||
}
|
||||
impl<T> fmt::Debug for Id<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Id({})", self.raw)
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands out sequential identifiers 0, 1, 2, ...
|
||||
pub struct IdGen<T> {
|
||||
next: u32,
|
||||
_marker: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> Default for IdGen<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
next: 0,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IdGen<T> {
|
||||
pub fn alloc(&mut self) -> Id<T> {
|
||||
let id = Id::from_raw(self.next);
|
||||
self.next += 1;
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
14
crates/core/src/id/tests.rs
Normal file
14
crates/core/src/id/tests.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
use super::*;
|
||||
|
||||
struct Part;
|
||||
|
||||
#[test]
|
||||
fn ids_are_sequential_and_ordered() {
|
||||
let mut generator = IdGen::<Part>::default();
|
||||
let a = generator.alloc();
|
||||
let b = generator.alloc();
|
||||
assert_eq!((a.raw(), b.raw()), (0, 1));
|
||||
assert!(a < b);
|
||||
assert_eq!(b.index(), 1);
|
||||
assert_eq!(format!("{a:?}"), "Id(0)");
|
||||
}
|
||||
10
crates/core/src/lib.rs
Normal file
10
crates/core/src/lib.rs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
//! SI units, simulation time (integer ns), multi-rate scheduler, Fidelity, state snapshots, deterministic math
|
||||
pub mod fidelity;
|
||||
pub mod id;
|
||||
pub mod math;
|
||||
pub mod rng;
|
||||
pub mod sched;
|
||||
pub mod snapshot;
|
||||
pub mod time;
|
||||
pub mod units;
|
||||
pub mod vec;
|
||||
125
crates/core/src/math/mod.rs
Normal file
125
crates/core/src/math/mod.rs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
//! Deterministic math.
|
||||
//!
|
||||
//! The system libm behind `std` differs between operating systems, so transcendental
|
||||
//! functions come from the pure-Rust `libm` crate. `std`'s `sqrt` is an IEEE-exact CPU operation,
|
||||
//! identical everywhere. See docs/DETERMINISM.md.
|
||||
|
||||
pub use core::f64::consts::{E, PI, TAU};
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn sin(x: f64) -> f64 {
|
||||
libm::sin(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn cos(x: f64) -> f64 {
|
||||
libm::cos(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn sin_cos(x: f64) -> (f64, f64) {
|
||||
libm::sincos(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn tan(x: f64) -> f64 {
|
||||
libm::tan(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn asin(x: f64) -> f64 {
|
||||
libm::asin(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn acos(x: f64) -> f64 {
|
||||
libm::acos(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn atan(x: f64) -> f64 {
|
||||
libm::atan(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn atan2(y: f64, x: f64) -> f64 {
|
||||
libm::atan2(y, x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn sinh(x: f64) -> f64 {
|
||||
libm::sinh(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn cosh(x: f64) -> f64 {
|
||||
libm::cosh(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn tanh(x: f64) -> f64 {
|
||||
libm::tanh(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn exp(x: f64) -> f64 {
|
||||
libm::exp(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn ln(x: f64) -> f64 {
|
||||
libm::log(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn log10(x: f64) -> f64 {
|
||||
libm::log10(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn log2(x: f64) -> f64 {
|
||||
libm::log2(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn pow(x: f64, y: f64) -> f64 {
|
||||
libm::pow(x, y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn cbrt(x: f64) -> f64 {
|
||||
libm::cbrt(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn hypot(x: f64, y: f64) -> f64 {
|
||||
libm::hypot(x, y)
|
||||
}
|
||||
|
||||
/// IEEE-exact square root (hardware, identical on all platforms).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn sqrt(x: f64) -> f64 {
|
||||
x.sqrt()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
18
crates/core/src/math/tests.rs
Normal file
18
crates/core/src/math/tests.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn basic_values() {
|
||||
assert_eq!(sin(0.0), 0.0);
|
||||
assert_eq!(cos(0.0), 1.0);
|
||||
assert_eq!(pow(2.0, 10.0), 1024.0);
|
||||
assert_eq!(sqrt(9.0), 3.0);
|
||||
assert!((atan2(1.0, 1.0) - PI / 4.0).abs() < 1e-15);
|
||||
assert!((exp(1.0) - E).abs() < 1e-15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sin_cos_matches_parts() {
|
||||
let (s, c) = sin_cos(0.7);
|
||||
assert!((s - sin(0.7)).abs() < 1e-15);
|
||||
assert!((c - cos(0.7)).abs() < 1e-15);
|
||||
}
|
||||
100
crates/core/src/rng/mod.rs
Normal file
100
crates/core/src/rng/mod.rs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
//! Deterministic seeded random numbers: xoshiro256**, seeded through SplitMix64.
|
||||
//!
|
||||
//! Only integer arithmetic, so the sequence is identical on every platform. The state
|
||||
//! will be stored in a snapshot (docs/DETERMINISM.md).
|
||||
|
||||
/// A seeded generator; the same seed always gives the same sequence.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Rng {
|
||||
state: [u64; 4],
|
||||
}
|
||||
|
||||
const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15;
|
||||
|
||||
fn split_mix(counter: &mut u64) -> u64 {
|
||||
*counter = counter.wrapping_add(GAMMA);
|
||||
let mut z = *counter;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
impl Rng {
|
||||
/// Creates a generator from a seed; every seed is valid.
|
||||
#[must_use]
|
||||
pub fn new(seed: u64) -> Self {
|
||||
let mut counter = seed;
|
||||
let mut state = [
|
||||
split_mix(&mut counter),
|
||||
split_mix(&mut counter),
|
||||
split_mix(&mut counter),
|
||||
split_mix(&mut counter),
|
||||
];
|
||||
// xoshiro cannot start from the all-zero state; split_mix never produces it
|
||||
// for a real seed, but the invariant is made explicit.
|
||||
if state == [0; 4] {
|
||||
state[0] = GAMMA;
|
||||
}
|
||||
Self { state }
|
||||
}
|
||||
|
||||
/// The next 64 random bits.
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
let result = self.state[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
|
||||
let t = self.state[1] << 17;
|
||||
self.state[2] ^= self.state[0];
|
||||
self.state[3] ^= self.state[1];
|
||||
self.state[1] ^= self.state[2];
|
||||
self.state[0] ^= self.state[3];
|
||||
self.state[2] ^= t;
|
||||
self.state[3] = self.state[3].rotate_left(45);
|
||||
result
|
||||
}
|
||||
|
||||
/// The next 32 random bits, taken from the high half of the 64-bit output.
|
||||
pub fn next_u32(&mut self) -> u32 {
|
||||
(self.next_u64() >> 32) as u32
|
||||
}
|
||||
|
||||
/// A fair coin.
|
||||
pub fn next_bool(&mut self) -> bool {
|
||||
self.next_u64() >> 63 == 1
|
||||
}
|
||||
|
||||
/// A uniform value in `[0, 1)`, with 53 bits of precision.
|
||||
pub fn next_f64(&mut self) -> f64 {
|
||||
const SCALE: f64 = 1.0 / (1u64 << 53) as f64;
|
||||
(self.next_u64() >> 11) as f64 * SCALE
|
||||
}
|
||||
|
||||
/// A uniform value in `[0, bound)` without modulo bias; `0` when `bound` is zero.
|
||||
pub fn below(&mut self, bound: u64) -> u64 {
|
||||
if bound == 0 {
|
||||
return 0;
|
||||
}
|
||||
let threshold = bound.wrapping_neg() % bound;
|
||||
loop {
|
||||
let value = self.next_u64();
|
||||
if value >= threshold {
|
||||
return value % bound;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A uniform value in `[low, high)`; `low` when the range is empty or reversed.
|
||||
pub fn range_u64(&mut self, low: u64, high: u64) -> u64 {
|
||||
if high <= low {
|
||||
low
|
||||
} else {
|
||||
low + self.below(high - low)
|
||||
}
|
||||
}
|
||||
|
||||
/// A uniform value in `[low, high)`.
|
||||
pub fn range_f64(&mut self, low: f64, high: f64) -> f64 {
|
||||
low + (high - low) * self.next_f64()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
60
crates/core/src/rng/tests.rs
Normal file
60
crates/core/src/rng/tests.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_sequence_is_pinned() {
|
||||
let mut rng = Rng::new(42);
|
||||
let expected = [
|
||||
0x1578_0b2e_0c2e_c716,
|
||||
0x6104_d986_6d11_3a7e,
|
||||
0xae17_5332_39e4_99a1,
|
||||
0xecb8_ad47_03b3_60a1,
|
||||
0xfde6_dc7f_e2ec_5e64,
|
||||
];
|
||||
for value in expected {
|
||||
assert_eq!(rng.next_u64(), value);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_seed_repeats_the_sequence() {
|
||||
let mut a = Rng::new(7);
|
||||
let mut b = Rng::new(7);
|
||||
for _ in 0..100 {
|
||||
assert_eq!(a.next_u64(), b.next_u64());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_seeds_diverge() {
|
||||
let mut a = Rng::new(1);
|
||||
let mut b = Rng::new(2);
|
||||
assert_ne!(a.next_u64(), b.next_u64());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floats_stay_in_the_unit_interval() {
|
||||
let mut rng = Rng::new(9);
|
||||
for _ in 0..10_000 {
|
||||
let value = rng.next_f64();
|
||||
assert!((0.0..1.0).contains(&value), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_is_half_open() {
|
||||
let mut rng = Rng::new(11);
|
||||
for _ in 0..1_000 {
|
||||
let value = rng.range_u64(10, 20);
|
||||
assert!((10..20).contains(&value), "{value}");
|
||||
}
|
||||
let value = rng.range_f64(-1.0, 1.0);
|
||||
assert!((-1.0..1.0).contains(&value), "{value}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_ranges_return_the_lower_bound() {
|
||||
let mut rng = Rng::new(13);
|
||||
assert_eq!(rng.below(0), 0);
|
||||
assert_eq!(rng.range_u64(5, 5), 5);
|
||||
assert_eq!(rng.range_u64(5, 1), 5);
|
||||
}
|
||||
141
crates/core/src/sched/mod.rs
Normal file
141
crates/core/src/sched/mod.rs
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
//! Multi-rate scheduler.
|
||||
//!
|
||||
//! Time is split into fixed-length epochs. Within an epoch subsystems step
|
||||
//! in order of (step start time, registration order), so the result does not
|
||||
//! depend on threads or chance. Subsystems exchange data only at
|
||||
//! sync points at the end of an epoch (see `bridge`).
|
||||
|
||||
use core::fmt;
|
||||
|
||||
use crate::time::{SimDelta, SimTime};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// A subsystem with its own step period.
|
||||
pub trait Subsystem {
|
||||
fn name(&self) -> &'static str;
|
||||
/// A step of length `dt` that starts at `now`.
|
||||
fn step(&mut self, now: SimTime, dt: SimDelta);
|
||||
}
|
||||
|
||||
/// Sync point: called at the end of every epoch.
|
||||
pub trait SyncPoint {
|
||||
fn sync(&mut self, now: SimTime);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SchedError {
|
||||
ZeroPeriod,
|
||||
PeriodDoesNotDivideEpoch { period: SimDelta, epoch: SimDelta },
|
||||
}
|
||||
|
||||
impl fmt::Display for SchedError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::ZeroPeriod => write!(f, "период должен быть больше нуля"),
|
||||
Self::PeriodDoesNotDivideEpoch { period, epoch } => write!(
|
||||
f,
|
||||
"период {} нс не делит эпоху {} нс",
|
||||
period.nanos(),
|
||||
epoch.nanos()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for SchedError {}
|
||||
|
||||
struct Slot {
|
||||
sub: Box<dyn Subsystem>,
|
||||
period: SimDelta,
|
||||
next: SimTime,
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
epoch: SimDelta,
|
||||
now: SimTime,
|
||||
slots: Vec<Slot>,
|
||||
syncs: Vec<Box<dyn SyncPoint>>,
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
/// # Errors
|
||||
/// `ZeroPeriod` if the epoch is zero.
|
||||
pub fn new(epoch: SimDelta) -> Result<Self, SchedError> {
|
||||
if epoch == SimDelta::ZERO {
|
||||
return Err(SchedError::ZeroPeriod);
|
||||
}
|
||||
Ok(Self {
|
||||
epoch,
|
||||
now: SimTime::ZERO,
|
||||
slots: Vec::new(),
|
||||
syncs: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Registers a subsystem. Registration order breaks ties in time.
|
||||
///
|
||||
/// # Errors
|
||||
/// The period is zero or does not divide the epoch evenly.
|
||||
pub fn add(&mut self, sub: Box<dyn Subsystem>, period: SimDelta) -> Result<(), SchedError> {
|
||||
if period == SimDelta::ZERO {
|
||||
return Err(SchedError::ZeroPeriod);
|
||||
}
|
||||
if !self.epoch.is_multiple_of(period) {
|
||||
return Err(SchedError::PeriodDoesNotDivideEpoch {
|
||||
period,
|
||||
epoch: self.epoch,
|
||||
});
|
||||
}
|
||||
self.slots.push(Slot {
|
||||
sub,
|
||||
period,
|
||||
next: self.now,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_sync(&mut self, sync: Box<dyn SyncPoint>) {
|
||||
self.syncs.push(sync);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn now(&self) -> SimTime {
|
||||
self.now
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn epoch(&self) -> SimDelta {
|
||||
self.epoch
|
||||
}
|
||||
|
||||
/// Index of the subsystem whose step starts earliest, before `end`.
|
||||
fn next_due(&self, end: SimTime) -> Option<usize> {
|
||||
self.slots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| s.next < end)
|
||||
.min_by_key(|(i, s)| (s.next, *i))
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
pub fn run_epoch(&mut self) {
|
||||
let end = self.now + self.epoch;
|
||||
while let Some(i) = self.next_due(end) {
|
||||
let slot = &mut self.slots[i];
|
||||
slot.sub.step(slot.next, slot.period);
|
||||
slot.next += slot.period;
|
||||
}
|
||||
self.now = end;
|
||||
for sync in &mut self.syncs {
|
||||
sync.sync(end);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_epochs(&mut self, count: u64) {
|
||||
for _ in 0..count {
|
||||
self.run_epoch();
|
||||
}
|
||||
}
|
||||
}
|
||||
79
crates/core/src/sched/tests.rs
Normal file
79
crates/core/src/sched/tests.rs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
|
||||
type Log = Rc<RefCell<Vec<String>>>;
|
||||
|
||||
struct Recorder {
|
||||
name: &'static str,
|
||||
log: Log,
|
||||
}
|
||||
|
||||
impl Subsystem for Recorder {
|
||||
fn name(&self) -> &'static str {
|
||||
self.name
|
||||
}
|
||||
fn step(&mut self, now: SimTime, _dt: SimDelta) {
|
||||
self.log
|
||||
.borrow_mut()
|
||||
.push(format!("{}@{}", self.name, now.nanos()));
|
||||
}
|
||||
}
|
||||
|
||||
struct SyncRecorder(Log);
|
||||
|
||||
impl SyncPoint for SyncRecorder {
|
||||
fn sync(&mut self, now: SimTime) {
|
||||
self.0.borrow_mut().push(format!("sync@{}", now.nanos()));
|
||||
}
|
||||
}
|
||||
|
||||
fn rec(name: &'static str, log: &Log) -> Box<Recorder> {
|
||||
Box::new(Recorder {
|
||||
name,
|
||||
log: Rc::clone(log),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_interleave_by_time_then_registration_order() {
|
||||
let log: Log = Rc::default();
|
||||
let mut s = Scheduler::new(SimDelta(4)).unwrap();
|
||||
s.add(rec("slow", &log), SimDelta(4)).unwrap();
|
||||
s.add(rec("fast", &log), SimDelta(1)).unwrap();
|
||||
s.add_sync(Box::new(SyncRecorder(Rc::clone(&log))));
|
||||
s.run_epoch();
|
||||
assert_eq!(
|
||||
*log.borrow(),
|
||||
["slow@0", "fast@0", "fast@1", "fast@2", "fast@3", "sync@4"]
|
||||
);
|
||||
assert_eq!(s.now(), SimTime(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_epoch_continues_timeline() {
|
||||
let log: Log = Rc::default();
|
||||
let mut s = Scheduler::new(SimDelta(2)).unwrap();
|
||||
s.add(rec("a", &log), SimDelta(1)).unwrap();
|
||||
s.run_epochs(2);
|
||||
assert_eq!(*log.borrow(), ["a@0", "a@1", "a@2", "a@3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_periods() {
|
||||
let log: Log = Rc::default();
|
||||
let mut s = Scheduler::new(SimDelta(4)).unwrap();
|
||||
assert_eq!(
|
||||
s.add(rec("x", &log), SimDelta(3)),
|
||||
Err(SchedError::PeriodDoesNotDivideEpoch {
|
||||
period: SimDelta(3),
|
||||
epoch: SimDelta(4)
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
s.add(rec("x", &log), SimDelta(0)),
|
||||
Err(SchedError::ZeroPeriod)
|
||||
);
|
||||
assert!(Scheduler::new(SimDelta(0)).is_err());
|
||||
}
|
||||
53
crates/core/src/snapshot/hash/mod.rs
Normal file
53
crates/core/src/snapshot/hash/mod.rs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
//! State hash (FNV-1a 64) for determinism golden tests.
|
||||
|
||||
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
const PRIME: u64 = 0x0000_0100_0000_01b3;
|
||||
/// One canonical bit pattern for every NaN.
|
||||
const CANONICAL_NAN: u64 = 0x7ff8_0000_0000_0000;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StateHasher(u64);
|
||||
|
||||
impl Default for StateHasher {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl StateHasher {
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self(OFFSET)
|
||||
}
|
||||
|
||||
pub fn write_bytes(&mut self, bytes: &[u8]) {
|
||||
for &b in bytes {
|
||||
self.0 ^= u64::from(b);
|
||||
self.0 = self.0.wrapping_mul(PRIME);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_u64(&mut self, value: u64) {
|
||||
self.write_bytes(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Hashes the bits of a number; every NaN and `-0.0` are normalized.
|
||||
pub fn write_f64(&mut self, value: f64) {
|
||||
let bits = if value.is_nan() {
|
||||
CANONICAL_NAN
|
||||
} else if value == 0.0 {
|
||||
0
|
||||
} else {
|
||||
value.to_bits()
|
||||
};
|
||||
self.write_u64(bits);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn finish(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
30
crates/core/src/snapshot/hash/tests.rs
Normal file
30
crates/core/src/snapshot/hash/tests.rs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn matches_known_fnv1a_vector() {
|
||||
let mut h = StateHasher::new();
|
||||
h.write_bytes(b"a");
|
||||
assert_eq!(h.finish(), 0xaf63_dc4c_8601_ec8c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_and_negative_zero_are_canonical() {
|
||||
let mut a = StateHasher::new();
|
||||
let mut b = StateHasher::new();
|
||||
a.write_f64(f64::NAN);
|
||||
b.write_f64(-f64::NAN);
|
||||
a.write_f64(0.0);
|
||||
b.write_f64(-0.0);
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn order_matters() {
|
||||
let mut a = StateHasher::new();
|
||||
let mut b = StateHasher::new();
|
||||
a.write_u64(1);
|
||||
a.write_u64(2);
|
||||
b.write_u64(2);
|
||||
b.write_u64(1);
|
||||
assert_ne!(a.finish(), b.finish());
|
||||
}
|
||||
59
crates/core/src/snapshot/mod.rs
Normal file
59
crates/core/src/snapshot/mod.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
//! State snapshots: a double buffer between the simulation and readers (render, UI).
|
||||
|
||||
pub mod hash;
|
||||
|
||||
use crate::time::SimTime;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct Header {
|
||||
pub tick: u64,
|
||||
pub time: SimTime,
|
||||
}
|
||||
|
||||
/// The simulation writes into `back_mut`, then `publish` exposes it to readers.
|
||||
///
|
||||
/// After `publish` the back buffer holds the previous snapshot: the writer must
|
||||
/// overwrite it completely.
|
||||
pub struct DoubleBuffer<T> {
|
||||
front: T,
|
||||
back: T,
|
||||
header: Header,
|
||||
}
|
||||
|
||||
impl<T: Clone> DoubleBuffer<T> {
|
||||
#[must_use]
|
||||
pub fn new(initial: T) -> Self {
|
||||
Self {
|
||||
front: initial.clone(),
|
||||
back: initial,
|
||||
header: Header::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DoubleBuffer<T> {
|
||||
#[must_use]
|
||||
pub fn front(&self) -> &T {
|
||||
&self.front
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn header(&self) -> Header {
|
||||
self.header
|
||||
}
|
||||
|
||||
pub fn back_mut(&mut self) -> &mut T {
|
||||
&mut self.back
|
||||
}
|
||||
|
||||
pub fn publish(&mut self, time: SimTime) {
|
||||
core::mem::swap(&mut self.front, &mut self.back);
|
||||
self.header = Header {
|
||||
tick: self.header.tick + 1,
|
||||
time,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
17
crates/core/src/snapshot/tests.rs
Normal file
17
crates/core/src/snapshot/tests.rs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn publish_swaps_and_counts() {
|
||||
let mut buf = DoubleBuffer::new(0_u32);
|
||||
*buf.back_mut() = 7;
|
||||
assert_eq!(*buf.front(), 0);
|
||||
buf.publish(SimTime(100));
|
||||
assert_eq!(*buf.front(), 7);
|
||||
assert_eq!(
|
||||
buf.header(),
|
||||
Header {
|
||||
tick: 1,
|
||||
time: SimTime(100)
|
||||
}
|
||||
);
|
||||
}
|
||||
93
crates/core/src/time/mod.rs
Normal file
93
crates/core/src/time/mod.rs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
//! Simulation time: integer nanoseconds, no float drift.
|
||||
|
||||
use core::ops::{Add, AddAssign, Sub};
|
||||
|
||||
use crate::units::Seconds;
|
||||
|
||||
pub const NS_PER_S: u64 = 1_000_000_000;
|
||||
|
||||
/// A point in simulation time, ns since the start.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||
pub struct SimTime(pub u64);
|
||||
|
||||
/// A duration, ns.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||
pub struct SimDelta(pub u64);
|
||||
|
||||
impl SimDelta {
|
||||
pub const ZERO: Self = Self(0);
|
||||
|
||||
#[must_use]
|
||||
pub const fn from_nanos(ns: u64) -> Self {
|
||||
Self(ns)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn from_micros(us: u64) -> Self {
|
||||
Self(us * 1_000)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn from_millis(ms: u64) -> Self {
|
||||
Self(ms * 1_000_000)
|
||||
}
|
||||
|
||||
/// Period of frequency `hz`; `None` if the period is not a whole number of ns.
|
||||
#[must_use]
|
||||
pub const fn from_hz(hz: u64) -> Option<Self> {
|
||||
if hz == 0 || !NS_PER_S.is_multiple_of(hz) {
|
||||
None
|
||||
} else {
|
||||
Some(Self(NS_PER_S / hz))
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn nanos(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Seconds for physics formulas. Deterministic: a single division.
|
||||
#[must_use]
|
||||
pub fn as_seconds(self) -> Seconds {
|
||||
Seconds(self.0 as f64 / NS_PER_S as f64)
|
||||
}
|
||||
|
||||
/// Whether `self` is evenly divisible by `period` (and `period > 0`).
|
||||
#[must_use]
|
||||
pub const fn is_multiple_of(self, period: Self) -> bool {
|
||||
period.0 != 0 && self.0.is_multiple_of(period.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl SimTime {
|
||||
pub const ZERO: Self = Self(0);
|
||||
|
||||
#[must_use]
|
||||
pub const fn nanos(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Add<SimDelta> for SimTime {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: SimDelta) -> Self {
|
||||
Self(self.0 + rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl AddAssign<SimDelta> for SimTime {
|
||||
fn add_assign(&mut self, rhs: SimDelta) {
|
||||
self.0 += rhs.0;
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for SimTime {
|
||||
type Output = SimDelta;
|
||||
fn sub(self, rhs: Self) -> SimDelta {
|
||||
SimDelta(self.0 - rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
23
crates/core/src/time/tests.rs
Normal file
23
crates/core/src/time/tests.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hz_must_be_whole_nanoseconds() {
|
||||
assert_eq!(SimDelta::from_hz(250), Some(SimDelta::from_millis(4)));
|
||||
assert_eq!(SimDelta::from_hz(1_000), Some(SimDelta::from_millis(1)));
|
||||
assert_eq!(SimDelta::from_hz(240), None);
|
||||
assert_eq!(SimDelta::from_hz(0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arithmetic_and_conversion() {
|
||||
let t = SimTime::ZERO + SimDelta::from_millis(3);
|
||||
assert_eq!(t - SimTime(1_000_000), SimDelta::from_millis(2));
|
||||
assert_eq!(SimDelta::from_millis(500).as_seconds(), Seconds(0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiples() {
|
||||
assert!(SimDelta::from_millis(4).is_multiple_of(SimDelta::from_micros(40)));
|
||||
assert!(!SimDelta::from_millis(4).is_multiple_of(SimDelta::from_micros(3_000)));
|
||||
assert!(!SimDelta::from_millis(4).is_multiple_of(SimDelta::ZERO));
|
||||
}
|
||||
194
crates/core/src/units/mod.rs
Normal file
194
crates/core/src/units/mod.rs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
//! SI units as newtypes over `f64`.
|
||||
//!
|
||||
//! Only identical units can be added; mixed operations
|
||||
//! (Ohm's law, power, energy) are defined explicitly below.
|
||||
|
||||
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
|
||||
|
||||
macro_rules! quantity {
|
||||
($(#[$meta:meta])* $name:ident) => {
|
||||
$(#[$meta])*
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
|
||||
pub struct $name(pub f64);
|
||||
|
||||
impl $name {
|
||||
pub const ZERO: Self = Self(0.0);
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn new(value: f64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn get(self) -> f64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for $name {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn add(self, rhs: Self) -> Self {
|
||||
Self(self.0 + rhs.0)
|
||||
}
|
||||
}
|
||||
impl Sub for $name {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn sub(self, rhs: Self) -> Self {
|
||||
Self(self.0 - rhs.0)
|
||||
}
|
||||
}
|
||||
impl Neg for $name {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn neg(self) -> Self {
|
||||
Self(-self.0)
|
||||
}
|
||||
}
|
||||
impl AddAssign for $name {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.0 += rhs.0;
|
||||
}
|
||||
}
|
||||
impl SubAssign for $name {
|
||||
#[inline]
|
||||
fn sub_assign(&mut self, rhs: Self) {
|
||||
self.0 -= rhs.0;
|
||||
}
|
||||
}
|
||||
impl Mul<f64> for $name {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn mul(self, rhs: f64) -> Self {
|
||||
Self(self.0 * rhs)
|
||||
}
|
||||
}
|
||||
impl Mul<$name> for f64 {
|
||||
type Output = $name;
|
||||
#[inline]
|
||||
fn mul(self, rhs: $name) -> $name {
|
||||
$name(self * rhs.0)
|
||||
}
|
||||
}
|
||||
impl Div<f64> for $name {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn div(self, rhs: f64) -> Self {
|
||||
Self(self.0 / rhs)
|
||||
}
|
||||
}
|
||||
impl Div for $name {
|
||||
type Output = f64;
|
||||
#[inline]
|
||||
fn div(self, rhs: Self) -> f64 {
|
||||
self.0 / rhs.0
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
quantity!(/// Length, m.
|
||||
Meters);
|
||||
quantity!(/// Mass, kg.
|
||||
Kilograms);
|
||||
quantity!(/// Time, s (for physics; the scheduler step is set in integer ns).
|
||||
Seconds);
|
||||
quantity!(/// Speed, m/s.
|
||||
MetersPerSecond);
|
||||
quantity!(/// Force, N.
|
||||
Newtons);
|
||||
quantity!(/// Pressure and material stress, Pa.
|
||||
Pascals);
|
||||
quantity!(/// Energy, J.
|
||||
Joules);
|
||||
quantity!(/// Power, W.
|
||||
Watts);
|
||||
quantity!(/// Temperature, K.
|
||||
Kelvin);
|
||||
quantity!(/// Electric potential, V.
|
||||
Volts);
|
||||
quantity!(/// Current, A.
|
||||
Amps);
|
||||
quantity!(/// Resistance, Ohm.
|
||||
Ohms);
|
||||
quantity!(/// Angle, rad.
|
||||
Radians);
|
||||
quantity!(/// Angular velocity, rad/s.
|
||||
RadiansPerSecond);
|
||||
quantity!(/// Acceleration, m/s².
|
||||
MetersPerSecondSquared);
|
||||
quantity!(/// Torque, N·m.
|
||||
NewtonMeters);
|
||||
|
||||
impl Radians {
|
||||
/// Converts degrees to radians; degrees exist only at the UI and import boundary.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn from_degrees(degrees: f64) -> Self {
|
||||
Self(degrees * core::f64::consts::PI / 180.0)
|
||||
}
|
||||
|
||||
/// The angle in degrees, for display only.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn to_degrees(self) -> f64 {
|
||||
self.0 * 180.0 / core::f64::consts::PI
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<Amps> for Volts {
|
||||
type Output = Watts;
|
||||
#[inline]
|
||||
fn mul(self, rhs: Amps) -> Watts {
|
||||
Watts(self.0 * rhs.0)
|
||||
}
|
||||
}
|
||||
impl Div<Ohms> for Volts {
|
||||
type Output = Amps;
|
||||
#[inline]
|
||||
fn div(self, rhs: Ohms) -> Amps {
|
||||
Amps(self.0 / rhs.0)
|
||||
}
|
||||
}
|
||||
impl Div<Amps> for Volts {
|
||||
type Output = Ohms;
|
||||
#[inline]
|
||||
fn div(self, rhs: Amps) -> Ohms {
|
||||
Ohms(self.0 / rhs.0)
|
||||
}
|
||||
}
|
||||
impl Mul<Seconds> for Watts {
|
||||
type Output = Joules;
|
||||
#[inline]
|
||||
fn mul(self, rhs: Seconds) -> Joules {
|
||||
Joules(self.0 * rhs.0)
|
||||
}
|
||||
}
|
||||
impl Div<Seconds> for Meters {
|
||||
type Output = MetersPerSecond;
|
||||
#[inline]
|
||||
fn div(self, rhs: Seconds) -> MetersPerSecond {
|
||||
MetersPerSecond(self.0 / rhs.0)
|
||||
}
|
||||
}
|
||||
impl Mul<Seconds> for MetersPerSecondSquared {
|
||||
type Output = MetersPerSecond;
|
||||
#[inline]
|
||||
fn mul(self, rhs: Seconds) -> MetersPerSecond {
|
||||
MetersPerSecond(self.0 * rhs.0)
|
||||
}
|
||||
}
|
||||
impl Mul<Seconds> for RadiansPerSecond {
|
||||
type Output = Radians;
|
||||
#[inline]
|
||||
fn mul(self, rhs: Seconds) -> Radians {
|
||||
Radians(self.0 * rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
41
crates/core/src/units/tests.rs
Normal file
41
crates/core/src/units/tests.rs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ohms_law_and_power() {
|
||||
let i = Volts(12.0) / Ohms(4.0);
|
||||
assert_eq!(i, Amps(3.0));
|
||||
assert_eq!(Volts(12.0) * i, Watts(36.0));
|
||||
assert_eq!(Volts(12.0) / i, Ohms(4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn energy_and_speed() {
|
||||
assert_eq!(Watts(10.0) * Seconds(3.0), Joules(30.0));
|
||||
assert_eq!(Meters(6.0) / Seconds(2.0), MetersPerSecond(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_unit_arithmetic() {
|
||||
let mut m = Kilograms(2.0) + Kilograms(3.0);
|
||||
m -= Kilograms(1.0);
|
||||
assert_eq!(m, Kilograms(4.0));
|
||||
assert_eq!(m / Kilograms(2.0), 2.0);
|
||||
assert_eq!(2.0 * m, Kilograms(8.0));
|
||||
assert_eq!(-m, Kilograms(-4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degrees_convert_to_radians() {
|
||||
let half_turn = Radians::from_degrees(180.0);
|
||||
assert!((half_turn.get() - core::f64::consts::PI).abs() < 1e-12);
|
||||
assert!((half_turn.to_degrees() - 180.0).abs() < 1e-12);
|
||||
assert_eq!(Radians(1.0) + Radians(2.0), Radians(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_motion_units() {
|
||||
let gravity = MetersPerSecondSquared(9.81);
|
||||
assert_eq!(gravity * Seconds(2.0), MetersPerSecond(19.62));
|
||||
let rate = RadiansPerSecond(3.0);
|
||||
assert_eq!(rate * Seconds(2.0), Radians(6.0));
|
||||
}
|
||||
15
crates/core/src/vec/mod.rs
Normal file
15
crates/core/src/vec/mod.rs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
//! Deterministic 3D vector math on `f64`.
|
||||
//!
|
||||
//! Trigonometry goes through [`crate::math`] (pure Rust `libm`), so results do not
|
||||
//! depend on the operating system. See docs/DETERMINISM.md.
|
||||
|
||||
mod rotation;
|
||||
mod transform;
|
||||
mod vec3;
|
||||
|
||||
pub use rotation::{Mat3, Quat};
|
||||
pub use transform::Transform;
|
||||
pub use vec3::Vec3;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
226
crates/core/src/vec/rotation.rs
Normal file
226
crates/core/src/vec/rotation.rs
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
//! Rotations: a 3×3 matrix and a unit quaternion.
|
||||
//!
|
||||
//! Both are `f64` and use [`crate::math`] for trigonometry, so results do not depend
|
||||
//! on the operating system. See docs/DETERMINISM.md.
|
||||
|
||||
use core::ops::{Div, Mul};
|
||||
|
||||
use super::Vec3;
|
||||
use crate::math;
|
||||
use crate::units::Radians;
|
||||
|
||||
/// A 3×3 matrix; column `i` is the image of the basis vector `i`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Mat3 {
|
||||
cols: [Vec3; 3],
|
||||
}
|
||||
|
||||
impl Mat3 {
|
||||
/// The identity matrix.
|
||||
pub const IDENTITY: Self = Self::from_cols(Vec3::X, Vec3::Y, Vec3::Z);
|
||||
|
||||
/// Builds a matrix from its columns.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn from_cols(x: Vec3, y: Vec3, z: Vec3) -> Self {
|
||||
Self { cols: [x, y, z] }
|
||||
}
|
||||
|
||||
/// A diagonal matrix.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn from_diagonal(diagonal: Vec3) -> Self {
|
||||
Self::from_cols(
|
||||
Vec3::new(diagonal.x, 0.0, 0.0),
|
||||
Vec3::new(0.0, diagonal.y, 0.0),
|
||||
Vec3::new(0.0, 0.0, diagonal.z),
|
||||
)
|
||||
}
|
||||
|
||||
/// The columns.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn cols(self) -> [Vec3; 3] {
|
||||
self.cols
|
||||
}
|
||||
|
||||
/// The transposed matrix.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn transpose(self) -> Self {
|
||||
let [x, y, z] = self.cols;
|
||||
Self::from_cols(
|
||||
Vec3::new(x.x, y.x, z.x),
|
||||
Vec3::new(x.y, y.y, z.y),
|
||||
Vec3::new(x.z, y.z, z.z),
|
||||
)
|
||||
}
|
||||
|
||||
/// The determinant.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn determinant(self) -> f64 {
|
||||
let [a, b, c] = self.cols;
|
||||
a.dot(b.cross(c))
|
||||
}
|
||||
|
||||
/// The inverse, or `None` for a singular or non-finite matrix.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn inverse(self) -> Option<Self> {
|
||||
let [a, b, c] = self.cols;
|
||||
let det = self.determinant();
|
||||
if det == 0.0 || !det.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let inv_det = 1.0 / det;
|
||||
let r0 = b.cross(c);
|
||||
let r1 = c.cross(a);
|
||||
let r2 = a.cross(b);
|
||||
Some(Self::from_cols(
|
||||
Vec3::new(r0.x, r1.x, r2.x) * inv_det,
|
||||
Vec3::new(r0.y, r1.y, r2.y) * inv_det,
|
||||
Vec3::new(r0.z, r1.z, r2.z) * inv_det,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<Vec3> for Mat3 {
|
||||
type Output = Vec3;
|
||||
|
||||
#[inline]
|
||||
fn mul(self, rhs: Vec3) -> Vec3 {
|
||||
let [a, b, c] = self.cols;
|
||||
a * rhs.x + b * rhs.y + c * rhs.z
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<Mat3> for Mat3 {
|
||||
type Output = Self;
|
||||
|
||||
#[inline]
|
||||
fn mul(self, rhs: Mat3) -> Self {
|
||||
let [x, y, z] = rhs.cols;
|
||||
Self::from_cols(self * x, self * y, self * z)
|
||||
}
|
||||
}
|
||||
|
||||
/// A rotation as a quaternion `w + xi + yj + zk`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Quat {
|
||||
pub w: f64,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub z: f64,
|
||||
}
|
||||
|
||||
impl Quat {
|
||||
/// The identity rotation.
|
||||
pub const IDENTITY: Self = Self::new(1.0, 0.0, 0.0, 0.0);
|
||||
|
||||
/// Builds a quaternion from its components; it is not normalized here.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn new(w: f64, x: f64, y: f64, z: f64) -> Self {
|
||||
Self { w, x, y, z }
|
||||
}
|
||||
|
||||
/// A rotation of `angle` around `axis`, or `None` for a zero axis.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn from_axis_angle(axis: Vec3, angle: Radians) -> Option<Self> {
|
||||
let axis = axis.normalized()?;
|
||||
let (sin, cos) = math::sin_cos(angle.get() * 0.5);
|
||||
Some(Self::new(cos, axis.x * sin, axis.y * sin, axis.z * sin))
|
||||
}
|
||||
|
||||
/// The squared norm; `1.0` for a unit quaternion.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn norm_squared(self) -> f64 {
|
||||
self.w * self.w + self.x * self.x + self.y * self.y + self.z * self.z
|
||||
}
|
||||
|
||||
/// The negation of the vector part, which is the inverse for a unit quaternion.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn conjugate(self) -> Self {
|
||||
Self::new(self.w, -self.x, -self.y, -self.z)
|
||||
}
|
||||
|
||||
/// The inverse, or `None` for the zero quaternion.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn inverse(self) -> Option<Self> {
|
||||
let norm_squared = self.norm_squared();
|
||||
if norm_squared > 0.0 && norm_squared.is_finite() {
|
||||
Some(self.conjugate() / norm_squared)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit quaternion, or `None` for the zero quaternion.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn normalize(self) -> Option<Self> {
|
||||
let norm_squared = self.norm_squared();
|
||||
if norm_squared > 0.0 && norm_squared.is_finite() {
|
||||
Some(self / math::sqrt(norm_squared))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotates a vector; a non-unit quaternion is normalized first.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn rotate(self, v: Vec3) -> Vec3 {
|
||||
let Some(unit) = self.normalize() else {
|
||||
return v;
|
||||
};
|
||||
let qv = Vec3::new(unit.x, unit.y, unit.z);
|
||||
let t = qv.cross(v) * 2.0;
|
||||
v + t * unit.w + qv.cross(t)
|
||||
}
|
||||
|
||||
/// The rotation matrix equivalent to this rotation.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn to_mat3(self) -> Mat3 {
|
||||
let Some(q) = self.normalize() else {
|
||||
return Mat3::IDENTITY;
|
||||
};
|
||||
let (w, x, y, z) = (q.w, q.x, q.y, q.z);
|
||||
let (xx, yy, zz) = (x * x, y * y, z * z);
|
||||
let (xy, xz, yz) = (x * y, x * z, y * z);
|
||||
let (wx, wy, wz) = (w * x, w * y, w * z);
|
||||
Mat3::from_cols(
|
||||
Vec3::new(1.0 - 2.0 * (yy + zz), 2.0 * (xy + wz), 2.0 * (xz - wy)),
|
||||
Vec3::new(2.0 * (xy - wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz + wx)),
|
||||
Vec3::new(2.0 * (xz + wy), 2.0 * (yz - wx), 1.0 - 2.0 * (xx + yy)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul for Quat {
|
||||
type Output = Self;
|
||||
|
||||
/// Composition: `(a * b).rotate(v) == a.rotate(b.rotate(v))`.
|
||||
#[inline]
|
||||
fn mul(self, rhs: Self) -> Self {
|
||||
let a = Vec3::new(self.x, self.y, self.z);
|
||||
let b = Vec3::new(rhs.x, rhs.y, rhs.z);
|
||||
let vector = b * self.w + a * rhs.w + a.cross(b);
|
||||
Self::new(self.w * rhs.w - a.dot(b), vector.x, vector.y, vector.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Div<f64> for Quat {
|
||||
type Output = Self;
|
||||
|
||||
#[inline]
|
||||
fn div(self, rhs: f64) -> Self {
|
||||
Self::new(self.w / rhs, self.x / rhs, self.y / rhs, self.z / rhs)
|
||||
}
|
||||
}
|
||||
230
crates/core/src/vec/tests.rs
Normal file
230
crates/core/src/vec/tests.rs
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
use super::*;
|
||||
use crate::units::Radians;
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-12
|
||||
}
|
||||
|
||||
fn assert_vec(actual: Vec3, expected: Vec3) {
|
||||
assert!(
|
||||
close(actual.x, expected.x) && close(actual.y, expected.y) && close(actual.z, expected.z),
|
||||
"{actual:?} != {expected:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_and_cross_follow_the_right_hand_rule() {
|
||||
let x = Vec3::X;
|
||||
let y = Vec3::Y;
|
||||
assert_eq!(x.dot(y), 0.0);
|
||||
assert_eq!(x.cross(y), Vec3::Z);
|
||||
assert_eq!(y.cross(x), -Vec3::Z);
|
||||
assert_eq!(x.dot(x), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_of_parallel_vectors_is_zero() {
|
||||
let v = Vec3::new(1.0, 2.0, 3.0);
|
||||
assert_eq!(v.cross(v), Vec3::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_and_normalize() {
|
||||
let v = Vec3::new(3.0, 4.0, 0.0);
|
||||
assert_eq!(v.length(), 5.0);
|
||||
assert_eq!(v.length_squared(), 25.0);
|
||||
let unit = v.normalized().expect("a non-zero vector normalizes");
|
||||
assert!(close(unit.length(), 1.0));
|
||||
assert!(close(unit.x, 0.6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_vector_does_not_normalize() {
|
||||
assert_eq!(Vec3::ZERO.normalized(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_arithmetic() {
|
||||
let a = Vec3::new(1.0, 2.0, 3.0);
|
||||
let b = Vec3::new(4.0, 5.0, 6.0);
|
||||
assert_eq!(a + b, Vec3::new(5.0, 7.0, 9.0));
|
||||
assert_eq!(b - a, Vec3::new(3.0, 3.0, 3.0));
|
||||
assert_eq!(a * 2.0, Vec3::new(2.0, 4.0, 6.0));
|
||||
assert_eq!(2.0 * a, Vec3::new(2.0, 4.0, 6.0));
|
||||
assert_eq!(-a, Vec3::new(-1.0, -2.0, -3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_leaves_vectors_alone() {
|
||||
let v = Vec3::new(1.0, -2.0, 3.5);
|
||||
assert_eq!(Mat3::IDENTITY * v, v);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_are_the_images_of_the_basis() {
|
||||
let m = Mat3::from_cols(Vec3::Y, Vec3::Z, Vec3::X);
|
||||
assert_eq!(m * Vec3::X, Vec3::Y);
|
||||
assert_eq!(m * Vec3::Y, Vec3::Z);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transpose_and_determinant() {
|
||||
let m = Mat3::from_cols(
|
||||
Vec3::new(1.0, 2.0, 3.0),
|
||||
Vec3::new(0.0, 1.0, 4.0),
|
||||
Vec3::new(5.0, 6.0, 0.0),
|
||||
);
|
||||
assert_eq!(m.determinant(), 1.0);
|
||||
assert_eq!(m.transpose().transpose(), m);
|
||||
let scaled = Mat3::from_diagonal(Vec3::new(2.0, 3.0, 4.0));
|
||||
assert_eq!(scaled.determinant(), 24.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_round_trip() {
|
||||
let m = Mat3::from_cols(
|
||||
Vec3::new(2.0, 0.0, 0.0),
|
||||
Vec3::new(0.0, 3.0, 0.0),
|
||||
Vec3::new(1.0, 0.0, 4.0),
|
||||
);
|
||||
let inv = m.inverse().expect("the matrix is invertible");
|
||||
let identity = m * inv;
|
||||
for (actual, expected) in [
|
||||
(identity * Vec3::X, Vec3::X),
|
||||
(identity * Vec3::Y, Vec3::Y),
|
||||
(identity * Vec3::Z, Vec3::Z),
|
||||
] {
|
||||
assert!(close(actual.x, expected.x));
|
||||
assert!(close(actual.y, expected.y));
|
||||
assert!(close(actual.z, expected.z));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn singular_matrix_has_no_inverse() {
|
||||
assert_eq!(
|
||||
Mat3::from_diagonal(Vec3::new(1.0, 0.0, 1.0)).inverse(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_product_matches_sequential_application() {
|
||||
let a = Mat3::from_diagonal(Vec3::new(2.0, 3.0, 4.0));
|
||||
let b = Mat3::from_cols(Vec3::Y, Vec3::Z, Vec3::X);
|
||||
let v = Vec3::new(1.0, 2.0, 3.0);
|
||||
assert_eq!((a * b) * v, a * (b * v));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_rotates_nothing() {
|
||||
assert_vec(Quat::IDENTITY.rotate(Vec3::X), Vec3::X);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quarter_turn_about_z_maps_x_to_y() {
|
||||
let q = Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis is non-zero");
|
||||
assert_vec(q.rotate(Vec3::X), Vec3::Y);
|
||||
assert_vec(q.rotate(Vec3::Y), -Vec3::X);
|
||||
assert_vec(q.rotate(Vec3::Z), Vec3::Z);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_turn_about_an_axis_maps_the_opposite_way() {
|
||||
let q = Quat::from_axis_angle(Vec3::X, Radians::from_degrees(180.0)).expect("axis is non-zero");
|
||||
assert_vec(q.rotate(Vec3::Y), -Vec3::Y);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_axis_is_rejected() {
|
||||
assert_eq!(Quat::from_axis_angle(Vec3::ZERO, Radians(1.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_applies_the_right_factor_first() {
|
||||
let x90 = Quat::from_axis_angle(Vec3::X, Radians::from_degrees(90.0)).expect("axis");
|
||||
let z90 = Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis");
|
||||
let v = Vec3::Y;
|
||||
assert_vec((z90 * x90).rotate(v), z90.rotate(x90.rotate(v)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_undoes_the_rotation() {
|
||||
let q = Quat::from_axis_angle(Vec3::new(1.0, 2.0, 3.0), Radians(0.7)).expect("axis");
|
||||
let v = Vec3::new(1.0, -2.0, 0.5);
|
||||
let back = q
|
||||
.inverse()
|
||||
.expect("a unit quaternion is invertible")
|
||||
.rotate(q.rotate(v));
|
||||
assert_vec(back, v);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_mat3_matches_rotate() {
|
||||
let q = Quat::from_axis_angle(Vec3::new(1.0, 1.0, 0.0), Radians(0.3)).expect("axis");
|
||||
let v = Vec3::new(0.5, 2.0, -1.0);
|
||||
assert_vec(q.to_mat3() * v, q.rotate(v));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalization_scales_to_unit_length() {
|
||||
let q = Quat::new(2.0, 0.0, 0.0, 0.0);
|
||||
let unit = q.normalize().expect("non-zero quaternion");
|
||||
assert!(close(unit.w, 1.0));
|
||||
assert_eq!(Quat::new(0.0, 0.0, 0.0, 0.0).normalize(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_maps_everything_to_itself() {
|
||||
let p = Vec3::new(1.0, 2.0, 3.0);
|
||||
assert_vec(Transform::IDENTITY.transform_point(p), p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_is_rotated_then_translated() {
|
||||
let t = Transform::new(
|
||||
Vec3::new(10.0, 0.0, 0.0),
|
||||
Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"),
|
||||
);
|
||||
assert_vec(t.transform_point(Vec3::X), Vec3::new(10.0, 1.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_ignores_translation() {
|
||||
let t = Transform::new(
|
||||
Vec3::new(10.0, 0.0, 0.0),
|
||||
Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"),
|
||||
);
|
||||
assert_vec(t.transform_vector(Vec3::X), Vec3::Y);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_matches_sequential_application() {
|
||||
let a = Transform::new(
|
||||
Vec3::new(1.0, 0.0, 0.0),
|
||||
Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"),
|
||||
);
|
||||
let b = Transform::new(
|
||||
Vec3::new(0.0, 2.0, 0.0),
|
||||
Quat::from_axis_angle(Vec3::X, Radians::from_degrees(45.0)).expect("axis"),
|
||||
);
|
||||
let p = Vec3::new(0.3, -0.4, 0.5);
|
||||
assert_vec(
|
||||
(a * b).transform_point(p),
|
||||
a.transform_point(b.transform_point(p)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_round_trip_of_the_transform() {
|
||||
let t = Transform::new(
|
||||
Vec3::new(1.0, -2.0, 3.0),
|
||||
Quat::from_axis_angle(Vec3::new(1.0, 1.0, 1.0), Radians(0.9)).expect("axis"),
|
||||
);
|
||||
let p = Vec3::new(-0.5, 0.25, 2.0);
|
||||
let back = t
|
||||
.inverse()
|
||||
.expect("unit rotation inverts")
|
||||
.transform_point(t.transform_point(p));
|
||||
assert_vec(back, p);
|
||||
}
|
||||
59
crates/core/src/vec/transform.rs
Normal file
59
crates/core/src/vec/transform.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
//! A rigid transform: rotation followed by translation.
|
||||
|
||||
use core::ops::Mul;
|
||||
|
||||
use super::{Quat, Vec3};
|
||||
|
||||
/// A position and an orientation; the canonical placement of a rigid body.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Transform {
|
||||
pub position: Vec3,
|
||||
pub rotation: Quat,
|
||||
}
|
||||
|
||||
impl Transform {
|
||||
/// The origin with no rotation.
|
||||
pub const IDENTITY: Self = Self::new(Vec3::ZERO, Quat::IDENTITY);
|
||||
|
||||
/// Builds a transform from a position and an orientation.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn new(position: Vec3, rotation: Quat) -> Self {
|
||||
Self { position, rotation }
|
||||
}
|
||||
|
||||
/// Maps a point from local space to the space this transform lives in.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn transform_point(self, point: Vec3) -> Vec3 {
|
||||
self.rotation.rotate(point) + self.position
|
||||
}
|
||||
|
||||
/// Rotates a direction; translation does not apply.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn transform_vector(self, vector: Vec3) -> Vec3 {
|
||||
self.rotation.rotate(vector)
|
||||
}
|
||||
|
||||
/// The inverse transform, or `None` for a zero rotation.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn inverse(self) -> Option<Self> {
|
||||
let rotation = self.rotation.inverse()?;
|
||||
Some(Self::new(-rotation.rotate(self.position), rotation))
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul for Transform {
|
||||
type Output = Self;
|
||||
|
||||
/// Composition: `(a * b).transform_point(p) == a.transform_point(b.transform_point(p))`.
|
||||
#[inline]
|
||||
fn mul(self, rhs: Self) -> Self {
|
||||
Self::new(
|
||||
self.transform_point(rhs.position),
|
||||
self.rotation * rhs.rotation,
|
||||
)
|
||||
}
|
||||
}
|
||||
151
crates/core/src/vec/vec3.rs
Normal file
151
crates/core/src/vec/vec3.rs
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
//! A 3D vector on `f64`, deterministic by construction: no `std` transcendental
|
||||
//! functions, only `fabrilis_core::math`.
|
||||
|
||||
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
|
||||
|
||||
use crate::math;
|
||||
|
||||
/// A point or direction in 3D space, metres unless stated otherwise.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct Vec3 {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub z: f64,
|
||||
}
|
||||
|
||||
impl Vec3 {
|
||||
/// The zero vector.
|
||||
pub const ZERO: Self = Self::new(0.0, 0.0, 0.0);
|
||||
/// The unit vector along X.
|
||||
pub const X: Self = Self::new(1.0, 0.0, 0.0);
|
||||
/// The unit vector along Y.
|
||||
pub const Y: Self = Self::new(0.0, 1.0, 0.0);
|
||||
/// The unit vector along Z.
|
||||
pub const Z: Self = Self::new(0.0, 0.0, 1.0);
|
||||
|
||||
/// Builds a vector from its components.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn new(x: f64, y: f64, z: f64) -> Self {
|
||||
Self { x, y, z }
|
||||
}
|
||||
|
||||
/// The dot product.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn dot(self, rhs: Self) -> f64 {
|
||||
self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
|
||||
}
|
||||
|
||||
/// The cross product; follows the right-hand rule.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn cross(self, rhs: Self) -> Self {
|
||||
Self::new(
|
||||
self.y * rhs.z - self.z * rhs.y,
|
||||
self.z * rhs.x - self.x * rhs.z,
|
||||
self.x * rhs.y - self.y * rhs.x,
|
||||
)
|
||||
}
|
||||
|
||||
/// The squared length, cheaper than `length` when only comparisons are needed.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn length_squared(self) -> f64 {
|
||||
self.dot(self)
|
||||
}
|
||||
|
||||
/// The Euclidean length.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn length(self) -> f64 {
|
||||
math::sqrt(self.length_squared())
|
||||
}
|
||||
|
||||
/// The unit vector, or `None` for the zero vector and non-finite input.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn normalized(self) -> Option<Self> {
|
||||
let len = self.length();
|
||||
if len > 0.0 && len.is_finite() {
|
||||
Some(self / len)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// True when every component is finite.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn is_finite(self) -> bool {
|
||||
self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
#[inline]
|
||||
fn add(self, rhs: Self) -> Self {
|
||||
Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
#[inline]
|
||||
fn sub(self, rhs: Self) -> Self {
|
||||
Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Neg for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
#[inline]
|
||||
fn neg(self) -> Self {
|
||||
Self::new(-self.x, -self.y, -self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<f64> for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
#[inline]
|
||||
fn mul(self, rhs: f64) -> Self {
|
||||
Self::new(self.x * rhs, self.y * rhs, self.z * rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<Vec3> for f64 {
|
||||
type Output = Vec3;
|
||||
|
||||
#[inline]
|
||||
fn mul(self, rhs: Vec3) -> Vec3 {
|
||||
rhs * self
|
||||
}
|
||||
}
|
||||
|
||||
impl Div<f64> for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
#[inline]
|
||||
fn div(self, rhs: f64) -> Self {
|
||||
Self::new(self.x / rhs, self.y / rhs, self.z / rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl AddAssign for Vec3 {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
*self = *self + rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl SubAssign for Vec3 {
|
||||
#[inline]
|
||||
fn sub_assign(&mut self, rhs: Self) {
|
||||
*self = *self - rhs;
|
||||
}
|
||||
}
|
||||
69
crates/core/tests/determinism.rs
Normal file
69
crates/core/tests/determinism.rs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
//! Determinism golden test: the trajectory hash must not change between runs,
|
||||
//! operating systems or versions. If it changed on purpose, update GOLDEN and explain why in the commit.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
reason = "test helper: a failure should abort the test"
|
||||
)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use fabrilis_core::fidelity::{Fidelity, Mode};
|
||||
use fabrilis_core::math;
|
||||
use fabrilis_core::sched::{Scheduler, Subsystem};
|
||||
use fabrilis_core::snapshot::hash::StateHasher;
|
||||
use fabrilis_core::time::{SimDelta, SimTime};
|
||||
|
||||
const GOLDEN: u64 = 0xdd62_00fc_171e_65e1;
|
||||
|
||||
struct Oscillator {
|
||||
id: u64,
|
||||
phase: f64,
|
||||
hasher: Rc<RefCell<StateHasher>>,
|
||||
}
|
||||
|
||||
impl Subsystem for Oscillator {
|
||||
fn name(&self) -> &'static str {
|
||||
"oscillator"
|
||||
}
|
||||
|
||||
fn step(&mut self, now: SimTime, dt: SimDelta) {
|
||||
let dt = dt.as_seconds().get();
|
||||
self.phase += dt * 50.0 * math::exp(-self.phase * 0.001);
|
||||
let value = math::sin(self.phase) * math::cos(self.phase * 0.5);
|
||||
let mut h = self.hasher.borrow_mut();
|
||||
h.write_u64(self.id);
|
||||
h.write_u64(now.nanos());
|
||||
h.write_f64(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(mode: Mode, epochs: u64) -> u64 {
|
||||
let fidelity = Fidelity::for_mode(mode);
|
||||
let hasher = Rc::new(RefCell::new(StateHasher::new()));
|
||||
let mut s = Scheduler::new(fidelity.epoch()).unwrap();
|
||||
for (id, period) in [(0, fidelity.physics_step), (1, fidelity.analog_step)] {
|
||||
let sub = Oscillator {
|
||||
id,
|
||||
phase: 0.1,
|
||||
hasher: Rc::clone(&hasher),
|
||||
};
|
||||
s.add(Box::new(sub), period).unwrap();
|
||||
}
|
||||
s.run_epochs(epochs);
|
||||
hasher.borrow().finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_runs_are_identical() {
|
||||
for mode in [Mode::Bench, Mode::Lab, Mode::World] {
|
||||
assert_eq!(run(mode, 50), run(mode, 50), "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_trajectory_matches_golden() {
|
||||
let hash = run(Mode::World, 250);
|
||||
assert_eq!(hash, GOLDEN, "новый хеш: {hash:#018x}");
|
||||
}
|
||||
16
crates/cpu/Cargo.toml
Normal file
16
crates/cpu/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-cpu"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/cpu/build.rs
Normal file
5
crates/cpu/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
1
crates/cpu/src/api/mod.rs
Normal file
1
crates/cpu/src/api/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-cpu :: api - stub (see docs/ARCHITECTURE.md)
|
||||
3
crates/cpu/src/lib.rs
Normal file
3
crates/cpu/src/lib.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
//! Cpu trait and implementations: riscv (RV32IMAC, RV64GC), arm/avr later
|
||||
pub mod api;
|
||||
pub mod riscv;
|
||||
1
crates/cpu/src/riscv/csr/mod.rs
Normal file
1
crates/cpu/src/riscv/csr/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-cpu :: riscv/csr - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/cpu/src/riscv/decode/mod.rs
Normal file
1
crates/cpu/src/riscv/decode/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-cpu :: riscv/decode - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/cpu/src/riscv/exec/mod.rs
Normal file
1
crates/cpu/src/riscv/exec/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-cpu :: riscv/exec - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/cpu/src/riscv/mmu/mod.rs
Normal file
1
crates/cpu/src/riscv/mmu/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-cpu :: riscv/mmu - stub (see docs/ARCHITECTURE.md)
|
||||
5
crates/cpu/src/riscv/mod.rs
Normal file
5
crates/cpu/src/riscv/mod.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! fabrilis-cpu :: riscv - stub (see docs/ARCHITECTURE.md)
|
||||
pub mod csr;
|
||||
pub mod decode;
|
||||
pub mod exec;
|
||||
pub mod mmu;
|
||||
16
crates/materials/Cargo.toml
Normal file
16
crates/materials/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-materials"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/materials/build.rs
Normal file
5
crates/materials/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
1
crates/materials/src/db/mod.rs
Normal file
1
crates/materials/src/db/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-materials :: db - stub (see docs/ARCHITECTURE.md)
|
||||
4
crates/materials/src/lib.rs
Normal file
4
crates/materials/src/lib.rs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
//! Material database, mass/volume/COM/inertia tensor from a mesh, strength
|
||||
pub mod db;
|
||||
pub mod massprops;
|
||||
pub mod strength;
|
||||
1
crates/materials/src/massprops/mod.rs
Normal file
1
crates/materials/src/massprops/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-materials :: massprops - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/materials/src/strength/mod.rs
Normal file
1
crates/materials/src/strength/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-materials :: strength - stub (see docs/ARCHITECTURE.md)
|
||||
32
crates/modes/Cargo.toml
Normal file
32
crates/modes/Cargo.toml
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
[package]
|
||||
name = "fabrilis-modes"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
fabrilis-platform = { path = "../platform" }
|
||||
fabrilis-storage = { path = "../storage" }
|
||||
fabrilis-scene = { path = "../scene" }
|
||||
fabrilis-parts = { path = "../parts" }
|
||||
fabrilis-physics = { path = "../physics" }
|
||||
fabrilis-structure = { path = "../structure" }
|
||||
fabrilis-thermal = { path = "../thermal" }
|
||||
fabrilis-wiring = { path = "../wiring" }
|
||||
fabrilis-aero = { path = "../aero" }
|
||||
fabrilis-actuators = { path = "../actuators" }
|
||||
fabrilis-analog = { path = "../analog" }
|
||||
fabrilis-cpu = { path = "../cpu" }
|
||||
fabrilis-soc = { path = "../soc" }
|
||||
fabrilis-bridge = { path = "../bridge" }
|
||||
fabrilis-worldgen = { path = "../worldgen" }
|
||||
fabrilis-scripting = { path = "../scripting" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/modes/build.rs
Normal file
5
crates/modes/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
1
crates/modes/src/bench/mod.rs
Normal file
1
crates/modes/src/bench/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-modes :: bench - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/modes/src/lab/mod.rs
Normal file
1
crates/modes/src/lab/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-modes :: lab - stub (see docs/ARCHITECTURE.md)
|
||||
5
crates/modes/src/lib.rs
Normal file
5
crates/modes/src/lib.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Bench / Lab / World modes as Fidelity presets
|
||||
pub mod bench;
|
||||
pub mod lab;
|
||||
pub mod presets;
|
||||
pub mod world;
|
||||
1
crates/modes/src/presets/mod.rs
Normal file
1
crates/modes/src/presets/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-modes :: presets - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/modes/src/world/mod.rs
Normal file
1
crates/modes/src/world/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-modes :: world - stub (see docs/ARCHITECTURE.md)
|
||||
18
crates/parts/Cargo.toml
Normal file
18
crates/parts/Cargo.toml
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
[package]
|
||||
name = "fabrilis-parts"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
fabrilis-materials = { path = "../materials" }
|
||||
fabrilis-scene = { path = "../scene" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/parts/build.rs
Normal file
5
crates/parts/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
1
crates/parts/src/bom/mod.rs
Normal file
1
crates/parts/src/bom/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-parts :: bom - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/parts/src/def/mod.rs
Normal file
1
crates/parts/src/def/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-parts :: def - stub (see docs/ARCHITECTURE.md)
|
||||
5
crates/parts/src/lib.rs
Normal file
5
crates/parts/src/lib.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Part library: data plus plugins, registry, BOM for real-world builds
|
||||
pub mod bom;
|
||||
pub mod def;
|
||||
pub mod plugin;
|
||||
pub mod registry;
|
||||
1
crates/parts/src/plugin/mod.rs
Normal file
1
crates/parts/src/plugin/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-parts :: plugin - stub (see docs/ARCHITECTURE.md)
|
||||
1
crates/parts/src/registry/mod.rs
Normal file
1
crates/parts/src/registry/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! fabrilis-parts :: registry - stub (see docs/ARCHITECTURE.md)
|
||||
16
crates/physics/Cargo.toml
Normal file
16
crates/physics/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "fabrilis-physics"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
fabrilis-core = { path = "../core" }
|
||||
|
||||
[build-dependencies]
|
||||
fabrilis-limits = { path = "../../tools/limits" }
|
||||
5
crates/physics/build.rs
Normal file
5
crates/physics/build.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! Enforces the repository rules at build time (see tools/limits).
|
||||
|
||||
fn main() {
|
||||
fabrilis_limits::enforce_crate();
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue