Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions rust-apps/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,14 @@ the real Files binary over an `AF_UNIX` socket. See `pagh-ui/README.md`,
`rust-apps/tinygl` vendors upstream **TinyGL 0.4.1** (MIT, Fabrice Bellard) and
wraps it in a thin Rust FFI layer. It renders **on the CPU only** into a dense
`0x00RRGGBB` (`XRGB8888`) buffer — the compositor's pixel format — so a client
can draw straight into its memfd and commit damage. Status: **PR1 build-probe + PR2 FFI
core, headless.** PR1 proved upstream C 0.4.1 builds for musl, links static-pie and produces
the reference pixels (a strict digest); PR2 adds the safe layer (context, viewport/clear,
matrix stack, immediate-mode primitives, depth/cull, `ZB_resize`). No desktop demo and no
compositor integration yet — that is the next PR, and the system build (`build-rust-app.sh`)
is still unchanged.
can draw straight into its memfd and commit damage. Status: **PR1 build-probe +
PR2 FFI core + PR3 textures/display lists** are merged; PR5 adds fixed-function
lighting (`glLightfv`/`glMaterialfv`) and the `pagh-gl-demo` client below. PR1
proved upstream C 0.4.1 builds for musl, links static-pie and produces the
reference pixels (a strict digest); PR2 added the safe layer (context,
viewport/clear, matrix stack, immediate-mode primitives, depth/cull,
`ZB_resize`). No GPU/DRM, and the system build (`build-rust-app.sh`) is still
unchanged.

Honest limits: fixed-function GL 1.1 subset, no shaders/GLSL/GL 2.0+, no
FBO/VBO/`glDrawArrays`, 16-bit Z, `stride == width*4`, `width % 4 == 0`,
Expand All @@ -83,3 +85,26 @@ The musl build needs a C compiler for `x86_64-unknown-linux-musl`
it and prints the install instructions if missing. The ELF is static-pie
(`INTERP` gate: `tinygl-probe --check-interp` plus the existing
`tools/build-rust-app.sh` check).


## CPU TinyGL demo: `pagh-gl-demo`

`rust-apps/pagh-gl-demo` is the PDP/1 client that renders the three CPU scenes
(`triangle`, `cube`, `gears`) **straight into the window's
`mmap(MAP_SHARED)` memfd** through `tinygl`; only `COMMIT` + `DAMAGE` travel
over the socket (PDP/1 `ShmSurface`, no frame copy). Frames are indexed, not
timed: frame `n` has a fixed angle, so FNV-1a pixel digests are reproducible on
the host, in QEMU and on musl. Without `--connect` it runs headless into
`Vec<u32>` and prints `TINYGL <scene> frame=<n> digest=0x…`; with `--connect
/tmp/pagh-desktop.sock` it opens a live window.

```bash
cd rust-apps/pagh-gl-demo && cargo test
cargo run --bin pagh-gl-demo -- gears --hash
tools/build-rust-app.sh rust-apps/pagh-gl-demo # static-pie musl
```

Honest limits (also in its README): CPU only, fixed-function GL 1.1 subset,
16-bit Z, `stride == width*4`, `width % 4 == 0`, one GL context per process,
and no full-frame fallback — a compositor without `ShmSurface` makes the demo
fail with an explicit error.
11 changes: 11 additions & 0 deletions rust-apps/pagh-gl-demo/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Демо — обычное host/musl std-приложение, а не часть bare-metal ядра.
# Корневой `.cargo/config.toml` задаёт target x86_64-unknown-none.json и
# -Zbuild-std; cargo обходит дерево вверх и складывает массивы build-std,
# поэтому здесь (как в `rust-apps/pagh-ui/.cargo/config.toml`) переопределяем
# target и дополняем набор до полного std, чтобы std и core собирались из
# одного исходника. Для другой архитектуры хоста: cargo test --target <triple>.
[build]
target = "x86_64-unknown-linux-gnu"

[unstable]
build-std = ["std", "panic_abort"]
42 changes: 42 additions & 0 deletions rust-apps/pagh-gl-demo/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 46 additions & 0 deletions rust-apps/pagh-gl-demo/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
[package]
name = "pagh-gl-demo"
version = "0.1.0"
edition = "2021"
publish = false
license = "MIT"
description = "CPU TinyGL demo for Pagh-OS: triangle/cube/gears rendered straight into a PDP/1 ShmSurface"

# Отдельный workspace: корневой workspace собирает bare-metal ядро под
# кастомный target и с -Zbuild-std (см. корневой .cargo/config.toml), а
# пользовательские приложения собираются под хост (тесты) и статический musl.
[workspace]

[lib]
name = "pagh_gl_demo"
path = "src/lib.rs"

[[bin]]
name = "pagh-gl-demo"
path = "src/main.rs"

[dependencies]
# Безопасная обёртка над vendored upstream TinyGL 0.4.1 (MIT) + C-растеризатор.
tinygl = { path = "../tinygl" }
# Клиентская половина PDP/1: ShmSurface (memfd/mmap/SCM_RIGHTS), протокол,
# damage. Композитор не трогаем — только публичный протокол.
pagh-ui = { path = "../pagh-ui" }

[dev-dependencies]
# Только для e2e: поднимаем реальный headless-композитор host-сборкой и
# подключаем к нему собранный бинарник демо по настоящему AF_UNIX-сокету.
pagh-desktop = { path = "../pagh-desktop" }

# Как у остальных render-крейтов rust-apps/: горячий путь — C-циклы TinyGL,
# через границу C/Rust LTO не работает; главное — `-O2` в build.rs tinygl.
[profile.release]
panic = "abort"
opt-level = 3
lto = true
strip = true

[profile.release.package.tinygl]
opt-level = 3

[profile.release.package.pagh-ui]
opt-level = 3
120 changes: 120 additions & 0 deletions rust-apps/pagh-gl-demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# `pagh-gl-demo` — CPU TinyGL-демо для Pagh-OS

Демонстрационный клиент **PDP/1**, который рендерит CPU-геометрию через
vendored [TinyGL 0.4.1](../tinygl/) (MIT) **прямо в `mmap(MAP_SHARED)`**
memfd-поверхность окна. Композитору не уходит ни одного пикселя: только
`COMMIT` + `DAMAGE`, как у остальных ShmSurface-клиентов (`pagh-files`,
`pagh-terminal`).

Это PR5 спеки [`docs/tinygl-port-spec.md`](../../docs/tinygl-port-spec.md):
интеграция с композитором и три сцены. Версия `pagh`/`Cargo.toml` ядра здесь
**не** меняется (MINOR — только в финальном acceptance PR6).

## Сцены

| Сцена | Что доказывает | Анимация |
|---|---|---|
| `triangle` | perspective + clip + Gouraud | нет, фиксированный угол |
| `cube` | 6 граней, depth test, back-face culling | кадр `n` = `25° + n*15°` вокруг Y |
| `gears` | ~1.1k треугольников, освещение on/off | кадр `n` = `n*1.5°` × передаточное отношение |

Все сцены — **наш** код под `tinygl::Context` (immediate mode). `gears` не
скопирован из GPL-примера upstream: зубчатый профиль (12/14/10 зубьев,
внутреннее отверстие, крышки/стенки) сгенерирован здесь; тригонометрия профиля
считается собственным рядом Тейлора без libm, чтобы host/musl-дайджесты
совпали бит-в-бит.

## CLI

```text
pagh-gl-demo <triangle|cube|gears> [options]

--connect <sock> живой PDP/1 (pagh-desktop); без него — headless
--frames <N> кадров (0 = до закрытия окна; headless: >= 1)
--size <WxH> клиентская область (по умолчанию 640x480, W кратно 4)
--out <dir> писать кадры как PPM (P6) в каталог
--hash печатать дайджест каждого кадра (live: по умолчанию
только кадр 0 и каждый 60-й)
--lighting <on|off> освещение gears (по умолчанию on)
-h, --help
```

Без `--connect` демо работает headless: рендер в `Vec<u32>`, на каждый кадр
печатается

```text
TINYGL <scene> frame=<n> digest=0x<16 hex> w=<w> h=<h>
```

и в конце — `ft=min/med/max ms (wall) cycles=...`. С `--connect` — живое окно
композитора; маркер `TINYGL` годен для grep из serial-лога, как `[BOOTID]` и
`LXSELFTEST`.

Кадры считаются **по номеру**, не по времени: `Instant`/`rdtsc` участвуют
только в замерах (спека §6.2). Поэтому дайджест кадра `n` воспроизводим в
headless-прогоне, в QEMU и на musl.

## PDP/1: ShmSurface

1. `memfd_create` → `ftruncate(w*h*4)` → `mmap(MAP_SHARED)` через
`pagh_ui::shm::ShmSurface` (`SharedFrame` в `src/surface.rs`).
2. `hello`/`welcome`; требуется `welcome.flags` bit 2 (`ShmSurface`).
3. `create` окна, затем `SHM_OFFER` с fd через `SCM_RIGHTS` и ожидание
`SHM_READY`.
4. `ZB_open(w, h, ZB_MODE_RGBA, 0, NULL, NULL, mapping_ptr)` + `glInit` —
один контекст на размер; рендер пишет прямо в memfd.
5. На кадр — `COMMIT` (header flags SHM) с полным damage-прямоугольником.
6. На `configure` — новый memfd, новый `SHM_OFFER`, `SHM_RELEASE(old)`; на
`SHM_RELEASE` от сервера — повторный offer того же размера.

**Fallback на full-frame upload отсутствует** намеренно (спека §4.5): если
композитор не объявил ShmSurface или нет memfd/mmap/`SCM_RIGHTS`, демо падает
с внятной ошибкой и кодом 1.

## Тесты и сборка

```bash
cd rust-apps/pagh-gl-demo
cargo test # host: сцены/дайджесты/CLI
cargo run --bin pagh-gl-demo -- triangle --hash
cargo build --release --target x86_64-unknown-linux-musl
```

`cargo test` покрывает:

* pinned FNV-1a-64 дайджесты `triangle`/`cube`/`gears` (lighting on/off);
* точечную геометрию: центр Gouraud-треугольника, грань куба, «дырка»
шестерёнки и точка на зубе;
* детерминизм (два рендера — один дайджест/пиксели);
* `keep_all`, независимость кадра 0 от числа кадров, отказ `w % 4 != 0`;
* разбор CLI (defaults, `--frames 0` только с `--connect`, ошибки).

Musl-сборке нужен C-компилятор для `x86_64-unknown-linux-musl`; его ищет
`tinygl/build.rs` (`CC_<target>` → `<target>-gcc` → `musl-gcc` → `clang
--target=...`) и печатает инструкцию, если не нашёл. Готовый бинарь
static-pie проверяется `INTERP`-гейтом `tools/build-rust-app.sh`.

## Честные ограничения

* **CPU only**: никакого GPU/DRM/NVIDIA, OpenGL 2+/GLSL/FBO/VBO/EGL/GLX/
Wayland/Mesa. Upstream fixed-function subset GL 1.1.
* Z-буфер **16-битный**; для залитых треугольников Z-тест идёт всегда, даже
без `GL_DEPTH_TEST` (upstream); `glDepthMask`/`glDepthFunc` нет.
* `stride == width*4`, `width % 4 == 0` — иначе `Surface::new`/`SharedFrame`
возвращают ошибку (TinyGL молча срезал бы `xsize & ~3`).
* Один `Context` на процесс (`gl_ctx` глобальный); демо однопоточное.
* `glClear` заливает Z нулём, `glClearDepth` upstream игнорирует.
* Освещение — только fixed-function `GL_LIGHT0..7` (в демо `Light0`);
`glColorMaterial` не используется, материал задаётся `glMaterialfv`.
* `gl_fatal_error` upstream — `exit(1)`; наш слой отвергает известные опасные
входы, но внутренний fatal остаётся смертью процесса.
* Живой путь требует `pagh-desktop` с ShmSurface (PDP/1 версии 1); окно
рисует композитор, клиент — только клиентскую область.
* Frame time в QEMU TCG — **верхняя граница**, не бенчмарк: TSC виртуален,
абсолютные числа честны только в пределах одной конфигурации QEMU.

## Лицензия

Код демо — MIT. Vendored TinyGL 0.4.1 — MIT (Fabrice Bellard); см.
[`../tinygl/LICENSE-TinyGL`](../tinygl/LICENSE-TinyGL) и
[`../tinygl/THIRD_PARTY_NOTICES.md`](../tinygl/THIRD_PARTY_NOTICES.md).
Loading
Loading