Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: gpu & taffy
Preetham Pemmasaniabb832d3827c
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 7d07f6d..d53bb91 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -59,6 +59,29 @@ defines `BuiGpuSink` — a function-pointer table (`triangles`, `lines`,- applies the model matrix and forwards screen-space primitives to the sink,- or, with no sink installed, discards everything (pure null).+### Raster and GPU renderer++The kit itself draws through `GPU_raster.h`:+- **Software raster** (`gpu/intern/gpu_raster.c`): the default. It renders+ anti-aliased SDF primitives into a CPU frame buffer, in parallel bands.+ Text is a glyph-run cache over GDI (Windows) or stb_truetype (everywhere+ else; `BUI_TEXT_STB=ON` selects it on Windows too).+- **GPU renderer** (`gpu/intern/gpu_d3d11.c`, `gpu/shaders/bui_ui.hlsl`):+ opt-in with `BUI_GPU=1`, `BUI_gpu_set_default`, Rust `.gpu(true)` or+ tkinter `Tk(gpu=True)`.++In GPU mode the same `BUI_raster_*` calls record one 128-byte instance per+primitive, after the same clip test. This follows Blender's+`GPU_SHADER_2D_WIDGET_BASE_INST` batching in `interface_widgets.cc`:+- One uber-shader evaluates the software raster's coverage formulas, so the+ pixels match. `gpu/tests/test_gpu_parity.c` checks this.+- Text runs and images are cached in atlases. Polygons are covered on the+ CPU and uploaded as masks.+- Frames render into a persistent target, so damage rectangles still limit+ redraws. Presentation uses a flip-model swap chain with dirty rects.+- The device is created on a worker thread, and a lost device falls back+ to software.+Real renderers plug in at three levels: C (`bui_set_render_sink`), Qt/C++(`BUI::QtSink`), Python (`buipy.set_backend`). See INTEGRATION.md.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 518e173..9de7804 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,50 @@ All notable changes to **blenderui** (BUI). The format follows## [Unreleased]### Added+- **Modern CSS in the Rust crate**:+ - **Layout:** [taffy](https://github.com/DioxusLabs/taffy) 0.6 → 0.15 behind a layout tree of our own. taffy's built-in tree resolves `calc()` to 0; ours evaluates it. That brings mixed-unit `calc()` everywhere (`calc(100% - 2rem)`, grid tracks, `fit-content(calc())`), floats and `clear`, `direction: rtl`, `grid-template-areas` with named lines and areas, the sizing keywords (`min-content`, `max-content`, `fit-content`, `stretch`), `display: flow-root`, real `position: static` / `fixed` with containing blocks, `contain`, `flex-wrap: balance`, and `safe` / `unsafe` alignment.+ - **Math:** `calc()`, `min()`, `max()`, `clamp()`, `round()` (all four strategies), `mod()`, `rem()`, `abs()`, `sign()`, trigonometry, `pow()`, `sqrt()`, `hypot()`, `log()`, `exp()`, the constants `e`/`pi`/`infinity`, and every length unit (`vmin`/`vmax`, `dvh`/`svh`/`lvh`, `ch`, `ex`, `lh`, `rlh`, `cap`, `cq*` ...) plus angles. Expressions are interned once.+ - **Custom properties:** `var()` with fallbacks, nesting inside functions, inheritance and cycle detection. `env()` is supported too. Variable maps live in a shared arena, not in reference-counted values.+ - **Colors (CSS Color 4/5):** modern `rgb()`/`hsl()` syntax with `none`; `hwb()`, `lab()`, `lch()`, `oklab()` and `oklch()`; `color()` in every predefined space; `color-mix()` with every interpolation space and hue method; relative colors (`oklch(from var(--c) calc(l + .1) c h)`); `light-dark()`; system colors; CSS gamut mapping into sRGB.+ - **Selectors Level 4:** full selector lists in `:is()`, `:where()` and `:not()`; relative `:has()` (evaluated on the element's declarative subtree before it is built); `:nth-child(An+B of S)`; the `*-of-type` family; `:lang()`; `:dir()`; attribute `i`/`s` flags; CSS escapes; nesting with `&`; and pseudo-elements, with `::before` / `::after` generating boxes (the `content` property with strings, `attr()` and quotes).+ - **At-rules:**+ - Media Queries 4: ranges, `not`/`or`, every desktop feature.+ - `@supports`, including `selector()`.+ - `@layer`: cascade layers, both the statement and the block form.+ - `@scope`.+ - Parsed but not applied yet: `@container`, `@font-face`, `@keyframes` and `@property`.+- **Tailwind CSS v4** (`blenderui-tailwind` crate): class names compile to CSS on first use, like Tailwind's JIT, using the v4 default theme.+ - **Variants:** state and structural ones, pseudo-elements, `group-*` and `peer-*` (including named), `has-*`, `not-*`, `in-*`, `data-*`, `aria-*`, `nth-*`, `*` and `**`, the breakpoints with their `max-*` and `min-[…]` forms, container queries, `dark`, `motion-*`, `contrast-*`, `print`, orientation, `supports-*`, `rtl`/`ltr`, `open`, `inert`, and arbitrary `[&…]`.+ - **Values:** arbitrary values and properties, `(--var)`, negatives, `/opacity` and `!important`.+ - **Order:** utilities sort the way Tailwind sorts them.+ - **Usage:** `.class("md:hover:bg-sky-500/50")` just works; `tw!("…")` checks classes at compile time; `blenderui::set_tailwind(false)` opts out.+- **GPU renderer** (Direct3D 11, opt-in): Rust `Application::new().gpu(true)`+ or `WindowOptions { gpu: Some(true), .. }`, tkinter `Tk(gpu=True)` or+ `bui.set_gpu()`, C `BUI_gpu_set_default` / `BK_window_set_gpu`, or+ `BUI_GPU=1` for any app. Modeled on Blender's instanced widget-base+ batches (`interface_widgets.cc`): every primitive (rects, Blender widget+ bases, circles, lines, shadows, gradients, HSV wheels, images, text runs)+ is one 128-byte instance of a single uber-shader, so a frame of thousands+ of widgets is a few `DrawInstanced` calls. Text runs and images live in+ atlases. Frames render into a persistent target, so the kit's damage+ rectangles still bound the work, and they present through a flip-model+ swap chain with dirty rects. The device is created on a worker thread+ (the first frame never waits for the driver), and a lost device falls+ back to the software raster. The pixel shader evaluates the software+ raster's coverage formulas, so both renderers draw the same pixels+ (`gpu_parity` test: 10 of 172,800 pixels differ by more than 3/255, all on+ hard triangle edges). Shaders live in `gpu/shaders/bui_ui.hlsl`, with+ precompiled bytecode checked in, so builds need no shader compiler.+- **Portable text engine**: stb_truetype behind the same glyph-run cache as+ GDI, so text renders on Linux, macOS and wasm. It is also available on+ Windows with `-DBUI_TEXT_STB=ON` or the `portable-text` Rust feature.+ Fonts come from the platform's font folders (Segoe UI, DejaVu, Liberation,+ Noto, Helvetica and others, with generic `sans`/`serif`/`mono`), from+ `BUI_FONT` / `BUI_FONT_DIR`, or from `BUI_text_add_font` (Rust+ `blenderui::add_font`), which wasm needs. Missing bold and italic faces+ are synthesized. A per-glyph bitmap cache keeps changing strings cheap.+ Layout matches GDI, and the 3000-cell benchmark costs the same CPU.+- `BUI_text_run_mask`, `BUI_raster_gpu_attach`/`_poll`/`is_gpu`.- **Rust crates** (`bindings/rust/`): `blenderui-sys` (FFI over `BUI_kit.h`,builds the kit with CMake) and `blenderui`: gpui syntax (`Application`,`Render`, `Context`, `Entity`, `cx.listener`, ~1,300 `Styled` methods), alldiff --git a/CMakeLists.txt b/CMakeLists.txtindex 9bd6527..de59e88 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -55,6 +55,7 @@ add_subdirectory(api) # stable C ABI for hosts & bindingsif(BUI_BUILD_TESTS)enable_testing()add_subdirectory(core/tests)+ add_subdirectory(gpu/tests)endif()if(BUI_BUILD_PYTHON_BINDINGS)diff --git a/README.md b/README.mdindex 41cfd4f..eb1c112 100644--- a/README.md+++ b/README.md@@ -45,7 +45,7 @@ Right: an unmodified tkinter program (<code>examples/tk_unchanged_app.py</code>)- [Blender components](#blender-components)- [Rust (gpui syntax, HTML and CSS)](#rust-gpui-syntax-html-and-css)- [How it works](#how-it-works)-- [Performance](#performance) (including [blenderui vs gpui](#rust-blenderui-vs-gpui))+- [Performance](#performance) (including [blenderui vs gpui](#rust-blenderui-vs-gpui) and the [GPU renderer](#gpu-renderer))- [Roadmap: more languages and platforms](#roadmap-more-languages-and-platforms)- [Packaging](#packaging)- [Documentation](#documentation)@@ -77,11 +77,11 @@ Right: an unmodified tkinter program (<code>examples/tk_unchanged_app.py</code>)| Component library (`bui.components`) | ✅ Working | 45 Blender components, including editors (color ramp, curves) and templates || C++ / Qt render-sink backends | ✅ Working | For embedding BUI drawing into your own renderer ([INTEGRATION.md](INTEGRATION.md)) || Packaging (`pip install blenderui`) | ✅ Published | [`blenderui` 0.1.0 on PyPI](https://pypi.org/project/blenderui/): a prebuilt wheel for Windows / CPython 3.12, and a source package that other platforms compile on install (needs CMake and a C compiler). Prebuilt wheels for all platforms come from CI on the next tagged release ([docs/publishing.md](docs/publishing.md)) |-| **Rust** (`blenderui` crate) | ✅ **Working** | gpui syntax (`Render`, `Context`, `Entity`, `cx.listener`, ~1,300 `Styled` methods) over **113/113 HTML elements** and CSS: **173 properties rendered** (+87 parsed without effect), CSS 2.1 screen properties 76/90 rendered (90/90 parsed), Flexbox 12/12, Grid 22/23. Layout by [taffy](https://github.com/DioxusLabs/taffy). Native window on Windows, headless rendering everywhere. Animating 3000 elements: 57.5 fps on 27 ms CPU per frame (same session: gpui-fast 50.5 fps, gpui 18.9 fps), with about half their memory and a 6 ms first frame ([benchmark](bindings/rust/bench/README.md)). [docs/rust.md](docs/rust.md) |+| **Rust** (`blenderui` crate) | ✅ **Working** | gpui syntax (`Render`, `Context`, `Entity`, `cx.listener`, ~1,300 `Styled` methods) over **113/113 HTML elements** and CSS: **180 properties rendered** (+81 parsed without effect); against the 745-property W3C index, 24% rendered, 10% parsed only and 66% left (mostly drafts, speech, print and SVG; [details](docs/rust.md#coverage)), CSS 2.1 screen properties 80/90 rendered, Flexbox 12/12, Grid 23/23, plus `calc()` and every math function, `var()`, CSS Color 4/5 (`oklch`, `color-mix`), Selectors 4 (`:has()`), nesting, `@layer`, and **Tailwind CSS v4** classes (`tw!` checks them at compile time). Layout by [taffy](https://github.com/DioxusLabs/taffy). Native window on Windows, headless rendering everywhere. Animating 3000 elements: 59.9 fps on 11.6 ms CPU per frame with the opt-in GPU renderer (same session: gpui-fast 31.5 fps on 31.9 ms, gpui 19.9 fps on 50.5 ms), with less memory and a ~5 ms first frame ([benchmark](bindings/rust/bench/README.md)). [docs/rust.md](docs/rust.md) || **egui integration** | 🗺️ Planned | BUI panels drawn inside egui (raster → `egui::TextureHandle`, input forwarded) and a Blender-styled `egui::Visuals` theme. Builds on the Rust crate || **WebAssembly build** | 🗺️ Planned | The kit compiled with Emscripten: the raster blits to `<canvas>` (damage rectangles only), DOM events feed `BK_press` / `BK_key` || **React** (`@blenderui/react`) | 🗺️ Planned | A JSX reconciler over the WASM build (`<Panel>`, `<NumberSlider>` ...); `@blenderui/web` for plain JS/TS, N-API for Node |-| Other languages and hosts | 🗺️ Planned | C#, Go, Zig, Swift, Kotlin, Lua; Dear ImGui; Godot, Unity, Bevy; Flutter; native Linux/macOS windows; GPU renderers ([roadmap](#roadmap-more-languages-and-platforms)) |+| Other languages and hosts | 🗺️ Planned | C#, Go, Zig, Swift, Kotlin, Lua; Dear ImGui; Godot, Unity, Bevy; Flutter; native Linux/macOS windows; Vulkan/Metal/WebGPU renderers ([roadmap](#roadmap-more-languages-and-platforms)) |## Install and build@@ -176,6 +176,9 @@ scroll regions), `Text` (indices, tags, marks, search, undo), `Treeview`,bindings, variables and traces, `after`, and window-manager calls.Full guide: **[docs/tkinter.md](docs/tkinter.md)**.+> **GPU rendering:** add `gpu=True` to `Tk(...)` (or call `bui.set_gpu(True)`,+> or run with `BUI_GPU=1`) to draw on the GPU. See [GPU renderer](#gpu-renderer).+### Qt syntax```python@@ -266,6 +269,10 @@ fn main() {}```+> **GPU rendering:** `Application::new().gpu(true)` (or `BUI_GPU=1`) draws every+> window with Direct3D 11: same pixels, about half the CPU of the default+> software raster, and less than gpui-fast. See [GPU renderer](#gpu-renderer).+<p align="center"><img src="docs/images/rust-showcase.png" width="560" alt="The Rust showcase example"></p><p align="center"><sub><code>bindings/rust/blenderui/examples/showcase.rs</code>: a stylesheet, grid cards withgradients and shadows, Blender form widgets, a table, lists, <code><details></code> and <code><pre></code>.</sub></p>@@ -294,7 +301,8 @@ Elements, the CSS that is supported, events and testing headless:packer and gridder. Qt's box, grid and form layouts are mapped onto them.- **Damage rendering.** A state change marks only its widget's rectangle.A frame redraws just those regions into a frame buffer (anti-aliased SDF- shapes and a cached native text engine). Only the changed tiles are+ shapes and a cached glyph-run text engine: GDI on Windows, stb_truetype+ elsewhere), on the CPU or, opt-in, on the GPU. Only the changed tiles arepresented to the window.- **Python stays thin.** Facades keep what tkinter and Qt keep in their ownscripting layers: option values, variables, traces, signals and bindings.@@ -318,30 +326,69 @@ interaction frames under 1 ms.### Rust: blenderui vs gpuiThe same UI built with the `blenderui` crate and with-[gpui](https://crates.io/crates/gpui) 0.2.2 (Zed's GPU-rendered framework): a+[gpui](https://crates.io/crates/gpui) 0.2.2 (Zed's GPU-rendered framework)+and its faster fork [gpui-fast](https://github.com/longbridge/gpui-fast): a1000×800 window of N rounded, labelled cells that all change every frame.-Ryzen 7 5800U laptop on mains power, 60 Hz display, release builds, both apps-in the same session, median of 3 runs-([method and full data](bindings/rust/bench/README.md)).+Ryzen 7 5800U laptop on mains power, 60 Hz display, release builds, all apps+back to back in one session+([method and full data](bindings/rust/bench/README.md)). blenderui is shown+with its opt-in GPU renderer (`.gpu(true)` / `BUI_GPU=1`) and its default+software raster.++| | blenderui (GPU) | blenderui (CPU raster) | gpui-fast | gpui |+|---|---:|---:|---:|---:|+| FPS, 3000 animated cells | **59.9** | 57.6 | 31.5 | 19.9 |+| FPS, 1000 animated cells | **60** | **60** | 49.2 | 36.4 |+| CPU per frame, 3000 cells | **11.6 ms** | 22.0 ms | 31.9 ms + GPU | 50.5 ms + GPU |+| CPU per frame, 1000 cells | **4.7 ms** | 10.2 ms | 20.5 ms + GPU | 27.7 ms + GPU |+| CPU per frame, 100 cells | **1.2 ms** | 4.6 ms | 2.7 ms + GPU | 4.7 ms + GPU |+| Uncapped FPS, 100 / 1000 / 3000 cells | **1491 / 309 / 94** | 649 / 202 / 76 | - | - |+| RAM (working set), 3000 / 1000 / 100 cells | 40 / 35 / 28 MB | **30 / 24 / 21 MB** | 65 / 45 / 47 MB | 77 / 47 / 40 MB |+| GPU memory | 19-22 MB | **none** | 19-24 MB | 16-21 MB |+| First frame after launch | **~5 ms** | **~5 ms** | ~200 ms | ~220 ms |+| Idle CPU | **0 %** | 0-0.9 % | 0-0.4 % | 0.9-1.4 % |++With the GPU renderer, blenderui beats gpui-fast on every row. It does the+least CPU work per frame at every scene size (2.2-4.4x less than gpui-fast),+holds 60 fps where both gpuis drop, and uses less RAM with the same GPU+memory. It still starts about 40x faster. The software raster remains the+default, because it needs no GPU memory or driver. gpui-fast's heavy-scene+frame rate varies between sessions on this laptop (30-60 fps at 3000 cells),+so compare within a session.++### GPU renderer++Off by default; turn it on per app or per window:-| | blenderui | gpui |-|---|---:|---:|-| FPS, 3000 animated cells | **57.5** | 18.9 |-| FPS, 1000 / 100 animated cells | 60 / 60 (display cap; 157 / 529 uncapped) | 60 / 60 |-| CPU per frame, 3000 cells | **27.3 ms** | 53.1 ms + GPU |-| CPU per frame, 1000 cells | **13.7 ms** | 14.7 ms + GPU |-| CPU per frame, 100 cells | 5.1 ms | **3.4 ms** + GPU |-| RAM (working set), 3000 / 1000 / 100 cells | **31 / 23 / 20 MB** | 76 / 46 / 32 MB, plus 16-21 MB GPU memory |-| First frame after launch | **~6 ms** | ~250 ms |-| Idle CPU | **0 %** | 0.7-1.4 % |--blenderui wins everything except CPU per frame on very small scenes, where-gpui's GPU does the drawing. With only one of 3000 cells changing per frame-(a later, power-limited session for both apps), blenderui ran at 54 fps and-gpui at 11 fps. Against [gpui-fast](https://github.com/longbridge/gpui-fast),-a faster gpui fork, blenderui leads on frame rate in the heavy scene, memory-and startup, while gpui-fast uses less CPU per frame; see the-[benchmark](bindings/rust/bench/README.md).+```rust+Application::new().gpu(true).run(|cx| { /* ... */ }); // every window+cx.open_window(WindowOptions { gpu: Some(true), ..Default::default() }, build); // one window+```++```python+from bui import tksyntax as tk+root = tk.Tk(gpu=True) # or bui.set_gpu(True) for every window+```++Or set `BUI_GPU=1` for any BUI app (C, Python, Rust); `BUI_GPU=0` forces the+software raster. It is Direct3D 11 on Windows. On other platforms, or when+no device can be created, windows stay on the software raster. The design+follows Blender's instanced widget-base batches (`interface_widgets.cc`):+- Every primitive is one 128-byte instance of a single uber-shader+ ([`gpu/shaders/bui_ui.hlsl`](gpu/shaders/bui_ui.hlsl)). The primitives are+ rects, Blender widget bases with outline and emboss, circles, lines,+ shadows, gradients, HSV wheels, images and text runs.+- A frame of thousands of widgets is a few `DrawInstanced` calls.+- Text runs and images are cached in atlases.+- Frames render into a persistent target, so damage tracking still limits+ redraws to what changed. Presentation uses a flip-model swap chain with+ dirty rects.+- The device is created on a worker thread, so startup never waits for the+ driver.++The shaders evaluate the software raster's own coverage formulas, so both+renderers draw the same pixels: the `gpu_parity` test finds 10 of 172,800+pixels that differ by more than 3/255, all on hard triangle edges.### tkinter canvas@@ -369,7 +416,7 @@ them needs Python.| **C / C++** | `BUI_kit.h`, render sinks, Qt/QPainter backend | ✅ Done || **Rust** | `blenderui-sys` (FFI over `BUI_kit.h`, builds the kit with CMake) and `blenderui`: gpui syntax, all HTML elements, CSS, taffy layout ([docs/rust.md](docs/rust.md)) | ✅ Done (native window on Windows; Linux/macOS render headless until their window hosts land) || **egui** | Two ways in: draw a BUI panel inside egui (raster to an `egui::TextureHandle`, with input forwarded), and a Blender-styled `egui::Visuals` theme | 🗺️ Planned |-| **WebAssembly** | Compile the kit with Emscripten. The raster blits to a `<canvas>` (`putImageData` of the damage rectangles only), and DOM pointer and keyboard events go to `BK_press` / `BK_key` | 🗺️ Planned |+| **WebAssembly** | Compile the kit with rust. The raster blits to a `<canvas>` (`putImageData` of the damage rectangles only), and DOM pointer and keyboard events go to `BK_press` / `BK_key` | 🗺️ Planned || **React** | `@blenderui/react` on top of the WASM build: a reconciler that maps JSX to kit nodes (`<Panel>`, `<NumberSlider>` ...) | 🗺️ Planned || **JavaScript / TypeScript** | `@blenderui/web` (the plain WASM API), and Node through N-API | 🗺️ Planned || **Tauri / Electron** | The WASM build in the webview, or the native kit through the host language | 🗺️ Planned |@@ -379,7 +426,7 @@ them needs Python.| **Game engines**: Godot, Unity, Bevy | Editor-style tool panels: GDExtension, a native Unity plugin, a Bevy plugin through the Rust crate | 🗺️ Planned || **Flutter** | `dart:ffi` bindings, with the frame buffer shown as a `Texture` | 🗺️ Planned || **Native windows on Linux / macOS** | Wayland / X11 and Cocoa hosts in C, like the Win32 one (today the stdlib Tk window hosts them) | 🗺️ Planned |-| **GPU renderers** | OpenGL / Vulkan / Metal / WebGPU render sinks for very large or high-DPI UIs (today a SIMD-friendly CPU raster, under 1 ms per frame) | 🗺️ Planned |+| **GPU renderers** | Direct3D 11 done (opt-in, see [GPU renderer](#gpu-renderer)); Vulkan / Metal / WebGPU backends for the same instance stream | 🟡 D3D11 done |<details><summary>Intended API sketches (planned, not implemented yet)</summary>@@ -395,17 +442,12 @@ egui::Window::new("Properties").show(ctx, |ui| {React (WebAssembly):```jsx-import { BlenderUI, Panel, NumberSlider, Checkbox } from "@blenderui/react";+import { render } from "@blenderui/react";export default function Properties() {const [size, setSize] = useState(1);return (- <BlenderUI width={360} height={260}>- <Panel title="Object">- <NumberSlider label="Size" value={size} min={0} max={10} onChange={setSize} />- <Checkbox label="Smooth" defaultChecked />- </Panel>- </BlenderUI>+ render(<App />, {title: "Bla bla", width: 1920, height: 1080}));}```@@ -472,7 +514,7 @@ Examples (`examples/`):| Path | Contents || --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `kit/` | **The C runtime**: `kit_core.c` (nodes, input, rendering, undo, views), `kit_draw.c` (theme and the `interface_widgets.cc` port), `kit_widgets.c`, `kit_views.c` (lists, trees), `kit_menus.c`, `kit_color.c`, `kit_frame.c` (geometry managers, canvas), `kit_textarea.c`, `kit_window.c` (Win32 host). Public API: `kit/include/BUI_kit.h` |-| `gpu/` | Drawing: software raster (`gpu_raster.c`), render-sink dispatch |+| `gpu/` | Drawing: software raster (`gpu_raster.c`), D3D11 GPU renderer (`gpu_d3d11.c`, `shaders/`), text (GDI / stb_truetype), render-sink dispatch || `core/`, `types/` | Blender's `blenlib` subset (C11) and data types || `ui/`, `compat/` | Blender's original interface sources and the seams replacing Blender's application APIs || `api/` | Stable C ABI for render-sink hosts (`bui_c_api.h`) |diff --git a/bindings/python/bui/__init__.py b/bindings/python/bui/__init__.pyindex c798199..b74291c 100644--- a/bindings/python/bui/__init__.py+++ b/bindings/python/bui/__init__.py@@ -123,3 +123,11 @@ def version() -> str:def set_backend(backend) -> None:"""Route BUI drawing into ``backend`` (or None to disable rendering)."""buipy.set_backend(backend)+++def set_gpu(on: bool = True) -> None:+ """Draw new native windows on the GPU (Direct3D 11): the same pixels as+ the software raster, with rasterization off the CPU. Falls back to the+ software raster where no device exists. ``BUI_GPU=1``/``0`` overrides.+ Per window: ``Tk(gpu=True)``."""+ buipy.set_gpu(bool(on))diff --git a/bindings/python/bui/__pycache__/__init__.cpython-314.pyc b/bindings/python/bui/__pycache__/__init__.cpython-314.pycindex 54a09d5..5df0713 100644Binary files a/bindings/python/bui/__pycache__/__init__.cpython-314.pyc and b/bindings/python/bui/__pycache__/__init__.cpython-314.pyc differdiff --git a/bindings/python/bui/__pycache__/host.cpython-314.pyc b/bindings/python/bui/__pycache__/host.cpython-314.pycindex b664507..b7faa40 100644Binary files a/bindings/python/bui/__pycache__/host.cpython-314.pyc and b/bindings/python/bui/__pycache__/host.cpython-314.pyc differdiff --git a/bindings/python/bui/host.py b/bindings/python/bui/host.pyindex 22e8ca3..1f56a61 100644--- a/bindings/python/bui/host.py+++ b/bindings/python/bui/host.py@@ -82,7 +82,8 @@ def _tk():class Window:- def __init__(self, ctx, title: str = "BUI", size=(640, 480), native: bool = None):+ def __init__(self, ctx, title: str = "BUI", size=(640, 480), native: bool = None,+ gpu: bool = None):self.ctx = ctxself._title, self._size = title, tuple(size)self.native = native_available() if native is None else native@@ -93,6 +94,8 @@ class Window:if self.native:self._win = buipy.KitWindow(ctx, title, *self._size)self._win.on_close = self._close_requested+ if gpu: # None: buipy.set_gpu() / BUI_GPU decide+ self._win.gpu = Trueelse:self._make_tk()_windows.append(self)diff --git a/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pycindex fa5d3a8..9bb0a3c 100644Binary files a/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc and b/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc differdiff --git a/bindings/python/bui/tksyntax/_core.py b/bindings/python/bui/tksyntax/_core.pyindex b3a3fe5..7b14c12 100644--- a/bindings/python/bui/tksyntax/_core.py+++ b/bindings/python/bui/tksyntax/_core.py@@ -2214,7 +2214,8 @@ class _WindowHost:self._withdrawn = Falseself._menubar = Noneself._ctx = buipy.KitContext(self._node)- self._window = host.Window(self._ctx, self._title, (200, 200))+ self._window = host.Window(self._ctx, self._title, (200, 200),+ gpu=getattr(self, "_gpu", None))self._window.on_close = self._on_close_button_window_list.append(self)@@ -2364,8 +2365,12 @@ class Tk(_WindowHost, Misc, Wm):_name = "."def __init__(self, screenName=None, baseName=None, className="Tk", useTk=True, sync=False,- use=None):+ use=None, gpu=None):+ """``gpu=True`` draws this window on the GPU (Direct3D 11) instead of+ the software raster: same pixels, rasterization off the CPU. ``None``+ follows ``bui.set_gpu()`` / the ``BUI_GPU`` environment variable."""global _default_root+ self._gpu = gpuself.master = Noneself.children = {}self._destroyed = Falsediff --git a/bindings/python/src/buipy_kit.c b/bindings/python/src/buipy_kit.cindex a13e834..0cd49c2 100644--- a/bindings/python/src/buipy_kit.c+++ b/bindings/python/src/buipy_kit.c@@ -2058,6 +2058,23 @@ static PyObject *kitwin_frames(KitWindowObject *self, void *c)return PyLong_FromLong(BK_window_frames(self->win));}+static PyObject *kitwin_get_gpu(KitWindowObject *self, void *c)+{+ return PyBool_FromLong(self->win && BK_window_gpu(self->win));+}++static int kitwin_set_gpu(KitWindowObject *self, PyObject *v, void *c)+{+ const int on = v ? PyObject_IsTrue(v) : 0;+ if (on < 0) {+ return -1;+ }+ if (self->win) {+ BK_window_set_gpu(self->win, on);+ }+ return 0;+}+static PyObject *kitwin_hwnd(KitWindowObject *self, void *c){return PyLong_FromVoidPtr(BK_window_handle(self->win));@@ -2149,6 +2166,8 @@ static PyMethodDef kitwin_methods[] = {static PyGetSetDef kitwin_getset[] = {{"size", (getter)kitwin_size, NULL, "client size in pixels", NULL},{"frames", (getter)kitwin_frames, NULL, "presented frames", NULL},+ {"gpu", (getter)kitwin_get_gpu, (setter)kitwin_set_gpu,+ "True once frames are drawn on the GPU; set True to switch this window to the GPU", NULL},{"hwnd", (getter)kitwin_hwnd, NULL, "native handle", NULL},{"on_close", (getter)kitwin_get_on_close, (setter)kitwin_set_on_close,"called on the close button; return True to close", NULL},diff --git a/bindings/python/src/buipy_module.c b/bindings/python/src/buipy_module.cindex 273a287..5626898 100644--- a/bindings/python/src/buipy_module.c+++ b/bindings/python/src/buipy_module.c@@ -1143,6 +1143,24 @@ static PyObject *buipy_has_native_text(PyObject *self, PyObject *noargs)return PyBool_FromLong(BUI_text_native());}+static PyObject *buipy_set_gpu(PyObject *self, PyObject *on)+{+ (void)self;+ const int v = PyObject_IsTrue(on);+ if (v < 0) {+ return NULL;+ }+ BUI_gpu_set_default(v);+ Py_RETURN_NONE;+}++static PyObject *buipy_gpu_default(PyObject *self, PyObject *noargs)+{+ (void)self;+ (void)noargs;+ return PyBool_FromLong(BUI_gpu_default());+}+static PyObject *buipy_version(PyObject *self, PyObject *args){int major, minor, patch;@@ -1232,6 +1250,9 @@ static PyMethodDef buipy_methods[] = {{"set_font", buipy_set_font, METH_VARARGS, "set_font(family='', flags=0): font for draw_text (1 bold, 2 italic, 4 underline)."},{"measure_text", buipy_measure_text, METH_VARARGS, "measure_text(text, size, family='', flags=0) -> float | None."},{"has_native_text", buipy_has_native_text, METH_NOARGS, "True when draw_text renders natively into a Raster."},+ {"set_gpu", buipy_set_gpu, METH_O,+ "set_gpu(on): new native windows draw on the GPU (Direct3D 11). BUI_GPU=1/0 overrides."},+ {"gpu_default", buipy_gpu_default, METH_NOARGS, "Whether new native windows use the GPU."},{"draw_triangles", buipy_draw_triangles, METH_VARARGS, "draw_triangles([(x, y), ...], [(r, g, b, a), ...]): per-vertex colored triangles."},{"draw_gradient", buipy_draw_gradient, METH_VARARGS, "draw_gradient(x, y, w, h, tl, tr, br, bl): bilinear corner-color rectangle."},{"draw_hsv_circle", buipy_draw_hsv_circle, METH_VARARGS, "draw_hsv_circle(cx, cy, radius, value): Blender HSV color wheel."},diff --git a/bindings/rust/Cargo.lock b/bindings/rust/Cargo.lockindex 568eaf4..a4f129c 100644--- a/bindings/rust/Cargo.lock+++ b/bindings/rust/Cargo.lock@@ -8,18 +8,6 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"-[[package]]-name = "arrayvec"-version = "0.7.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"--[[package]]-name = "autocfg"-version = "1.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"-[[package]]name = "bitflags"version = "1.3.2"@@ -32,6 +20,7 @@ version = "0.1.0"dependencies = ["blenderui-macros","blenderui-sys",+ "blenderui-tailwind","paste","png","smallvec",@@ -41,6 +30,9 @@ dependencies = [[[package]]name = "blenderui-macros"version = "0.1.0"+dependencies = [+ "blenderui-tailwind",+][[package]]name = "blenderui-sys"@@ -49,6 +41,10 @@ dependencies = ["cmake",]+[[package]]+name = "blenderui-tailwind"+version = "0.1.0"+[[package]]name = "cc"version = "1.11.0"@@ -109,12 +105,6 @@ dependencies = ["zlib-rs",]-[[package]]-name = "grid"-version = "0.15.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "36119f3a540b086b4e436bb2b588cf98a68863470e0e880f4d0842f112a3183a"-[[package]]name = "miniz_oxide"version = "0.8.9"@@ -135,15 +125,6 @@ dependencies = ["simd-adler32",]-[[package]]-name = "num-traits"-version = "0.2.19"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"-dependencies = [- "autocfg",-]-[[package]]name = "paste"version = "1.0.15"@@ -251,15 +232,13 @@ dependencies = [[[package]]name = "taffy"-version = "0.6.3"+version = "0.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "136661daffcdfb128afb0d45a8f7e88078739196d64d7ffa47f8513f4a00a6d7"+checksum = "31f7bd2d97198df05186f93a3a3c306845f40e8b3c22bf9279cdd7e5cf5fea7d"dependencies = [- "arrayvec",- "grid",- "num-traits","serde","slotmap",+ "smallvec",][[package]]diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.tomlindex 45f8d01..6b45684 100644--- a/bindings/rust/Cargo.toml+++ b/bindings/rust/Cargo.toml@@ -1,6 +1,6 @@[workspace]resolver = "2"-members = ["blenderui-sys", "blenderui-macros", "blenderui"]+members = ["blenderui-sys", "blenderui-tailwind", "blenderui-macros", "blenderui"]exclude = ["bench"][workspace.package]diff --git a/bindings/rust/bench/Cargo.lock b/bindings/rust/bench/Cargo.lockindex 76b7860..53440b9 100644--- a/bindings/rust/bench/Cargo.lock+++ b/bindings/rust/bench/Cargo.lock@@ -717,15 +717,19 @@ version = "0.1.0"dependencies = ["blenderui-macros","blenderui-sys",+ "blenderui-tailwind","paste","png 0.17.16","smallvec",- "taffy 0.6.3",+ "taffy 0.15.0",][[package]]name = "blenderui-macros"version = "0.1.0"+dependencies = [+ "blenderui-tailwind",+][[package]]name = "blenderui-sys"@@ -734,6 +738,10 @@ dependencies = ["cmake",]+[[package]]+name = "blenderui-tailwind"+version = "0.1.0"+[[package]]name = "block"version = "0.1.6"@@ -3258,12 +3266,6 @@ dependencies = ["syn 2.0.119",]-[[package]]-name = "grid"-version = "0.15.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "36119f3a540b086b4e436bb2b588cf98a68863470e0e880f4d0842f112a3183a"-[[package]]name = "grid"version = "0.18.0"@@ -6932,19 +6934,6 @@ dependencies = ["libc",]-[[package]]-name = "taffy"-version = "0.6.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "136661daffcdfb128afb0d45a8f7e88078739196d64d7ffa47f8513f4a00a6d7"-dependencies = [- "arrayvec",- "grid 0.15.0",- "num-traits",- "serde",- "slotmap",-]-[[package]]name = "taffy"version = "0.9.0"@@ -6952,7 +6941,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a13e5d13f79d558b5d353a98072ca8ca0e99da429467804de959aa8c83c9a004"dependencies = ["arrayvec",- "grid 0.18.0",+ "grid","serde","slotmap",]diff --git a/bindings/rust/bench/README.md b/bindings/rust/bench/README.mdindex 1accdc1..5e7c4cd 100644--- a/bindings/rust/bench/README.md+++ b/bindings/rust/bench/README.md@@ -1,7 +1,8 @@-# blenderui vs gpui vs gpui-fast+# blenderui (CPU and GPU) vs gpui vs gpui-fastThe same UI on three frameworks:-- `bui-bench`: blenderui.+- `bui-bench`: blenderui, on the software raster (default) or the GPU+ renderer (`BUI_GPU=1`; `run.py` runs it as `blenderui-gpu`).- `gpui-bench`: [gpui](https://crates.io/crates/gpui) 0.2.2, Zed's GPU-rendered framework.- `gpui-fast-bench`: [gpui-fast](https://github.com/longbridge/gpui-fast) 0.1.13, a gpui fork with rendering and layout optimizations.@@ -17,7 +18,8 @@ with a centred number), built with the same element tree in bothchanges: closer to a real UI (a hover, a ticking value), where reusing theprevious frame's work pays off.- **idle**: the scene renders once and then nothing changes.-- **blenderui (uncapped)**: animation without vsync pacing (`--uncapped`).+- **blenderui (uncapped)**: animation without vsync pacing (`--uncapped`), for+ both renderers.## Running@@ -43,74 +45,98 @@ Every configuration ran 3 times, and the table shows the medians.## Results-Ryzen 7 5800U (8 cores / 16 threads, laptop, plugged in), AMD Radeon iGPU,-60 Hz display, Windows 11, release builds. All three apps ran back to back in-one session, 3 runs each, medians shown. This is after blenderui's-arena / compile-time rework (no `Rc` / `RefCell`).+Ryzen 7 5800U (8 cores / 16 threads, laptop, plugged in, 100 % charge), AMD+Radeon iGPU, 60 Hz display, Windows 11, release builds. All four configurations+ran back to back in one session (`py run.py --reps 1 --warmup 2 --seconds 6`).+`blenderui-gpu` is the same binary with `BUI_GPU=1`: the Direct3D 11 renderer+instead of the software raster. Mode `one` changes one cell per frame; `idle`+changes nothing.| App | Cells | Mode | FPS | CPU % (1 core = 100) | CPU ms / frame | GPU 3D % | RAM working set MB | Private MB | GPU memory MB | First frame ms ||---|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|-| gpui | 100 | anim | 60.1 | 20.3 | 3.38 | 5.2 | 31.7 | 35.3 | 16.1 | 257 |-| gpui-fast | 100 | anim | 60.0 | 7.8 | 1.30 | 3.3 | 33.6 | 39.9 | 19.1 | 258 |-| blenderui | 100 | anim | 60.0 | 30.3 | 5.05 | 0 | 19.6 | 11.4 | 0 | 6 |-| gpui | 100 | idle | 0.0 | 0.7 | 0 | 0.0 | 31.4 | 34.9 | 16.1 | 274 |-| gpui-fast | 100 | idle | 0.0 | 0.0 | 0 | 0.0 | 32.5 | 39.0 | 18.8 | 254 |-| blenderui | 100 | idle | 0.0 | 0.0 | 0 | - | 17.8 | 9.5 | 0 | 6 |-| blenderui (uncapped) | 100 | anim | 529.3 | 329.9 | 6.24 | 0 | 19.8 | 11.8 | 0 | 7 |-| gpui | 1000 | anim | 60.1 | 88.4 | 14.73 | 6.1 | 46.0 | 51.7 | 17.1 | 275 |-| gpui-fast | 1000 | anim | 60.0 | 40.4 | 6.74 | 7.2 | 43.4 | 50.9 | 19.9 | 262 |-| blenderui | 1000 | anim | 59.8 | 81.8 | 13.67 | 0 | 23.4 | 15.6 | 0 | 7 |-| gpui | 1000 | idle | 0.0 | 1.4 | 0 | 0.0 | 47.1 | 50.9 | 17.1 | 261 |-| gpui-fast | 1000 | idle | 0.0 | 0.0 | 0 | 0.0 | 42.1 | 49.8 | 19.1 | 262 |-| blenderui | 1000 | idle | 0.0 | 0.0 | 0 | - | 21.6 | 13.5 | 0 | 6 |-| blenderui (uncapped) | 1000 | anim | 156.9 | 236.4 | 14.82 | 0 | 23.7 | 15.9 | 0 | 6 |-| gpui | 3000 | anim | 18.9 | 100.5 | 53.07 | 2.5 | 75.9 | 95.4 | 20.6 | 251 |-| gpui-fast | 3000 | anim | 50.5 | 101.2 | 20.05 | 6.6 | 63.7 | 85.3 | 23.5 | 243 |-| blenderui | 3000 | anim | 57.5 | 157.1 | 27.33 | 0 | 31.2 | 27.9 | 0 | 6 |-| gpui | 3000 | idle | 0.0 | 1.0 | 0 | 0.0 | 73.6 | 92.1 | 20.6 | 252 |-| gpui-fast | 3000 | idle | 0.0 | 0.1 | 0 | 0.0 | 59.7 | 80.9 | 20.9 | 254 |-| blenderui | 3000 | idle | 0.0 | 0.0 | 0 | - | 26.9 | 21.7 | 0 | 6 |-| blenderui (uncapped) | 3000 | anim | 58.1 | 168.0 | 28.90 | 0 | 31.3 | 28.3 | 0 | 6 |--blenderui has no GPU counter instances (shown as 0): it draws on the CPU. `CPU %`-counts all threads, so above 100 means more than one core.+| gpui | 100 | anim | 60.0 | 28.2 | 4.70 | 7.7 | 40.2 | 35.4 | 16.1 | 234 |+| gpui-fast | 100 | anim | 60.0 | 16.0 | 2.67 | 3.8 | 46.7 | 40.4 | 19.1 | 224 |+| blenderui | 100 | anim | 60.1 | 27.7 | 4.62 | - | 20.7 | 11.7 | - | 4 |+| blenderui-gpu | 100 | anim | 60.1 | 7.2 | 1.19 | 8.5 | 27.9 | 21.7 | 19.3 | 5 |+| gpui | 100 | one | 60.0 | 21.1 | 3.52 | 5.9 | 32.8 | 35.6 | 16.1 | 279 |+| gpui-fast | 100 | one | 60.0 | 14.0 | 2.34 | 2.5 | 34.5 | 39.9 | 19.1 | 213 |+| blenderui | 100 | one | 60.1 | 26.5 | 4.41 | - | 19.7 | 10.7 | - | 5 |+| blenderui-gpu | 100 | one | 60.1 | 6.3 | 1.05 | 5.6 | 25.1 | 20.4 | 18.8 | 6 |+| gpui | 100 | idle | 0.2 | 1.4 | - | 0.0 | 32.8 | 35.6 | 16.1 | 212 |+| gpui-fast | 100 | idle | 0.0 | 0.0 | - | 0.0 | 34.0 | 39.4 | 18.9 | 197 |+| blenderui | 100 | idle | 0.0 | 0.0 | - | - | 19.4 | 9.9 | - | 6 |+| blenderui-gpu | 100 | idle | 0.0 | 0.0 | - | 0.0 | 25.8 | 19.1 | 18.3 | 6 |+| blenderui (uncapped) | 100 | anim | 648.6 | 315.0 | 4.86 | - | 20.7 | 11.9 | - | 5 |+| blenderui-gpu (uncapped) | 100 | anim | 1491.2 | 89.8 | 0.60 | 92.1 | 28.3 | 22.2 | 19.5 | 6 |+| gpui | 1000 | anim | 36.4 | 100.9 | 27.73 | 3.8 | 47.2 | 51.6 | 17.1 | 227 |+| gpui-fast | 1000 | anim | 49.2 | 100.9 | 20.52 | 5.5 | 44.5 | 51.2 | 19.9 | 200 |+| blenderui | 1000 | anim | 60.0 | 61.2 | 10.20 | - | 23.8 | 14.9 | - | 5 |+| blenderui-gpu | 1000 | anim | 60.0 | 28.2 | 4.70 | 9.0 | 34.5 | 29.2 | 21.7 | 6 |+| gpui | 1000 | one | 35.7 | 100.9 | 28.26 | 3.6 | 47.3 | 52.3 | 17.1 | 229 |+| gpui-fast | 1000 | one | 29.6 | 59.1 | 19.99 | 2.5 | 44.5 | 51.8 | 19.9 | 197 |+| blenderui | 1000 | one | 60.1 | 61.4 | 10.21 | - | 24.1 | 15.9 | - | 4 |+| blenderui-gpu | 1000 | one | 60.0 | 29.0 | 4.83 | 8.7 | 34.3 | 28.4 | 21.5 | 5 |+| gpui | 1000 | idle | 0.0 | 0.9 | - | 0.0 | 46.4 | 50.9 | 17.1 | 204 |+| gpui-fast | 1000 | idle | 0.2 | 0.4 | - | 0.0 | 43.4 | 50.2 | 19.9 | 212 |+| blenderui | 1000 | idle | 0.3 | 0.9 | - | - | 23.6 | 14.2 | - | 6 |+| blenderui-gpu | 1000 | idle | 0.0 | 0.0 | - | 0.0 | 31.8 | 27.1 | 21.7 | 5 |+| blenderui (uncapped) | 1000 | anim | 202.4 | 233.2 | 11.52 | - | 24.5 | 15.9 | - | 4 |+| blenderui-gpu (uncapped) | 1000 | anim | 309.1 | 101.8 | 3.29 | 42.6 | 35.4 | 29.9 | 21.8 | 4 |+| gpui | 3000 | anim | 19.9 | 100.6 | 50.47 | 3.0 | 77.2 | 95.3 | 20.6 | 210 |+| gpui-fast | 3000 | anim | 31.5 | 100.5 | 31.89 | 4.4 | 64.9 | 85.3 | 23.5 | 193 |+| blenderui | 3000 | anim | 57.6 | 126.7 | 21.98 | - | 30.2 | 26.9 | - | 5 |+| blenderui-gpu | 3000 | anim | 59.9 | 69.4 | 11.58 | 11.0 | 39.6 | 38.0 | 20.8 | 5 |+| gpui | 3000 | one | 20.2 | 100.6 | 49.69 | 4.1 | 76.7 | 94.9 | 20.6 | 215 |+| gpui-fast | 3000 | one | 39.2 | 100.7 | 25.71 | 6.5 | 63.6 | 85.7 | 23.5 | 209 |+| blenderui | 3000 | one | 59.9 | 127.6 | 21.29 | - | 30.1 | 23.9 | - | 5 |+| blenderui-gpu | 3000 | one | 60.1 | 67.3 | 11.20 | 10.2 | 39.2 | 36.4 | 20.8 | 10 |+| gpui | 3000 | idle | 0.0 | 1.1 | - | 0.0 | 74.8 | 92.5 | 20.6 | 205 |+| gpui-fast | 3000 | idle | 0.0 | 0.1 | - | 0.0 | 60.9 | 81.4 | 20.9 | 202 |+| blenderui | 3000 | idle | 0.0 | 0.1 | - | - | 27.9 | 21.4 | - | 5 |+| blenderui-gpu | 3000 | idle | 0.0 | 0.1 | - | 0.0 | 36.0 | 34.2 | 19.6 | 8 |+| blenderui (uncapped) | 3000 | anim | 75.5 | 166.4 | 22.04 | - | 30.5 | 26.2 | - | 4 |+| blenderui-gpu (uncapped) | 3000 | anim | 94.0 | 101.1 | 10.75 | 14.7 | 39.7 | 36.8 | 20.8 | 9 |++The software raster has no GPU counter instances (shown as -). `CPU %` counts+all threads, so above 100 means more than one core. `CPU ms / frame` excludes+GPU work for every app, so read it together with the GPU column.## What it says-| Animated cells | blenderui | gpui-fast | gpui |-|---|---:|---:|---:|-| 100 | 60 fps, 5.1 ms CPU/frame (529 uncapped) | 60 fps, **1.3 ms** + GPU | 60 fps, 3.4 ms + GPU |-| 1000 | 60 fps, 13.7 ms (157 uncapped) | 60 fps, **6.7 ms** + GPU | 60 fps, 14.7 ms + GPU |-| 3000 | **57.5 fps**, 27.3 ms | 50.5 fps, **20.1 ms** + GPU | 18.9 fps, 53.1 ms + GPU |-| RAM working set (3000) | **31 MB** | 64 MB + 24 MB GPU | 76 MB + 21 MB GPU |-| First frame | **~6 ms** | ~250 ms | ~260 ms |-| Idle CPU | **0.0 %** | 0.0-0.1 % | 0.7-1.4 % |--- **Frame rate:** blenderui is fastest at 3000 cells in this session (57.5 vs gpui-fast 50.5; per-run ranges 57.4-58.6 vs 49.9-51.6). Smaller scenes hit the 60 Hz cap in all three. gpui-fast's 3000-cell frame rate varies a lot between sessions on this laptop (29.7, 59.8 and 50.5 fps in three sessions), so compare within a session only.-- **CPU efficiency:** gpui-fast still does the least CPU work per frame (plus GPU work). The gap at 3000 cells has narrowed from 2.1× to 1.4×.-- **Memory and startup:** blenderui uses about half the RAM of either gpui and no GPU memory, and starts about 40× faster.--## Frame-to-frame reuse (mode `one`)--Measured in a later session while the laptop was charging from a low battery,-so everything (all three apps) ran slower than in the table above; only-same-session comparisons are meaningful:--| 3000 cells, same session | blenderui | gpui-fast | gpui |-|---|---:|---:|---:|-| all cells change (`anim`) | 36.8 fps, 47.7 ms CPU/frame | 31.3 fps, 27.4 ms + GPU | 11.3 fps, 89.2 ms + GPU |-| one cell changes (`one`) | **54.0 fps, 27.5 ms** | 29.4 fps, 16.3 ms + GPU | 11.3 fps, 89.1 ms + GPU |--blenderui spends 42 % less CPU per frame when little changes (38 % at 1000-cells). gpui-fast was capped near 30 fps throughout that session (its GPU in a-low-power state), so its frame rate there says little.+| Animated cells | blenderui-gpu | blenderui (CPU raster) | gpui-fast | gpui |+|---|---:|---:|---:|---:|+| 100 | 60 fps, **1.19 ms** CPU/frame (1491 fps uncapped) | 60 fps, 4.62 ms | 60 fps, 2.67 ms | 60 fps, 4.70 ms |+| 1000 | **60 fps, 4.70 ms** (309 uncapped) | 60 fps, 10.2 ms | 49.2 fps, 20.5 ms | 36.4 fps, 27.7 ms |+| 3000 | **59.9 fps, 11.6 ms** (94 uncapped) | 57.6 fps, 22.0 ms | 31.5 fps, 31.9 ms | 19.9 fps, 50.5 ms |+| GPU 3D % (100 / 1000 / 3000) | 8.5 / 9.0 / 11.0 | - | 3.8 / 5.5 / 4.4 | 7.7 / 3.8 / 3.0 |+| RAM working set (100 / 1000 / 3000) | 28 / 35 / 40 MB | **21 / 24 / 30 MB** | 47 / 45 / 65 MB | 40 / 47 / 77 MB |+| GPU memory | 19-22 MB | **0** | 19-24 MB | 16-21 MB |+| First frame | **5-10 ms** | **4-5 ms** | ~200 ms | ~220 ms |+| Idle CPU | **0.0 %** | 0.0-0.9 % | 0.0-0.4 % | 0.9-1.4 % |++- **blenderui-gpu beats gpui-fast on every measurement.** At 100 cells it+ uses 2.2x less CPU per frame (1.19 vs 2.67 ms). At 1000 cells the gap is+ 4.4x (4.70 vs 20.5 ms), and at 3000 cells it is 2.8x (11.6 vs 31.9 ms) at+ nearly twice the frame rate (59.9 vs 31.5 fps). It also uses less RAM, the+ same GPU memory, starts about 40x faster and idles at 0 %.+- **The GPU renderer halves blenderui's own CPU cost** (22.0 to 11.6 ms at+ 3000 cells; 4.6 to 1.2 ms at 100 cells). Rasterization moves to the GPU,+ and what remains on the CPU is the Rust side (cascade, layout, paint list)+ plus recording 128-byte instances. Its GPU load is a few percent of the+ iGPU, about what gpui spends.+- **The software raster stays the lightest on memory** (no D3D runtime or GPU+ memory) and remains the default.+- gpui-fast's heavy-scene frame rate varies a lot between sessions on this+ laptop (29.7, 59.8, 50.5 and now 31.5 fps at 3000 cells), so compare within+ one session only. The previous session's data, before the GPU renderer, is+ in git history.## Caveats- One laptop, one display (60 Hz caps both), the iGPU. A discrete GPU would make gpui's GPU share smaller still.- Laptop clocks vary between sessions. gpui's 1000-cell scene measured 51 fps in this run and 45-60 fps in earlier ones, so the medians are from runs made back to back in one session.- blenderui's root is wrapped in `body().m_0()` so its grid fills the window exactly like gpui's root `div`.-- **Where gpui can't win:** gpui uses a parallel GPU, so a much larger window or a high-DPI display shifts work its way. Every blenderui pixel is CPU work (spread over up to 8 threads).+- **Large or high-DPI windows:** the software raster's cost grows with pixels (spread over up to 8 threads); the GPU renderer's barely does. Use `BUI_GPU=1` / `.gpu(true)` there.- `CPU ms / frame` for gpui excludes its GPU work. Compare it together with the GPU column.## How blenderui got herediff --git a/bindings/rust/bench/results.json b/bindings/rust/bench/results.jsonindex 6a187e2..12516bb 100644--- a/bindings/rust/bench/results.json+++ b/bindings/rust/bench/results.json@@ -4,98 +4,126 @@"cells": 100,"mode": "anim","fps": 60.0,- "cpu_pct": 18.3,- "cpu_ms_per_frame": 3.046,- "gpu_pct": 2.160049611054961,- "ws_mb": 33.6,- "peak_ws_mb": 33.6,- "private_mb": 35.6,+ "cpu_pct": 28.2,+ "cpu_ms_per_frame": 4.696,+ "gpu_pct": 7.74527881392689,+ "ws_mb": 40.2,+ "peak_ws_mb": 40.2,+ "private_mb": 35.4,"gpu_mem_mb": 16.12890625,- "first_frame_ms": 299+ "first_frame_ms": 234},{"app": "gpui-fast","cells": 100,"mode": "anim",- "fps": 60.1,- "cpu_pct": 7.6,- "cpu_ms_per_frame": 1.323,- "gpu_pct": 1.7367879010844638,- "ws_mb": 35.3,- "peak_ws_mb": 35.3,- "private_mb": 40.2,+ "fps": 60.0,+ "cpu_pct": 16.0,+ "cpu_ms_per_frame": 2.675,+ "gpu_pct": 3.804781362567745,+ "ws_mb": 46.7,+ "peak_ws_mb": 46.7,+ "private_mb": 40.4,"gpu_mem_mb": 19.1484375,- "first_frame_ms": 295+ "first_frame_ms": 224},{"app": "blenderui","cells": 100,"mode": "anim",- "fps": 59.9,- "cpu_pct": 36.8,- "cpu_ms_per_frame": 6.168,+ "fps": 60.1,+ "cpu_pct": 27.7,+ "cpu_ms_per_frame": 4.616,"gpu_pct": null,- "ws_mb": 21.2,- "peak_ws_mb": 21.2,- "private_mb": 11.6,+ "ws_mb": 20.7,+ "peak_ws_mb": 20.7,+ "private_mb": 11.7,"gpu_mem_mb": null,- "first_frame_ms": 9+ "first_frame_ms": 4+ },+ {+ "app": "blenderui-gpu",+ "cells": 100,+ "mode": "anim",+ "fps": 60.1,+ "cpu_pct": 7.2,+ "cpu_ms_per_frame": 1.192,+ "gpu_pct": 8.490680562219257,+ "ws_mb": 27.9,+ "peak_ws_mb": 27.9,+ "private_mb": 21.7,+ "gpu_mem_mb": 19.29296875,+ "first_frame_ms": 5},{"app": "gpui","cells": 100,"mode": "one","fps": 60.0,- "cpu_pct": 12.9,- "cpu_ms_per_frame": 2.149,- "gpu_pct": 2.0736485199869437,- "ws_mb": 33.4,- "peak_ws_mb": 33.4,- "private_mb": 35.4,+ "cpu_pct": 21.1,+ "cpu_ms_per_frame": 3.516,+ "gpu_pct": 5.895781827760465,+ "ws_mb": 32.8,+ "peak_ws_mb": 32.9,+ "private_mb": 35.6,"gpu_mem_mb": 16.12890625,- "first_frame_ms": 340+ "first_frame_ms": 279},{"app": "gpui-fast","cells": 100,"mode": "one",- "fps": 29.7,- "cpu_pct": 4.2,- "cpu_ms_per_frame": 1.355,- "gpu_pct": 0.9146514374982673,- "ws_mb": 34.8,- "peak_ws_mb": 35.0,- "private_mb": 39.8,+ "fps": 60.0,+ "cpu_pct": 14.0,+ "cpu_ms_per_frame": 2.342,+ "gpu_pct": 2.541856576909325,+ "ws_mb": 34.5,+ "peak_ws_mb": 34.6,+ "private_mb": 39.9,"gpu_mem_mb": 19.1484375,- "first_frame_ms": 278+ "first_frame_ms": 213},{"app": "blenderui","cells": 100,"mode": "one",- "fps": 59.9,- "cpu_pct": 37.6,- "cpu_ms_per_frame": 6.292,+ "fps": 60.1,+ "cpu_pct": 26.5,+ "cpu_ms_per_frame": 4.414,"gpu_pct": null,- "ws_mb": 20.4,- "peak_ws_mb": 20.6,- "private_mb": 10.9,+ "ws_mb": 19.7,+ "peak_ws_mb": 19.9,+ "private_mb": 10.7,"gpu_mem_mb": null,- "first_frame_ms": 7+ "first_frame_ms": 5+ },+ {+ "app": "blenderui-gpu",+ "cells": 100,+ "mode": "one",+ "fps": 60.1,+ "cpu_pct": 6.3,+ "cpu_ms_per_frame": 1.051,+ "gpu_pct": 5.594142989433645,+ "ws_mb": 25.1,+ "peak_ws_mb": 25.2,+ "private_mb": 20.4,+ "gpu_mem_mb": 18.78515625,+ "first_frame_ms": 6},{"app": "gpui","cells": 100,"mode": "idle",- "fps": 0.0,- "cpu_pct": 1.1,- "cpu_ms_per_frame": 0.0,+ "fps": 0.2,+ "cpu_pct": 1.4,+ "cpu_ms_per_frame": 82.208,"gpu_pct": 0.0,- "ws_mb": 33.1,- "peak_ws_mb": 33.1,- "private_mb": 35.1,+ "ws_mb": 32.8,+ "peak_ws_mb": 32.9,+ "private_mb": 35.6,"gpu_mem_mb": 16.12890625,- "first_frame_ms": 274+ "first_frame_ms": 212},{"app": "gpui-fast",@@ -105,11 +133,11 @@"cpu_pct": 0.0,"cpu_ms_per_frame": 0.0,"gpu_pct": 0.0,- "ws_mb": 34.1,- "peak_ws_mb": 34.1,- "private_mb": 39.2,- "gpu_mem_mb": 18.7578125,- "first_frame_ms": 246+ "ws_mb": 34.0,+ "peak_ws_mb": 34.0,+ "private_mb": 39.4,+ "gpu_mem_mb": 18.94921875,+ "first_frame_ms": 197},{"app": "blenderui",@@ -119,304 +147,444 @@"cpu_pct": 0.0,"cpu_ms_per_frame": 0.0,"gpu_pct": null,- "ws_mb": 19.7,- "peak_ws_mb": 19.7,- "private_mb": 9.7,+ "ws_mb": 19.4,+ "peak_ws_mb": 19.4,+ "private_mb": 9.9,"gpu_mem_mb": null,- "first_frame_ms": 8+ "first_frame_ms": 6+ },+ {+ "app": "blenderui-gpu",+ "cells": 100,+ "mode": "idle",+ "fps": 0.0,+ "cpu_pct": 0.0,+ "cpu_ms_per_frame": 0.0,+ "gpu_pct": 0.0,+ "ws_mb": 25.8,+ "peak_ws_mb": 25.8,+ "private_mb": 19.1,+ "gpu_mem_mb": 18.28515625,+ "first_frame_ms": 6},{"app": "blenderui (uncapped)","cells": 100,"mode": "anim",- "fps": 288.9,- "cpu_pct": 322.2,- "cpu_ms_per_frame": 11.155,+ "fps": 648.6,+ "cpu_pct": 315.0,+ "cpu_ms_per_frame": 4.857,"gpu_pct": null,- "ws_mb": 21.3,- "peak_ws_mb": 21.5,+ "ws_mb": 20.7,+ "peak_ws_mb": 20.8,"private_mb": 11.9,"gpu_mem_mb": null,- "first_frame_ms": 16+ "first_frame_ms": 5+ },+ {+ "app": "blenderui-gpu (uncapped)",+ "cells": 100,+ "mode": "anim",+ "fps": 1491.2,+ "cpu_pct": 89.8,+ "cpu_ms_per_frame": 0.602,+ "gpu_pct": 92.07909147050972,+ "ws_mb": 28.3,+ "peak_ws_mb": 28.3,+ "private_mb": 22.2,+ "gpu_mem_mb": 19.546875,+ "first_frame_ms": 6},{"app": "gpui","cells": 1000,"mode": "anim",- "fps": 54.8,- "cpu_pct": 92.0,- "cpu_ms_per_frame": 16.789,- "gpu_pct": 3.3781059655571912,- "ws_mb": 47.6,- "peak_ws_mb": 48.2,- "private_mb": 51.5,+ "fps": 36.4,+ "cpu_pct": 100.9,+ "cpu_ms_per_frame": 27.726,+ "gpu_pct": 3.764205848581965,+ "ws_mb": 47.2,+ "peak_ws_mb": 47.5,+ "private_mb": 51.6,"gpu_mem_mb": 17.07421875,- "first_frame_ms": 344+ "first_frame_ms": 227},{"app": "gpui-fast","cells": 1000,"mode": "anim",- "fps": 29.7,- "cpu_pct": 27.5,- "cpu_ms_per_frame": 9.231,- "gpu_pct": 1.505138613040445,- "ws_mb": 44.7,- "peak_ws_mb": 44.9,- "private_mb": 50.9,+ "fps": 49.2,+ "cpu_pct": 100.9,+ "cpu_ms_per_frame": 20.515,+ "gpu_pct": 5.504059756315993,+ "ws_mb": 44.5,+ "peak_ws_mb": 44.6,+ "private_mb": 51.2,"gpu_mem_mb": 19.89453125,- "first_frame_ms": 394+ "first_frame_ms": 200},{"app": "blenderui","cells": 1000,"mode": "anim",- "fps": 54.8,- "cpu_pct": 150.5,- "cpu_ms_per_frame": 27.466,+ "fps": 60.0,+ "cpu_pct": 61.2,+ "cpu_ms_per_frame": 10.201,"gpu_pct": null,- "ws_mb": 24.9,- "peak_ws_mb": 25.5,- "private_mb": 16.0,+ "ws_mb": 23.8,+ "peak_ws_mb": 24.7,+ "private_mb": 14.9,"gpu_mem_mb": null,- "first_frame_ms": 12+ "first_frame_ms": 5+ },+ {+ "app": "blenderui-gpu",+ "cells": 1000,+ "mode": "anim",+ "fps": 60.0,+ "cpu_pct": 28.2,+ "cpu_ms_per_frame": 4.702,+ "gpu_pct": 9.046779328061197,+ "ws_mb": 34.5,+ "peak_ws_mb": 35.5,+ "private_mb": 29.2,+ "gpu_mem_mb": 21.69140625,+ "first_frame_ms": 6},{"app": "gpui","cells": 1000,"mode": "one",- "fps": 44.3,- "cpu_pct": 100.0,- "cpu_ms_per_frame": 22.046,- "gpu_pct": 2.5052906138400513,- "ws_mb": 46.2,- "peak_ws_mb": 46.4,- "private_mb": 51.7,+ "fps": 35.7,+ "cpu_pct": 100.9,+ "cpu_ms_per_frame": 28.257,+ "gpu_pct": 3.569115647625785,+ "ws_mb": 47.3,+ "peak_ws_mb": 47.6,+ "private_mb": 52.3,"gpu_mem_mb": 17.07421875,- "first_frame_ms": 345+ "first_frame_ms": 229},{"app": "gpui-fast","cells": 1000,"mode": "one",- "fps": 29.4,- "cpu_pct": 27.1,- "cpu_ms_per_frame": 9.113,- "gpu_pct": 1.8060058098129863,- "ws_mb": 44.9,- "peak_ws_mb": 44.9,- "private_mb": 51.6,+ "fps": 29.6,+ "cpu_pct": 59.1,+ "cpu_ms_per_frame": 19.99,+ "gpu_pct": 2.4599204070895526,+ "ws_mb": 44.5,+ "peak_ws_mb": 44.6,+ "private_mb": 51.8,"gpu_mem_mb": 19.89453125,- "first_frame_ms": 300+ "first_frame_ms": 197},{"app": "blenderui","cells": 1000,"mode": "one",- "fps": 59.5,- "cpu_pct": 101.7,- "cpu_ms_per_frame": 17.131,+ "fps": 60.1,+ "cpu_pct": 61.4,+ "cpu_ms_per_frame": 10.208,"gpu_pct": null,- "ws_mb": 24.7,- "peak_ws_mb": 25.5,- "private_mb": 15.8,+ "ws_mb": 24.1,+ "peak_ws_mb": 25.0,+ "private_mb": 15.9,"gpu_mem_mb": null,- "first_frame_ms": 10+ "first_frame_ms": 4+ },+ {+ "app": "blenderui-gpu",+ "cells": 1000,+ "mode": "one",+ "fps": 60.0,+ "cpu_pct": 29.0,+ "cpu_ms_per_frame": 4.834,+ "gpu_pct": 8.746954225653713,+ "ws_mb": 34.3,+ "peak_ws_mb": 35.0,+ "private_mb": 28.4,+ "gpu_mem_mb": 21.5,+ "first_frame_ms": 5},{"app": "gpui","cells": 1000,"mode": "idle","fps": 0.0,- "cpu_pct": 1.0,+ "cpu_pct": 0.9,"cpu_ms_per_frame": 0.0,"gpu_pct": 0.0,- "ws_mb": 47.3,- "peak_ws_mb": 47.3,- "private_mb": 51.3,- "gpu_mem_mb": 17.51171875,- "first_frame_ms": 387+ "ws_mb": 46.4,+ "peak_ws_mb": 46.4,+ "private_mb": 50.9,+ "gpu_mem_mb": 17.07421875,+ "first_frame_ms": 204},{"app": "gpui-fast","cells": 1000,"mode": "idle",- "fps": 0.0,- "cpu_pct": 0.0,- "cpu_ms_per_frame": 0.0,+ "fps": 0.2,+ "cpu_pct": 0.4,+ "cpu_ms_per_frame": 25.054,"gpu_pct": 0.0,- "ws_mb": 43.7,- "peak_ws_mb": 43.7,- "private_mb": 50.1,+ "ws_mb": 43.4,+ "peak_ws_mb": 43.8,+ "private_mb": 50.2,"gpu_mem_mb": 19.89453125,- "first_frame_ms": 277+ "first_frame_ms": 212},{"app": "blenderui","cells": 1000,"mode": "idle",+ "fps": 0.3,+ "cpu_pct": 0.9,+ "cpu_ms_per_frame": 26.518,+ "gpu_pct": null,+ "ws_mb": 23.6,+ "peak_ws_mb": 23.7,+ "private_mb": 14.2,+ "gpu_mem_mb": null,+ "first_frame_ms": 6+ },+ {+ "app": "blenderui-gpu",+ "cells": 1000,+ "mode": "idle","fps": 0.0,"cpu_pct": 0.0,"cpu_ms_per_frame": 0.0,- "gpu_pct": null,- "ws_mb": 23.4,- "peak_ws_mb": 23.4,- "private_mb": 13.6,- "gpu_mem_mb": null,- "first_frame_ms": 10+ "gpu_pct": 0.0,+ "ws_mb": 31.8,+ "peak_ws_mb": 31.9,+ "private_mb": 27.1,+ "gpu_mem_mb": 21.69140625,+ "first_frame_ms": 5},{"app": "blenderui (uncapped)","cells": 1000,"mode": "anim",- "fps": 86.6,- "cpu_pct": 239.3,- "cpu_ms_per_frame": 27.625,+ "fps": 202.4,+ "cpu_pct": 233.2,+ "cpu_ms_per_frame": 11.523,"gpu_pct": null,- "ws_mb": 25.1,- "peak_ws_mb": 25.6,- "private_mb": 16.0,+ "ws_mb": 24.5,+ "peak_ws_mb": 24.9,+ "private_mb": 15.9,"gpu_mem_mb": null,- "first_frame_ms": 12+ "first_frame_ms": 4+ },+ {+ "app": "blenderui-gpu (uncapped)",+ "cells": 1000,+ "mode": "anim",+ "fps": 309.1,+ "cpu_pct": 101.8,+ "cpu_ms_per_frame": 3.292,+ "gpu_pct": 42.598707686330776,+ "ws_mb": 35.4,+ "peak_ws_mb": 35.9,+ "private_mb": 29.9,+ "gpu_mem_mb": 21.75390625,+ "first_frame_ms": 4},{"app": "gpui","cells": 3000,"mode": "anim",- "fps": 11.3,- "cpu_pct": 100.5,- "cpu_ms_per_frame": 89.241,- "gpu_pct": 1.0648015763039103,- "ws_mb": 77.8,- "peak_ws_mb": 78.6,- "private_mb": 93.7,+ "fps": 19.9,+ "cpu_pct": 100.6,+ "cpu_ms_per_frame": 50.471,+ "gpu_pct": 2.9571464808078,+ "ws_mb": 77.2,+ "peak_ws_mb": 78.0,+ "private_mb": 95.3,"gpu_mem_mb": 20.64453125,- "first_frame_ms": 583+ "first_frame_ms": 210},{"app": "gpui-fast","cells": 3000,"mode": "anim",- "fps": 31.3,- "cpu_pct": 91.8,- "cpu_ms_per_frame": 27.417,- "gpu_pct": 2.254235548767074,+ "fps": 31.5,+ "cpu_pct": 100.5,+ "cpu_ms_per_frame": 31.885,+ "gpu_pct": 4.385109321763488,"ws_mb": 64.9,"peak_ws_mb": 65.5,- "private_mb": 85.1,+ "private_mb": 85.3,"gpu_mem_mb": 23.47265625,- "first_frame_ms": 498+ "first_frame_ms": 193},{"app": "blenderui","cells": 3000,"mode": "anim",- "fps": 36.8,- "cpu_pct": 175.8,- "cpu_ms_per_frame": 47.7,+ "fps": 57.6,+ "cpu_pct": 126.7,+ "cpu_ms_per_frame": 21.979,"gpu_pct": null,- "ws_mb": 30.7,- "peak_ws_mb": 33.2,- "private_mb": 26.1,+ "ws_mb": 30.2,+ "peak_ws_mb": 33.1,+ "private_mb": 26.9,"gpu_mem_mb": null,- "first_frame_ms": 11+ "first_frame_ms": 5+ },+ {+ "app": "blenderui-gpu",+ "cells": 3000,+ "mode": "anim",+ "fps": 59.9,+ "cpu_pct": 69.4,+ "cpu_ms_per_frame": 11.582,+ "gpu_pct": 10.990262499917524,+ "ws_mb": 39.6,+ "peak_ws_mb": 42.2,+ "private_mb": 38.0,+ "gpu_mem_mb": 20.80859375,+ "first_frame_ms": 5},{"app": "gpui","cells": 3000,"mode": "one",- "fps": 11.3,- "cpu_pct": 100.5,- "cpu_ms_per_frame": 89.116,- "gpu_pct": 1.0455488689161836,- "ws_mb": 77.9,- "peak_ws_mb": 78.7,- "private_mb": 95.1,+ "fps": 20.2,+ "cpu_pct": 100.6,+ "cpu_ms_per_frame": 49.685,+ "gpu_pct": 4.146866676585088,+ "ws_mb": 76.7,+ "peak_ws_mb": 77.4,+ "private_mb": 94.9,"gpu_mem_mb": 20.64453125,- "first_frame_ms": 556+ "first_frame_ms": 215},{"app": "gpui-fast","cells": 3000,"mode": "one",- "fps": 29.4,- "cpu_pct": 62.1,- "cpu_ms_per_frame": 16.341,- "gpu_pct": 2.313129568589991,- "ws_mb": 64.2,- "peak_ws_mb": 64.2,- "private_mb": 85.6,+ "fps": 39.2,+ "cpu_pct": 100.7,+ "cpu_ms_per_frame": 25.715,+ "gpu_pct": 6.548003516690843,+ "ws_mb": 63.6,+ "peak_ws_mb": 64.6,+ "private_mb": 85.7,"gpu_mem_mb": 23.47265625,- "first_frame_ms": 358+ "first_frame_ms": 209},{"app": "blenderui","cells": 3000,"mode": "one",- "fps": 54.0,- "cpu_pct": 148.4,- "cpu_ms_per_frame": 27.488,+ "fps": 59.9,+ "cpu_pct": 127.6,+ "cpu_ms_per_frame": 21.29,"gpu_pct": null,- "ws_mb": 31.6,- "peak_ws_mb": 33.9,- "private_mb": 27.2,+ "ws_mb": 30.1,+ "peak_ws_mb": 33.3,+ "private_mb": 23.9,"gpu_mem_mb": null,- "first_frame_ms": 15+ "first_frame_ms": 5+ },+ {+ "app": "blenderui-gpu",+ "cells": 3000,+ "mode": "one",+ "fps": 60.1,+ "cpu_pct": 67.3,+ "cpu_ms_per_frame": 11.195,+ "gpu_pct": 10.188285266632718,+ "ws_mb": 39.2,+ "peak_ws_mb": 42.2,+ "private_mb": 36.4,+ "gpu_mem_mb": 20.80859375,+ "first_frame_ms": 10},{"app": "gpui","cells": 3000,"mode": "idle","fps": 0.0,- "cpu_pct": 1.0,+ "cpu_pct": 1.1,"cpu_ms_per_frame": 0.0,"gpu_pct": 0.0,- "ws_mb": 75.0,- "peak_ws_mb": 75.0,- "private_mb": 91.8,+ "ws_mb": 74.8,+ "peak_ws_mb": 74.8,+ "private_mb": 92.5,"gpu_mem_mb": 20.64453125,- "first_frame_ms": 409+ "first_frame_ms": 205},{"app": "gpui-fast","cells": 3000,"mode": "idle","fps": 0.0,- "cpu_pct": 0.0,+ "cpu_pct": 0.1,"cpu_ms_per_frame": 0.0,"gpu_pct": 0.0,- "ws_mb": 62.0,- "peak_ws_mb": 62.1,- "private_mb": 81.6,- "gpu_mem_mb": 23.47265625,- "first_frame_ms": 359+ "ws_mb": 60.9,+ "peak_ws_mb": 61.0,+ "private_mb": 81.4,+ "gpu_mem_mb": 20.90625,+ "first_frame_ms": 202},{"app": "blenderui","cells": 3000,"mode": "idle","fps": 0.0,- "cpu_pct": 0.0,+ "cpu_pct": 0.1,"cpu_ms_per_frame": 0.0,"gpu_pct": null,- "ws_mb": 30.3,- "peak_ws_mb": 30.3,- "private_mb": 23.1,+ "ws_mb": 27.9,+ "peak_ws_mb": 27.9,+ "private_mb": 21.4,"gpu_mem_mb": null,- "first_frame_ms": 7+ "first_frame_ms": 5+ },+ {+ "app": "blenderui-gpu",+ "cells": 3000,+ "mode": "idle",+ "fps": 0.0,+ "cpu_pct": 0.1,+ "cpu_ms_per_frame": 0.0,+ "gpu_pct": 0.0,+ "ws_mb": 36.0,+ "peak_ws_mb": 36.0,+ "private_mb": 34.2,+ "gpu_mem_mb": 19.6171875,+ "first_frame_ms": 8},{"app": "blenderui (uncapped)","cells": 3000,"mode": "anim",- "fps": 34.7,- "cpu_pct": 173.0,- "cpu_ms_per_frame": 50.11,+ "fps": 75.5,+ "cpu_pct": 166.4,+ "cpu_ms_per_frame": 22.037,"gpu_pct": null,- "ws_mb": 30.8,- "peak_ws_mb": 33.7,- "private_mb": 25.9,+ "ws_mb": 30.5,+ "peak_ws_mb": 32.5,+ "private_mb": 26.2,"gpu_mem_mb": null,+ "first_frame_ms": 4+ },+ {+ "app": "blenderui-gpu (uncapped)",+ "cells": 3000,+ "mode": "anim",+ "fps": 94.0,+ "cpu_pct": 101.1,+ "cpu_ms_per_frame": 10.751,+ "gpu_pct": 14.692075994349425,+ "ws_mb": 39.7,+ "peak_ws_mb": 41.7,+ "private_mb": 36.8,+ "gpu_mem_mb": 20.83984375,"first_frame_ms": 9}]\ No newline at end of filediff --git a/bindings/rust/bench/run.py b/bindings/rust/bench/run.pyindex c831508..aa7870f 100644--- a/bindings/rust/bench/run.py+++ b/bindings/rust/bench/run.py@@ -21,7 +21,10 @@ from pathlib import PathHERE = Path(__file__).resolve().parentEXE = {"blenderui": HERE / "target/release/bui-bench.exe", "gpui": HERE / "target/release/gpui-bench.exe",- "gpui-fast": HERE / "target/release/gpui-fast-bench.exe"}+ "gpui-fast": HERE / "target/release/gpui-fast-bench.exe",+ "blenderui-gpu": HERE / "target/release/bui-bench.exe"}+# per-app environment: blenderui-gpu is blenderui with the GPU renderer+ENV = {"blenderui": {"BUI_GPU": "0"}, "blenderui-gpu": {"BUI_GPU": "1"}}def gpu_sampler(pid, start_after, duration, out):@@ -50,7 +53,9 @@ def gpu_sampler(pid, start_after, duration, out):def run(app, cells, mode, warmup, seconds, extra=()):args = [str(EXE[app]), "--cells", str(cells), "--mode", mode,"--warmup", str(warmup), "--seconds", str(seconds), *extra]- p = subprocess.Popen(args, stdout=subprocess.PIPE, text=True)+ import os+ env = dict(os.environ, **ENV.get(app, {}))+ p = subprocess.Popen(args, stdout=subprocess.PIPE, text=True, env=env)gpu = {}t = threading.Thread(target=gpu_sampler, args=(p.pid, warmup + 1.0, seconds, gpu))t.start()@@ -75,21 +80,22 @@ def main():ap.add_argument("--warmup", type=float, default=3)ap.add_argument("--seconds", type=float, default=10)ap.add_argument("--cells", default="100,1000,3000")- ap.add_argument("--apps", default="gpui,gpui-fast,blenderui")+ ap.add_argument("--apps", default="gpui,gpui-fast,blenderui,blenderui-gpu")a = ap.parse_args()configs = []for cells in map(int, a.cells.split(",")):for mode in ("anim", "one", "idle"):for app in a.apps.split(","):configs.append((app, cells, mode, ()))- if "blenderui" in a.apps.split(","):- configs.append(("blenderui", cells, "anim", ("--uncapped",)))+ for app in ("blenderui", "blenderui-gpu"):+ if app in a.apps.split(","):+ configs.append((app, cells, "anim", ("--uncapped",)))results = []for app, cells, mode, extra in configs:rows = []for rep in range(a.reps):r = run(app, cells, mode, a.warmup, a.seconds, extra)- print(f" {app:9} {cells:5} {mode}{' uncapped' if extra else ''} #{rep + 1}: {json.dumps(r)}",+ print(f" {app:13} {cells:5} {mode}{' uncapped' if extra else ''} #{rep + 1}: {json.dumps(r)}",file=sys.stderr)rows.append(r)label = app + (" (uncapped)" if extra else "")diff --git a/bindings/rust/blenderui-macros/Cargo.toml b/bindings/rust/blenderui-macros/Cargo.tomlindex 52544c6..5ae9092 100644--- a/bindings/rust/blenderui-macros/Cargo.toml+++ b/bindings/rust/blenderui-macros/Cargo.toml@@ -9,3 +9,6 @@ rust-version.workspace = true[lib]proc-macro = true++[dependencies]+blenderui-tailwind = { path = "../blenderui-tailwind", version = "0.1.0" }diff --git a/bindings/rust/blenderui-macros/src/lib.rs b/bindings/rust/blenderui-macros/src/lib.rsindex ce680c7..a6bf6e2 100644--- a/bindings/rust/blenderui-macros/src/lib.rs+++ b/bindings/rust/blenderui-macros/src/lib.rs@@ -19,6 +19,28 @@ pub fn css(input: TokenStream) -> TokenStream {}}+/// `tw!("p-4 md:flex hover:bg-sky-500/50")`: Tailwind classes, checked when+/// the program compiles (a misspelled or unknown utility is a compile+/// error), expanding to the class string for `.class(...)`.+///+#[proc_macro]+pub fn tw(input: TokenStream) -> TokenStream {+ let mut tokens = input.into_iter();+ let lit = match (tokens.next(), tokens.next()) {+ (Some(TokenTree::Literal(l)), None) => l.to_string(),+ _ => return "::core::compile_error!(\"tw! takes one string literal\")".parse().unwrap(),+ };+ let Some(text) = unquote(&lit) else {+ return "::core::compile_error!(\"tw! takes one string literal\")".parse().unwrap();+ };+ let unknown: Vec<&str> = text.split_whitespace().filter(|c| blenderui_tailwind::compile(c).is_none()).collect();+ if !unknown.is_empty() {+ let msg = format!("tw!: not Tailwind utilities: {}", unknown.join(", "));+ return format!("::core::compile_error!({msg:?})").parse().unwrap();+ }+ format!("{text:?}").parse().unwrap()+}+fn expand(input: TokenStream) -> Result<String, String> {let mut tokens = input.into_iter();let lit = match (tokens.next(), tokens.next()) {@@ -46,9 +68,17 @@ fn expand(input: TokenStream) -> Result<String, String> {if value.is_empty() {return Err(format!("css!: missing value for `{name}`"));}+ // custom properties are interned at run time (once per call site)+ let prop = if name.starts_with("--") {+ format!("{{ static P: ::std::sync::OnceLock<::blenderui::css::Prop> = \+ ::std::sync::OnceLock::new(); \+ *P.get_or_init(|| ::blenderui::css::Prop::custom({name:?})) }}")+ } else {+ format!("const {{ ::blenderui::css::Prop::named({name:?}) }}")+ };decls.push(format!("::blenderui::css::Decl {{ \- prop: const {{ ::blenderui::css::Prop::named({name:?}) }}, \+ prop: {prop}, \value: {{ \static V: ::std::sync::OnceLock<::std::boxed::Box<[::blenderui::css::Tok]>> = \::std::sync::OnceLock::new(); \diff --git a/bindings/rust/blenderui-sys/Cargo.toml b/bindings/rust/blenderui-sys/Cargo.tomlindex 6e013c8..0553fa4 100644--- a/bindings/rust/blenderui-sys/Cargo.toml+++ b/bindings/rust/blenderui-sys/Cargo.toml@@ -9,5 +9,9 @@ rust-version.workspace = truelinks = "bui_kit"build = "build.rs"+[features]+# The portable stb_truetype text engine on Windows too (always on elsewhere).+portable-text = []+[build-dependencies]cmake = "0.1"diff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rsindex a81f0ea..e0f74e1 100644--- a/bindings/rust/blenderui-sys/build.rs+++ b/bindings/rust/blenderui-sys/build.rs@@ -12,7 +12,12 @@ fn main() {// Windows canonical paths are \\?\C:\...; compilers' /FI and -include can't take them.let root = PathBuf::from(root.to_string_lossy().trim_start_matches(r"\\?\").to_string());+ // Portable (stb_truetype) text on Windows too: the `portable-text`+ // feature or BUI_TEXT_STB=1. Other platforms always use it.+ let stb = std::env::var("CARGO_FEATURE_PORTABLE_TEXT").is_ok()+ || std::env::var("BUI_TEXT_STB").map(|v| v == "1").unwrap_or(false);let dst = cmake::Config::new(&root)+ .define("BUI_TEXT_STB", if stb { "ON" } else { "OFF" }).define("BUI_BUILD_TESTS", "OFF").define("BUI_BUILD_EXAMPLES", "OFF").define("BUI_BUILD_PYTHON_BINDINGS", "OFF")@@ -45,5 +50,6 @@ fn main() {println!("cargo:rerun-if-changed={}", root.join(dir).display());}println!("cargo:rerun-if-env-changed=BUI_SOURCE_DIR");+ println!("cargo:rerun-if-env-changed=BUI_TEXT_STB");println!("cargo:include={}", root.join("kit/include").display());}diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rsindex 64cd8aa..a264cc7 100644--- a/bindings/rust/blenderui-sys/src/lib.rs+++ b/bindings/rust/blenderui-sys/src/lib.rs@@ -245,4 +245,12 @@ unsafe extern "C" {pub fn BUI_raster_pixels(r: *const BuiRaster) -> *const u32;pub fn BUI_text_measure(family: *const c_char, flags: c_int, size: c_float,utf8: *const c_char, len: c_int, r_width: *mut c_float) -> c_int;+ /// Registers a TrueType/OpenType font (copied) for `family` + style flags.+ /// GPU rendering: default for new windows (BUI_GPU overrides).+ pub fn BUI_gpu_set_default(on: c_int);+ pub fn BUI_gpu_default() -> c_int;+ pub fn BK_window_set_gpu(win: *mut BKWindow, on: c_int);+ pub fn BK_window_gpu(win: *mut BKWindow) -> c_int;+ pub fn BUI_text_add_font(family: *const c_char, flags: c_int, data: *const c_void,+ len: c_int) -> c_int;}diff --git a/bindings/rust/blenderui-tailwind/Cargo.toml b/bindings/rust/blenderui-tailwind/Cargo.tomlnew file mode 100644index 0000000..1dc17cb--- /dev/null+++ b/bindings/rust/blenderui-tailwind/Cargo.toml@@ -0,0 +1,8 @@+[package]+name = "blenderui-tailwind"+description = "Tailwind CSS v4 class compiler (class name -> CSS) for blenderui"+version.workspace = true+edition.workspace = true+license.workspace = true+repository.workspace = true+rust-version.workspace = truediff --git a/bindings/rust/blenderui-tailwind/src/lib.rs b/bindings/rust/blenderui-tailwind/src/lib.rsnew file mode 100644index 0000000..edbffa5--- /dev/null+++ b/bindings/rust/blenderui-tailwind/src/lib.rs@@ -0,0 +1,1457 @@+//! Tailwind CSS v4: class names to CSS, like Tailwind's JIT engine.+//!+//! `compile("md:hover:bg-sky-500/50")` gives the rule for that class:+//! variants (state, pseudo-element, `group-*` / `peer-*`, `has-*`, `data-*`,+//! `aria-*`, `nth-*`, breakpoints, container queries, `dark`, `motion-*`,+//! `supports-*`, arbitrary `[&_p]` ...), utilities with the v4 theme,+//! arbitrary values (`w-[calc(100%-2rem)]`), CSS variable shorthand+//! (`bg-(--brand)`), negatives, opacity modifiers and `!important`.+//!+//! Self-contained (std only) so the `tw!` macro can check classes at+//! compile time with the same code.++mod theme;+use theme::THEME;++/// A compiled class: the CSS (inside `@layer utilities`) and its sort key+/// (Tailwind's order: variants, then property order).+#[derive(Clone, Debug, PartialEq)]+pub struct Compiled {+ pub css: String,+ pub sort: (u32, u32),+}++fn theme(name: &str) -> Option<&'static str> {+ THEME.iter().find(|(k, _)| *k == name).map(|(_, v)| *v)+}++/// The rule for `class`, or None when it isn't a Tailwind class.+pub fn compile(class: &str) -> Option<Compiled> {+ let parts = split_variants(class)?;+ let (variants, utility) = parts.split_at(parts.len() - 1);+ let mut utility = utility[0];+ let mut important = false;+ if let Some(u) = utility.strip_suffix('!') {+ utility = u;+ important = true;+ } else if let Some(u) = utility.strip_prefix('!') {+ utility = u;+ important = true;+ }+ let mut out = utility_decls(utility)?;+ let mut sel = format!(".{}", escape(class));+ let mut wrappers: Vec<String> = Vec::new();+ let mut vweight = 0u32;+ let mut pseudo_el = false;+ // variants apply right to left: the leftmost wraps everything+ for v in variants.iter().rev() {+ let (s, w, weight) = variant(v, &sel)?;+ if let Some(s) = s {+ pseudo_el |= s.contains("::before") || s.contains("::after");+ sel = s;+ }+ if let Some(w) = w {+ wrappers.push(w);+ }+ vweight = vweight.max(weight);+ }+ if pseudo_el && !out.decls.iter().any(|(p, _)| p == "content") {+ out.decls.insert(0, ("content".into(), "''".into()));+ }+ let bang = if important { " !important" } else { "" };+ let body: String = out.decls.iter().map(|(p, v)| format!("{p}: {v}{bang}; ")).collect();+ let mut css = match &out.child {+ Some(child) => format!("{} {{ {body}}}", child.replace('&', &sel)),+ None => format!("{sel} {{ {body}}}"),+ };+ for w in wrappers.iter() {+ css = format!("{w} {{ {css} }}");+ }+ let mut full = format!("@layer utilities {{ {css} }}");+ if let Some(k) = out.keyframes {+ full.push('\n');+ full.push_str(k);+ }+ let prank = out.decls.first().map(|(p, _)| prop_rank(p)).unwrap_or(0);+ Some(Compiled { css: full, sort: (vweight, prank) })+}++/// Split `a:b:[&>p]:c` at top-level colons.+fn split_variants(class: &str) -> Option<Vec<&str>> {+ let mut parts = Vec::new();+ let (mut depth, mut start) = (0i32, 0);+ for (k, c) in class.char_indices() {+ match c {+ '[' | '(' => depth += 1,+ ']' | ')' => depth -= 1,+ ':' if depth == 0 => {+ parts.push(&class[start..k]);+ start = k + 1;+ }+ _ => {}+ }+ }+ parts.push(&class[start..]);+ (!parts.iter().any(|p| p.is_empty())).then_some(parts)+}++/// Escape a class name for use in a selector.+pub fn escape(class: &str) -> String {+ let mut out = String::with_capacity(class.len() + 8);+ for (k, c) in class.chars().enumerate() {+ if c.is_ascii_alphanumeric() && !(k == 0 && c.is_ascii_digit()) || c == '-' || c == '_' {+ out.push(c);+ } else {+ out.push('\\');+ out.push(c);+ }+ }+ out+}++/// `[a_b]` contents: underscores are spaces (`\_` stays an underscore).+fn arbitrary(s: &str) -> Option<String> {+ let inner = s.strip_prefix('[')?.strip_suffix(']')?;+ let mut out = String::with_capacity(inner.len());+ let mut it = inner.chars().peekable();+ while let Some(c) = it.next() {+ match c {+ '\\' if it.peek() == Some(&'_') => {+ out.push('_');+ it.next();+ }+ '_' => out.push(' '),+ c => out.push(c),+ }+ }+ Some(out)+}++/// `(--x)` -> `var(--x)`.+fn css_var(s: &str) -> Option<String> {+ let inner = s.strip_prefix('(')?.strip_suffix(')')?;+ let inner = inner.split_once(':').map(|(_, v)| v).unwrap_or(inner);+ inner.starts_with("--").then(|| format!("var({inner})"))+}++/// An arbitrary or variable value, with an optional type hint (`[length:..]`).+fn free(s: &str) -> Option<(Option<String>, String)> {+ if let Some(v) = css_var(s) {+ let hint = s.trim_start_matches('(').split_once(':').map(|(h, _)| h.to_string());+ return Some((hint, v));+ }+ let a = arbitrary(s)?;+ for hint in ["length", "color", "number", "percentage", "url", "image", "position", "size", "family-name",+ "absolute-size", "relative-size", "line-width", "bg-size", "integer", "angle", "ratio"] {+ if let Some(v) = a.strip_prefix(hint).and_then(|r| r.strip_prefix(':')) {+ return Some((Some(hint.to_string()), v.to_string()));+ }+ }+ Some((None, a))+}++fn is_color_value(v: &str) -> bool {+ let v = v.trim();+ v.starts_with('#') || v.starts_with("rgb") || v.starts_with("hsl") || v.starts_with("oklch")+ || v.starts_with("oklab") || v.starts_with("lab(") || v.starts_with("lch(") || v.starts_with("hwb(")+ || v.starts_with("color(") || v.starts_with("color-mix(") || v.starts_with("light-dark(")+ || v == "transparent" || v == "currentColor" || v == "currentcolor"+ || NAMED_COLORS.contains(&v.to_ascii_lowercase().as_str())+}++const NAMED_COLORS: &[&str] = &[+ "black", "white", "red", "green", "blue", "yellow", "orange", "purple", "pink", "gray", "grey", "silver",+ "maroon", "navy", "teal", "olive", "lime", "aqua", "fuchsia", "cyan", "magenta", "brown", "gold", "indigo",+ "violet", "coral", "salmon", "tomato", "crimson", "khaki", "beige", "ivory", "lavender", "plum", "orchid",+ "tan", "chocolate", "sienna", "peru", "wheat", "linen", "azure", "snow", "mintcream", "honeydew",+ "rebeccapurple", "darkred", "darkgreen", "darkblue", "lightgray", "lightgrey", "darkgray", "darkgrey",+];++/// A spacing value: `4` -> 1rem, `px`, fractions, keywords, arbitrary.+fn spacing(v: &str) -> Option<String> {+ if v == "px" {+ return Some("1px".into());+ }+ if let Some((_, a)) = free(v) {+ return Some(a);+ }+ if let Ok(n) = v.parse::<f32>() {+ if n >= 0.0 && (n * 4.0).fract() == 0.0 {+ let base = theme("spacing")?;+ return Some(if n == 0.0 { "0".into() } else { format!("calc({base} * {})", trim_num(n)) });+ }+ }+ None+}++fn fraction(v: &str) -> Option<String> {+ let (a, b) = v.split_once('/')?;+ let (a, b) = (a.parse::<f32>().ok()?, b.parse::<f32>().ok()?);+ (b != 0.0).then(|| format!("{}%", trim_num(a / b * 100.0)))+}++fn trim_num(n: f32) -> String {+ let s = format!("{n:.6}");+ s.trim_end_matches('0').trim_end_matches('.').to_string()+}++/// Theme colors (`sky-500`), keywords and arbitrary colors, with an+/// optional opacity modifier (`/50`, `/[0.3]`).+fn color(v: &str) -> Option<String> {+ let (base, alpha) = split_modifier(v);+ let c = match base {+ "transparent" => "transparent".to_string(),+ "current" => "currentColor".to_string(),+ "inherit" => "inherit".to_string(),+ "black" | "white" => theme(&format!("color-{base}"))?.to_string(),+ _ => match free(base) {+ Some((hint, a)) if hint.as_deref().is_none_or(|h| h == "color") => {+ if hint.is_none() && !is_color_value(&a) && !a.starts_with("var(") {+ return None;+ }+ a+ }+ Some(_) => return None,+ None => theme(&format!("color-{base}"))?.to_string(),+ },+ };+ Some(match alpha.and_then(opacity) {+ Some(p) => format!("color-mix(in oklab, {c} {p}, transparent)"),+ None => c,+ })+}++/// `50` -> `50%`, `[0.3]` -> `30%`, `(--a)` -> var.+fn opacity(v: &str) -> Option<String> {+ if let Ok(n) = v.parse::<f32>() {+ return Some(format!("{}%", trim_num(n)));+ }+ let (_, a) = free(v)?;+ Some(match a.parse::<f32>() {+ Ok(n) if n <= 1.0 => format!("{}%", trim_num(n * 100.0)),+ _ => a,+ })+}++/// `bg-red-500/50` -> (`red-500`, `50`); not inside brackets.+fn split_modifier(v: &str) -> (&str, Option<&str>) {+ let mut depth = 0;+ for (k, c) in v.char_indices().rev() {+ match c {+ ']' | ')' => depth += 1,+ '[' | '(' => depth -= 1,+ '/' if depth == 0 => return (&v[..k], Some(&v[k + 1..])),+ _ => {}+ }+ }+ (v, None)+}++/// Utility output: declarations, an optional child selector (`& > :not(:last-child)`)+/// and keyframes it needs.+struct Out {+ decls: Vec<(String, String)>,+ child: Option<String>,+ keyframes: Option<&'static str>,+}++fn decls(list: &[(&str, &str)]) -> Option<Out> {+ Some(Out { decls: list.iter().map(|(p, v)| (p.to_string(), v.to_string())).collect(), child: None, keyframes: None })+}++fn one(p: &str, v: String) -> Option<Out> {+ Some(Out { decls: vec![(p.to_string(), v)], child: None, keyframes: None })+}++fn many(props: &[&str], v: String) -> Option<Out> {+ Some(Out { decls: props.iter().map(|p| (p.to_string(), v.clone())).collect(), child: None, keyframes: None })+}++/// Static utilities: exact class name -> declarations.+const STATIC: &[(&str, &[(&str, &str)])] = &[+ // layout+ ("block", &[("display", "block")]), ("inline-block", &[("display", "inline-block")]),+ ("inline", &[("display", "inline")]), ("flex", &[("display", "flex")]),+ ("inline-flex", &[("display", "inline-flex")]), ("grid", &[("display", "grid")]),+ ("inline-grid", &[("display", "inline-grid")]), ("table", &[("display", "table")]),+ ("inline-table", &[("display", "inline-table")]), ("table-row", &[("display", "table-row")]),+ ("table-cell", &[("display", "table-cell")]), ("table-caption", &[("display", "table-caption")]),+ ("table-row-group", &[("display", "table-row-group")]), ("table-header-group", &[("display", "table-header-group")]),+ ("table-footer-group", &[("display", "table-footer-group")]), ("table-column", &[("display", "table-column")]),+ ("table-column-group", &[("display", "table-column-group")]),+ ("contents", &[("display", "contents")]), ("list-item", &[("display", "list-item")]),+ ("hidden", &[("display", "none")]), ("flow-root", &[("display", "flow-root")]),+ ("sr-only", &[("position", "absolute"), ("width", "1px"), ("height", "1px"), ("padding", "0"),+ ("margin", "-1px"), ("overflow", "hidden"), ("clip-path", "inset(50%)"), ("white-space", "nowrap"),+ ("border-width", "0")]),+ ("not-sr-only", &[("position", "static"), ("width", "auto"), ("height", "auto"), ("padding", "0"),+ ("margin", "0"), ("overflow", "visible"), ("clip-path", "none"), ("white-space", "normal")]),+ ("static", &[("position", "static")]), ("fixed", &[("position", "fixed")]),+ ("absolute", &[("position", "absolute")]), ("relative", &[("position", "relative")]),+ ("sticky", &[("position", "sticky")]),+ ("visible", &[("visibility", "visible")]), ("invisible", &[("visibility", "hidden")]),+ ("collapse", &[("visibility", "collapse")]),+ ("isolate", &[("isolation", "isolate")]), ("isolation-auto", &[("isolation", "auto")]),+ ("box-border", &[("box-sizing", "border-box")]), ("box-content", &[("box-sizing", "content-box")]),+ ("float-left", &[("float", "left")]), ("float-right", &[("float", "right")]),+ ("float-start", &[("float", "inline-start")]), ("float-end", &[("float", "inline-end")]),+ ("float-none", &[("float", "none")]),+ ("clear-left", &[("clear", "left")]), ("clear-right", &[("clear", "right")]),+ ("clear-both", &[("clear", "both")]), ("clear-none", &[("clear", "none")]),+ ("clear-start", &[("clear", "inline-start")]), ("clear-end", &[("clear", "inline-end")]),+ ("container", &[("width", "100%")]),+ ("truncate", &[("overflow", "hidden"), ("text-overflow", "ellipsis"), ("white-space", "nowrap")]),+ // flex & grid+ ("flex-row", &[("flex-direction", "row")]), ("flex-row-reverse", &[("flex-direction", "row-reverse")]),+ ("flex-col", &[("flex-direction", "column")]), ("flex-col-reverse", &[("flex-direction", "column-reverse")]),+ ("flex-wrap", &[("flex-wrap", "wrap")]), ("flex-wrap-reverse", &[("flex-wrap", "wrap-reverse")]),+ ("flex-nowrap", &[("flex-wrap", "nowrap")]),+ ("flex-auto", &[("flex", "auto")]), ("flex-initial", &[("flex", "0 auto")]), ("flex-none", &[("flex", "none")]),+ ("grow", &[("flex-grow", "1")]), ("shrink", &[("flex-shrink", "1")]),+ ("grid-flow-row", &[("grid-auto-flow", "row")]), ("grid-flow-col", &[("grid-auto-flow", "column")]),+ ("grid-flow-dense", &[("grid-auto-flow", "dense")]), ("grid-flow-row-dense", &[("grid-auto-flow", "row dense")]),+ ("grid-flow-col-dense", &[("grid-auto-flow", "column dense")]),+ ("col-auto", &[("grid-column", "auto")]), ("row-auto", &[("grid-row", "auto")]),+ ("col-span-full", &[("grid-column", "1 / -1")]), ("row-span-full", &[("grid-row", "1 / -1")]),+ ("auto-cols-auto", &[("grid-auto-columns", "auto")]), ("auto-cols-min", &[("grid-auto-columns", "min-content")]),+ ("auto-cols-max", &[("grid-auto-columns", "max-content")]), ("auto-cols-fr", &[("grid-auto-columns", "minmax(0, 1fr)")]),+ ("auto-rows-auto", &[("grid-auto-rows", "auto")]), ("auto-rows-min", &[("grid-auto-rows", "min-content")]),+ ("auto-rows-max", &[("grid-auto-rows", "max-content")]), ("auto-rows-fr", &[("grid-auto-rows", "minmax(0, 1fr)")]),+ ("grid-cols-none", &[("grid-template-columns", "none")]), ("grid-rows-none", &[("grid-template-rows", "none")]),+ ("grid-cols-subgrid", &[("grid-template-columns", "subgrid")]), ("grid-rows-subgrid", &[("grid-template-rows", "subgrid")]),+ // typography+ ("italic", &[("font-style", "italic")]), ("not-italic", &[("font-style", "normal")]),+ ("underline", &[("text-decoration-line", "underline")]), ("overline", &[("text-decoration-line", "overline")]),+ ("line-through", &[("text-decoration-line", "line-through")]), ("no-underline", &[("text-decoration-line", "none")]),+ ("uppercase", &[("text-transform", "uppercase")]), ("lowercase", &[("text-transform", "lowercase")]),+ ("capitalize", &[("text-transform", "capitalize")]), ("normal-case", &[("text-transform", "none")]),+ ("text-ellipsis", &[("text-overflow", "ellipsis")]), ("text-clip", &[("text-overflow", "clip")]),+ ("text-wrap", &[("text-wrap", "wrap")]), ("text-nowrap", &[("text-wrap", "nowrap")]),+ ("text-balance", &[("text-wrap", "balance")]), ("text-pretty", &[("text-wrap", "pretty")]),+ ("antialiased", &[("-webkit-font-smoothing", "antialiased")]), ("subpixel-antialiased", &[("-webkit-font-smoothing", "auto")]),+ ("ordinal", &[("font-variant-numeric", "ordinal")]), ("slashed-zero", &[("font-variant-numeric", "slashed-zero")]),+ ("lining-nums", &[("font-variant-numeric", "lining-nums")]), ("oldstyle-nums", &[("font-variant-numeric", "oldstyle-nums")]),+ ("proportional-nums", &[("font-variant-numeric", "proportional-nums")]), ("tabular-nums", &[("font-variant-numeric", "tabular-nums")]),+ ("diagonal-fractions", &[("font-variant-numeric", "diagonal-fractions")]), ("stacked-fractions", &[("font-variant-numeric", "stacked-fractions")]),+ ("normal-nums", &[("font-variant-numeric", "normal")]),+ ("break-normal", &[("overflow-wrap", "normal"), ("word-break", "normal")]), ("break-all", &[("word-break", "break-all")]),+ ("break-keep", &[("word-break", "keep-all")]), ("break-words", &[("overflow-wrap", "break-word")]),+ ("wrap-break-word", &[("overflow-wrap", "break-word")]), ("wrap-anywhere", &[("overflow-wrap", "anywhere")]), ("wrap-normal", &[("overflow-wrap", "normal")]),+ ("hyphens-none", &[("hyphens", "none")]), ("hyphens-manual", &[("hyphens", "manual")]), ("hyphens-auto", &[("hyphens", "auto")]),+ ("list-inside", &[("list-style-position", "inside")]), ("list-outside", &[("list-style-position", "outside")]),+ ("list-none", &[("list-style-type", "none")]), ("list-disc", &[("list-style-type", "disc")]),+ ("list-decimal", &[("list-style-type", "decimal")]),+ ("whitespace-normal", &[("white-space", "normal")]), ("whitespace-nowrap", &[("white-space", "nowrap")]),+ ("whitespace-pre", &[("white-space", "pre")]), ("whitespace-pre-line", &[("white-space", "pre-line")]),+ ("whitespace-pre-wrap", &[("white-space", "pre-wrap")]), ("whitespace-break-spaces", &[("white-space", "break-spaces")]),+ ("decoration-solid", &[("text-decoration-style", "solid")]), ("decoration-double", &[("text-decoration-style", "double")]),+ ("decoration-dotted", &[("text-decoration-style", "dotted")]), ("decoration-dashed", &[("text-decoration-style", "dashed")]),+ ("decoration-wavy", &[("text-decoration-style", "wavy")]),+ ("decoration-from-font", &[("text-decoration-thickness", "from-font")]), ("decoration-auto", &[("text-decoration-thickness", "auto")]),+ ("align-baseline", &[("vertical-align", "baseline")]), ("align-top", &[("vertical-align", "top")]),+ ("align-middle", &[("vertical-align", "middle")]), ("align-bottom", &[("vertical-align", "bottom")]),+ ("align-text-top", &[("vertical-align", "text-top")]), ("align-text-bottom", &[("vertical-align", "text-bottom")]),+ ("align-sub", &[("vertical-align", "sub")]), ("align-super", &[("vertical-align", "super")]),+ // backgrounds+ ("bg-fixed", &[("background-attachment", "fixed")]), ("bg-local", &[("background-attachment", "local")]),+ ("bg-scroll", &[("background-attachment", "scroll")]),+ ("bg-clip-border", &[("background-clip", "border-box")]), ("bg-clip-padding", &[("background-clip", "padding-box")]),+ ("bg-clip-content", &[("background-clip", "content-box")]), ("bg-clip-text", &[("background-clip", "text")]),+ ("bg-origin-border", &[("background-origin", "border-box")]), ("bg-origin-padding", &[("background-origin", "padding-box")]),+ ("bg-origin-content", &[("background-origin", "content-box")]),+ ("bg-repeat", &[("background-repeat", "repeat")]), ("bg-no-repeat", &[("background-repeat", "no-repeat")]),+ ("bg-repeat-x", &[("background-repeat", "repeat-x")]), ("bg-repeat-y", &[("background-repeat", "repeat-y")]),+ ("bg-repeat-round", &[("background-repeat", "round")]), ("bg-repeat-space", &[("background-repeat", "space")]),+ ("bg-auto", &[("background-size", "auto")]), ("bg-cover", &[("background-size", "cover")]),+ ("bg-contain", &[("background-size", "contain")]), ("bg-none", &[("background-image", "none")]),+ // borders+ ("border-solid", &[("border-style", "solid")]), ("border-dashed", &[("border-style", "dashed")]),+ ("border-dotted", &[("border-style", "dotted")]), ("border-double", &[("border-style", "double")]),+ ("border-hidden", &[("border-style", "hidden")]), ("border-none", &[("border-style", "none")]),+ ("outline-hidden", &[("outline", "2px solid transparent"), ("outline-offset", "2px")]),+ ("outline-none", &[("outline-style", "none")]), ("outline-solid", &[("outline-style", "solid")]),+ ("outline-dashed", &[("outline-style", "dashed")]), ("outline-dotted", &[("outline-style", "dotted")]),+ ("outline-double", &[("outline-style", "double")]),+ ("border-collapse", &[("border-collapse", "collapse")]), ("border-separate", &[("border-collapse", "separate")]),+ ("table-auto", &[("table-layout", "auto")]), ("table-fixed", &[("table-layout", "fixed")]),+ ("caption-top", &[("caption-side", "top")]), ("caption-bottom", &[("caption-side", "bottom")]),+ // effects & interactivity+ ("pointer-events-none", &[("pointer-events", "none")]), ("pointer-events-auto", &[("pointer-events", "auto")]),+ ("resize-none", &[("resize", "none")]), ("resize", &[("resize", "both")]), ("resize-x", &[("resize", "horizontal")]),+ ("resize-y", &[("resize", "vertical")]),+ ("select-none", &[("user-select", "none")]), ("select-text", &[("user-select", "text")]),+ ("select-all", &[("user-select", "all")]), ("select-auto", &[("user-select", "auto")]),+ ("appearance-none", &[("appearance", "none")]), ("appearance-auto", &[("appearance", "auto")]),+ ("scroll-auto", &[("scroll-behavior", "auto")]), ("scroll-smooth", &[("scroll-behavior", "smooth")]),+ ("snap-start", &[("scroll-snap-align", "start")]), ("snap-end", &[("scroll-snap-align", "end")]),+ ("snap-center", &[("scroll-snap-align", "center")]), ("snap-align-none", &[("scroll-snap-align", "none")]),+ ("snap-normal", &[("scroll-snap-stop", "normal")]), ("snap-always", &[("scroll-snap-stop", "always")]),+ ("snap-none", &[("scroll-snap-type", "none")]), ("snap-x", &[("scroll-snap-type", "x mandatory")]),+ ("snap-y", &[("scroll-snap-type", "y mandatory")]), ("snap-both", &[("scroll-snap-type", "both mandatory")]),+ ("transform-none", &[("transform", "none")]), ("transform-gpu", &[("will-change", "transform")]),+ ("transform-cpu", &[("will-change", "auto")]),+ ("transform-3d", &[("transform-style", "preserve-3d")]), ("transform-flat", &[("transform-style", "flat")]),+ ("backface-visible", &[("backface-visibility", "visible")]), ("backface-hidden", &[("backface-visibility", "hidden")]),+ ("transition", &[("transition-property", "color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, translate, scale, rotate, filter, backdrop-filter"),+ ("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"), ("transition-duration", "150ms")]),+ ("transition-all", &[("transition-property", "all"), ("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"),+ ("transition-duration", "150ms")]),+ ("transition-colors", &[("transition-property", "color, background-color, border-color, outline-color, text-decoration-color, fill, stroke"),+ ("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"), ("transition-duration", "150ms")]),+ ("transition-opacity", &[("transition-property", "opacity"), ("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"),+ ("transition-duration", "150ms")]),+ ("transition-shadow", &[("transition-property", "box-shadow"), ("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"),+ ("transition-duration", "150ms")]),+ ("transition-transform", &[("transition-property", "transform, translate, scale, rotate"),+ ("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"), ("transition-duration", "150ms")]),+ ("transition-none", &[("transition-property", "none")]),+ ("ease-linear", &[("transition-timing-function", "linear")]),+ ("ease-in", &[("transition-timing-function", "cubic-bezier(0.4, 0, 1, 1)")]),+ ("ease-out", &[("transition-timing-function", "cubic-bezier(0, 0, 0.2, 1)")]),+ ("ease-in-out", &[("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)")]),+ ("ease-initial", &[("transition-timing-function", "initial")]),+ ("animate-none", &[("animation", "none")]),+ ("filter-none", &[("filter", "none")]), ("backdrop-filter-none", &[("backdrop-filter", "none")]),+ ("grayscale", &[("filter", "grayscale(100%)")]), ("invert", &[("filter", "invert(100%)")]),+ ("sepia", &[("filter", "sepia(100%)")]),+ ("backdrop-grayscale", &[("backdrop-filter", "grayscale(100%)")]), ("backdrop-invert", &[("backdrop-filter", "invert(100%)")]),+ ("backdrop-sepia", &[("backdrop-filter", "sepia(100%)")]),+ ("field-sizing-content", &[("field-sizing", "content")]), ("field-sizing-fixed", &[("field-sizing", "fixed")]),+ ("scheme-normal", &[("color-scheme", "normal")]), ("scheme-dark", &[("color-scheme", "dark")]),+ ("scheme-light", &[("color-scheme", "light")]), ("scheme-light-dark", &[("color-scheme", "light dark")]),+ ("scheme-only-dark", &[("color-scheme", "only dark")]), ("scheme-only-light", &[("color-scheme", "only light")]),+ ("forced-color-adjust-auto", &[("forced-color-adjust", "auto")]), ("forced-color-adjust-none", &[("forced-color-adjust", "none")]),+ ("object-contain", &[("object-fit", "contain")]), ("object-cover", &[("object-fit", "cover")]),+ ("object-fill", &[("object-fit", "fill")]), ("object-none", &[("object-fit", "none")]),+ ("object-scale-down", &[("object-fit", "scale-down")]),+ ("overflow-auto", &[("overflow", "auto")]), ("overflow-hidden", &[("overflow", "hidden")]),+ ("overflow-clip", &[("overflow", "clip")]), ("overflow-visible", &[("overflow", "visible")]),+ ("overflow-scroll", &[("overflow", "scroll")]),+ ("overflow-x-auto", &[("overflow-x", "auto")]), ("overflow-y-auto", &[("overflow-y", "auto")]),+ ("overflow-x-hidden", &[("overflow-x", "hidden")]), ("overflow-y-hidden", &[("overflow-y", "hidden")]),+ ("overflow-x-clip", &[("overflow-x", "clip")]), ("overflow-y-clip", &[("overflow-y", "clip")]),+ ("overflow-x-visible", &[("overflow-x", "visible")]), ("overflow-y-visible", &[("overflow-y", "visible")]),+ ("overflow-x-scroll", &[("overflow-x", "scroll")]), ("overflow-y-scroll", &[("overflow-y", "scroll")]),+ ("overscroll-auto", &[("overscroll-behavior", "auto")]), ("overscroll-contain", &[("overscroll-behavior", "contain")]),+ ("overscroll-none", &[("overscroll-behavior", "none")]),+ ("bg-blend-normal", &[("background-blend-mode", "normal")]),+ ("mix-blend-normal", &[("mix-blend-mode", "normal")]), ("mix-blend-plus-darker", &[("mix-blend-mode", "plus-darker")]),+ ("mix-blend-plus-lighter", &[("mix-blend-mode", "plus-lighter")]),+ ("content-none", &[("content", "none")]),+ ("break-before-auto", &[("break-before", "auto")]), ("break-after-auto", &[("break-after", "auto")]),+ ("break-inside-auto", &[("break-inside", "auto")]), ("break-inside-avoid", &[("break-inside", "avoid")]),+ ("box-decoration-clone", &[("box-decoration-break", "clone")]), ("box-decoration-slice", &[("box-decoration-break", "slice")]),+ ("touch-auto", &[("touch-action", "auto")]), ("touch-none", &[("touch-action", "none")]),+ ("touch-manipulation", &[("touch-action", "manipulation")]),+ ("will-change-auto", &[("will-change", "auto")]), ("will-change-scroll", &[("will-change", "scroll-position")]),+ ("will-change-contents", &[("will-change", "contents")]), ("will-change-transform", &[("will-change", "transform")]),+ ("rounded-none", &[("border-radius", "0")]), ("rounded-full", &[("border-radius", "calc(infinity * 1px)")]),+ ("shadow-none", &[("box-shadow", "0 0 #0000")]), ("inset-shadow-none", &[("box-shadow", "0 0 #0000")]),+ ("text-shadow-none", &[("text-shadow", "none")]), ("drop-shadow-none", &[("filter", "drop-shadow(0 0 #0000)")]),+];++const BLEND: &[&str] = &["multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn",+ "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"];++const CURSORS: &[&str] = &["auto", "default", "pointer", "wait", "text", "move", "help", "not-allowed", "none",+ "context-menu", "progress", "cell", "crosshair", "vertical-text", "alias", "copy", "no-drop", "grab", "grabbing",+ "all-scroll", "col-resize", "row-resize", "n-resize", "e-resize", "s-resize", "w-resize", "ne-resize", "nw-resize",+ "se-resize", "sw-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "zoom-in", "zoom-out"];++/// Sizes for width / height: spacing, fractions, keywords, containers.+fn size(v: &str, axis: char) -> Option<String> {+ Some(match v {+ "auto" => "auto".into(),+ "full" => "100%".into(),+ "screen" => if axis == 'w' { "100vw".into() } else { "100vh".into() },+ "dvw" | "svw" | "lvw" | "dvh" | "svh" | "lvh" => format!("100{v}"),+ "min" => "min-content".into(),+ "max" => "max-content".into(),+ "fit" => "fit-content".into(),+ "lh" => "1lh".into(),+ "none" => "none".into(),+ "prose" => "65ch".into(),+ _ if axis == 'w' && theme(&format!("container-{v}")).is_some() => theme(&format!("container-{v}"))?.into(),+ _ if v.starts_with("screen-") => theme(&format!("breakpoint-{}", &v[7..]))?.into(),+ _ => fraction(v).or_else(|| spacing(v))?,+ })+}++fn sides(prefix: &str) -> Option<&'static [&'static str]> {+ Some(match prefix {+ "" => &[""],+ "x" => &["-inline"],+ "y" => &["-block"],+ "s" => &["-inline-start"],+ "e" => &["-inline-end"],+ "t" => &["-top"],+ "r" => &["-right"],+ "b" => &["-bottom"],+ "l" => &["-left"],+ "bs" => &["-block-start"],+ "be" => &["-block-end"],+ _ => return None,+ })+}++/// The declarations for one utility (no variants).+fn utility_decls(u: &str) -> Option<Out> {+ // arbitrary property: [mask-type:luminance]+ if u.starts_with('[') && u.ends_with(']') {+ let a = arbitrary(u)?;+ let (p, v) = a.split_once(':')?;+ return one(p.trim(), v.trim().to_string());+ }+ if let Some((_, d)) = STATIC.iter().find(|(n, _)| *n == u) {+ return decls(d);+ }+ let (neg, u) = match u.strip_prefix('-') {+ Some(r) => (true, r),+ None => (false, u),+ };+ let negate = |v: String| if neg { format!("calc({v} * -1)") } else { v };+ // longest matching root first+ let (root, val) = split_root(u)?;+ let v = val;+ let out = match root {+ // ---- spacing+ "p" | "px" | "py" | "ps" | "pe" | "pt" | "pr" | "pb" | "pl" | "pbs" | "pbe" if !neg => {+ let s = sides(&root[1..])?;+ let val = spacing(v)?;+ let props: Vec<String> = s.iter().map(|x| format!("padding{x}")).collect();+ Out { decls: props.into_iter().map(|p| (p, val.clone())).collect(), child: None, keyframes: None }+ }+ "m" | "mx" | "my" | "ms" | "me" | "mt" | "mr" | "mb" | "ml" | "mbs" | "mbe" => {+ let s = sides(&root[1..])?;+ let val = if v == "auto" { "auto".into() } else { negate(spacing(v)?) };+ Out { decls: s.iter().map(|x| (format!("margin{x}"), val.clone())).collect(), child: None, keyframes: None }+ }+ "space-x" | "space-y" => {+ let val = negate(spacing(v)?);+ let p = if root == "space-x" { "margin-inline-end" } else { "margin-block-end" };+ Out { decls: vec![(p.into(), val)], child: Some("& > :not(:last-child)".into()), keyframes: None }+ }+ "gap" | "gap-x" | "gap-y" if !neg => {+ let p = match root { "gap" => "gap", "gap-x" => "column-gap", _ => "row-gap" };+ one(p, spacing(v)?)?+ }+ // ---- sizing+ "w" | "min-w" | "max-w" if !neg => {+ let p = match root { "w" => "width", "min-w" => "min-width", _ => "max-width" };+ one(p, size(v, 'w')?)?+ }+ "h" | "min-h" | "max-h" if !neg => {+ let p = match root { "h" => "height", "min-h" => "min-height", _ => "max-height" };+ one(p, size(v, 'h')?)?+ }+ "size" if !neg => many(&["width", "height"], size(v, 'w')?)?,+ "inline" | "min-inline" | "max-inline" if !neg => {+ let p = match root { "inline" => "inline-size", "min-inline" => "min-inline-size", _ => "max-inline-size" };+ one(p, size(v, 'w')?)?+ }+ "block" | "min-block" | "max-block" if !neg => {+ let p = match root { "block" => "block-size", "min-block" => "min-block-size", _ => "max-block-size" };+ one(p, size(v, 'h')?)?+ }+ // ---- position+ "inset" | "inset-x" | "inset-y" | "start" | "end" | "top" | "right" | "bottom" | "left" => {+ let val = match v {+ "auto" => "auto".into(),+ "full" => negate("100%".into()),+ _ => negate(fraction(v).or_else(|| spacing(v))?),+ };+ let props: &[&str] = match root {+ "inset" => &["inset"],+ "inset-x" => &["inset-inline"],+ "inset-y" => &["inset-block"],+ "start" => &["inset-inline-start"],+ "end" => &["inset-inline-end"],+ r => std::slice::from_ref(match r { "top" => &"top", "right" => &"right", "bottom" => &"bottom", _ => &"left" }),+ };+ many(props, val)?+ }+ "z" => one("z-index", if v == "auto" { "auto".into() } else { negate(int_or_free(v)?) })?,+ "order" => one("order", match v {+ "first" => "-9999".into(),+ "last" => "9999".into(),+ "none" => "0".into(),+ _ => negate(int_or_free(v)?),+ })?,+ // ---- flex & grid+ "basis" if !neg => one("flex-basis", match v {+ "auto" => "auto".into(),+ "full" => "100%".into(),+ _ => match theme(&format!("container-{v}")) {+ Some(c) => c.into(),+ None => fraction(v).or_else(|| spacing(v))?,+ },+ })?,+ "flex" if !neg => one("flex", match v {+ _ if v.contains('/') && !v.starts_with('[') => format!("{} 1 0%", fraction(v)?),+ _ => num_or_free(v)?,+ })?,+ "grow" | "shrink" if !neg => one(if root == "grow" { "flex-grow" } else { "flex-shrink" }, num_or_free(v)?)?,+ "grid-cols" | "grid-rows" if !neg => {+ let p = if root == "grid-cols" { "grid-template-columns" } else { "grid-template-rows" };+ one(p, match v.parse::<u32>() {+ Ok(n) => format!("repeat({n}, minmax(0, 1fr))"),+ Err(_) => free(v)?.1,+ })?+ }+ "col-span" | "row-span" if !neg => {+ let p = if root == "col-span" { "grid-column" } else { "grid-row" };+ one(p, format!("span {} / span {}", int_or_free(v)?, int_or_free(v)?))?+ }+ "col-start" | "col-end" | "row-start" | "row-end" => {+ let p = match root {+ "col-start" => "grid-column-start",+ "col-end" => "grid-column-end",+ "row-start" => "grid-row-start",+ _ => "grid-row-end",+ };+ one(p, if v == "auto" { "auto".into() } else { negate(int_or_free(v)?) })?+ }+ "col" | "row" if !neg => one(if root == "col" { "grid-column" } else { "grid-row" }, int_or_free(v)?)?,+ "auto-cols" | "auto-rows" if !neg => one(if root == "auto-cols" { "grid-auto-columns" } else { "grid-auto-rows" }, free(v)?.1)?,+ "justify" | "justify-items" | "justify-self" | "content" | "items" | "self" | "place-content" | "place-items"+ | "place-self" if !neg && align_kw(root, v).is_some() => {+ let p = match root {+ "justify" => "justify-content",+ "justify-items" => "justify-items",+ "justify-self" => "justify-self",+ "content" => "align-content",+ "items" => "align-items",+ "self" => "align-self",+ r => r,+ };+ one(p, align_kw(root, v)?)?+ }+ // ---- typography+ "font" if !neg => match v {+ "sans" | "serif" | "mono" => one("font-family", theme(&format!("font-{v}"))?.into())?,+ _ => match theme(&format!("font-weight-{v}")) {+ Some(w) => one("font-weight", w.into())?,+ None => {+ let (hint, a) = free(v)?;+ if hint.as_deref() == Some("family-name") || a.parse::<f32>().is_err() && !a.starts_with("var(") {+ one("font-family", a)?+ } else {+ one("font-weight", a)?+ }+ }+ },+ },+ "text" if !neg => {+ let (base, lh) = split_modifier(v);+ if let Some(sz) = theme(&format!("text-{base}")) {+ let line = match lh {+ Some(l) => leading(l)?,+ None => theme(&format!("text-{base}--line-height")).unwrap_or("1.5").to_string(),+ };+ decls(&[("font-size", sz), ("line-height", &line)])?+ } else if matches!(v, "left" | "center" | "right" | "justify" | "start" | "end") {+ one("text-align", v.into())?+ } else if let Some(c) = color(v) {+ one("color", c)?+ } else {+ let (hint, a) = free(base)?;+ match hint.as_deref() {+ Some("length") | Some("absolute-size") | Some("relative-size") => one("font-size", a)?,+ _ if a.ends_with("px") || a.ends_with("rem") || a.ends_with("em") || a.contains("calc") => one("font-size", a)?,+ _ => one("color", a)?,+ }+ }+ }+ "tracking" => one("letter-spacing", match theme(&format!("tracking-{v}")) {+ Some(t) => negate(t.into()),+ None => negate(free(v)?.1),+ })?,+ "leading" if !neg => one("line-height", leading(v)?)?,+ "line-clamp" if !neg => match v {+ "none" => decls(&[("overflow", "visible"), ("display", "block"), ("-webkit-box-orient", "horizontal"),+ ("-webkit-line-clamp", "unset")])?,+ _ => {+ let n = int_or_free(v)?;+ decls(&[("overflow", "hidden"), ("display", "-webkit-box"), ("-webkit-box-orient", "vertical"),+ ("-webkit-line-clamp", &n), ("line-clamp", &n)])?+ }+ },+ "indent" => one("text-indent", negate(spacing(v)?))?,+ "decoration" if !neg => match color(v) {+ Some(c) => one("text-decoration-color", c)?,+ None => one("text-decoration-thickness", px_or_free(v)?)?,+ },+ "underline-offset" => one("text-underline-offset", if v == "auto" { "auto".into() } else { negate(px_or_free(v)?) })?,+ "list" if !neg => one("list-style-type", free(v)?.1)?,+ "list-image" if !neg => one("list-style-image", if v == "none" { "none".into() } else { free(v)?.1 })?,+ "content" if !neg => one("content", free(v)?.1)?,+ "align" if !neg => one("vertical-align", free(v)?.1)?,+ // ---- backgrounds+ "bg" if !neg => {+ if let Some(c) = color(v) {+ one("background-color", c)?+ } else if let Some(dir) = v.strip_prefix("linear-to-").or_else(|| v.strip_prefix("gradient-to-")) {+ let to = dir_words(dir)?;+ one("background-image", format!("linear-gradient(to {to}, var(--tw-gradient-stops))"))?+ } else if let Some(rest) = v.strip_prefix("linear-") {+ let a = if let Ok(n) = rest.parse::<f32>() { format!("{n}deg") } else { free(rest)?.1 };+ one("background-image", format!("linear-gradient({a}, var(--tw-gradient-stops))"))?+ } else if v == "radial" {+ one("background-image", "radial-gradient(var(--tw-gradient-stops))".into())?+ } else if let Some(rest) = v.strip_prefix("radial-") {+ one("background-image", format!("radial-gradient({}, var(--tw-gradient-stops))", free(rest)?.1))?+ } else if v == "conic" {+ one("background-image", "conic-gradient(var(--tw-gradient-stops))".into())?+ } else if let Some(rest) = v.strip_prefix("conic-") {+ let a = if let Ok(n) = rest.parse::<f32>() { format!("from {n}deg") } else { free(rest)?.1 };+ one("background-image", format!("conic-gradient({a}, var(--tw-gradient-stops))"))?+ } else if let Some(p) = position_kw(v) {+ one("background-position", p)?+ } else {+ let (hint, a) = free(v)?;+ match hint.as_deref() {+ Some("length") | Some("size") | Some("bg-size") => one("background-size", a)?,+ Some("position") => one("background-position", a)?,+ _ if a.starts_with("url(") || a.contains("gradient(") || hint.as_deref() == Some("image") || hint.as_deref() == Some("url") => {+ one("background-image", a)?+ }+ _ => one("background-color", a)?,+ }+ }+ }+ "from" | "via" | "to" if !neg => {+ if let Some(c) = color(v) {+ let stops = match root {+ "from" => format!("{c}, var(--tw-gradient-via, {c}), var(--tw-gradient-to, transparent)"),+ "via" => format!("var(--tw-gradient-from, transparent), {c}, var(--tw-gradient-to, transparent)"),+ _ => format!("var(--tw-gradient-from, transparent), var(--tw-gradient-via, {c}), {c}"),+ };+ Out { decls: vec![(format!("--tw-gradient-{root}"), c), ("--tw-gradient-stops".into(), stops)],+ child: None, keyframes: None }+ } else {+ one(&format!("--tw-gradient-{root}-position"), pct_or_free(v)?)?+ }+ }+ "bg-blend" if !neg && BLEND.contains(&v) => one("background-blend-mode", v.into())?,+ "mix-blend" if !neg && BLEND.contains(&v) => one("mix-blend-mode", v.into())?,+ // ---- borders+ "border" | "border-x" | "border-y" | "border-s" | "border-e" | "border-t" | "border-r" | "border-b"+ | "border-l" | "border-bs" | "border-be" if !neg => {+ let s = sides(root.strip_prefix("border-").unwrap_or(""))?;+ match border_width(v) {+ Some(w) => Out { decls: s.iter().map(|x| (format!("border{x}-width"), w.clone())).collect(),+ child: None, keyframes: None },+ None => {+ let c = color(v)?;+ Out { decls: s.iter().map(|x| (format!("border{x}-color"), c.clone())).collect(), child: None, keyframes: None }+ }+ }+ }+ "rounded" | "rounded-s" | "rounded-e" | "rounded-t" | "rounded-r" | "rounded-b" | "rounded-l" | "rounded-ss"+ | "rounded-se" | "rounded-ee" | "rounded-es" | "rounded-tl" | "rounded-tr" | "rounded-br" | "rounded-bl" if !neg => {+ let r = radius(v)?;+ let props: &[&str] = match root {+ "rounded" => &["border-radius"],+ "rounded-s" => &["border-start-start-radius", "border-end-start-radius"],+ "rounded-e" => &["border-start-end-radius", "border-end-end-radius"],+ "rounded-t" => &["border-top-left-radius", "border-top-right-radius"],+ "rounded-r" => &["border-top-right-radius", "border-bottom-right-radius"],+ "rounded-b" => &["border-bottom-right-radius", "border-bottom-left-radius"],+ "rounded-l" => &["border-top-left-radius", "border-bottom-left-radius"],+ "rounded-ss" => &["border-start-start-radius"],+ "rounded-se" => &["border-start-end-radius"],+ "rounded-ee" => &["border-end-end-radius"],+ "rounded-es" => &["border-end-start-radius"],+ "rounded-tl" => &["border-top-left-radius"],+ "rounded-tr" => &["border-top-right-radius"],+ "rounded-br" => &["border-bottom-right-radius"],+ _ => &["border-bottom-left-radius"],+ };+ many(props, r)?+ }+ "divide-x" | "divide-y" if !neg => {+ let w = border_width(v)?;+ let p = if root == "divide-x" { "border-inline-start-width" } else { "border-top-width" };+ Out { decls: vec![(p.into(), w)], child: Some("& > :not(:last-child) ~ *".into()), keyframes: None }+ }+ "divide" if !neg => Out { decls: vec![("border-color".into(), color(v)?)],+ child: Some("& > :not(:last-child)".into()), keyframes: None },+ "outline" if !neg => match border_width(v) {+ Some(w) => decls(&[("outline-style", "solid"), ("outline-width", &w)])?,+ None => one("outline-color", color(v)?)?,+ },+ "outline-offset" => one("outline-offset", negate(px_or_free(v)?))?,+ "ring" | "inset-ring" if !neg => {+ let inset = if root == "inset-ring" { "inset " } else { "" };+ match border_width(v) {+ Some(w) => one("box-shadow", format!("{inset}0 0 0 {w} var(--tw-ring-color, currentColor)"))?,+ None => one("--tw-ring-color", color(v)?)?,+ }+ }+ "ring-offset" if !neg => match border_width(v) {+ Some(w) => one("--tw-ring-offset-width", w)?,+ None => one("--tw-ring-offset-color", color(v)?)?,+ },+ // ---- effects+ "shadow" | "inset-shadow" | "drop-shadow" | "text-shadow" if !neg => {+ let (base, alpha) = split_modifier(v);+ let key = format!("{root}-{base}");+ let theme_shadow = theme(&key).or_else(|| (base == "DEFAULT").then(|| match root {+ "shadow" => "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",+ "drop-shadow" => "0 1px 2px rgb(0 0 0 / 0.1), 0 1px 1px rgb(0 0 0 / 0.06)",+ "inset-shadow" => "inset 0 2px 4px rgb(0 0 0 / 0.05)",+ _ => "0px 1px 1px rgb(0 0 0 / 0.2)",+ }));+ if let Some(s) = theme_shadow {+ // `shadow-lg/50`: the shadow color's alpha becomes 50%+ let s = match alpha.and_then(opacity) {+ Some(a) => with_shadow_alpha(s, &a),+ None => s.to_string(),+ };+ match root {+ "drop-shadow" => one("filter", s.split(", ").map(|d| format!("drop-shadow({d})")).collect::<Vec<_>>().join(" "))?,+ "text-shadow" => one("text-shadow", s)?,+ _ => one("box-shadow", s)?,+ }+ } else if let Some(c) = color(v) {+ one(&format!("--tw-{root}-color"), c)?+ } else {+ let a = free(v)?.1;+ match root {+ "drop-shadow" => one("filter", format!("drop-shadow({a})"))?,+ "text-shadow" => one("text-shadow", a)?,+ "inset-shadow" => one("box-shadow", format!("inset {a}"))?,+ _ => one("box-shadow", a)?,+ }+ }+ }+ "opacity" if !neg => one("opacity", opacity(v)?)?,+ "blur" | "backdrop-blur" if !neg => {+ let b = match v {+ "none" => "0".to_string(),+ "DEFAULT" => "8px".to_string(),+ _ => theme(&format!("blur-{v}")).map(String::from).or_else(|| free(v).map(|f| f.1))?,+ };+ one(if root == "blur" { "filter" } else { "backdrop-filter" }, format!("blur({b})"))?+ }+ "brightness" | "contrast" | "saturate" | "backdrop-brightness" | "backdrop-contrast" | "backdrop-saturate" if !neg => {+ let f = root.trim_start_matches("backdrop-");+ let p = if root.starts_with("backdrop") { "backdrop-filter" } else { "filter" };+ one(p, format!("{f}({})", pct_num(v)?))?+ }+ "grayscale" | "invert" | "sepia" | "backdrop-grayscale" | "backdrop-invert" | "backdrop-sepia" | "backdrop-opacity" if !neg => {+ let f = root.trim_start_matches("backdrop-");+ let p = if root.starts_with("backdrop") { "backdrop-filter" } else { "filter" };+ one(p, format!("{f}({})", pct_num(v)?))?+ }+ "hue-rotate" | "backdrop-hue-rotate" => {+ let p = if root.starts_with("backdrop") { "backdrop-filter" } else { "filter" };+ one(p, format!("hue-rotate({})", negate(deg(v)?)))?+ }+ // ---- transforms+ "scale" | "scale-x" | "scale-y" | "scale-z" => {+ let s = negate(pct_num(v)?);+ match root {+ "scale" => one("scale", s)?,+ "scale-x" => one("scale", format!("{s} 1"))?,+ "scale-y" => one("scale", format!("1 {s}"))?,+ _ => one("scale", format!("1 1 {s}"))?,+ }+ }+ "rotate" | "rotate-x" | "rotate-y" | "rotate-z" => {+ let d = negate(deg(v)?);+ match root {+ "rotate" => one("rotate", d)?,+ "rotate-x" => one("rotate", format!("x {d}"))?,+ "rotate-y" => one("rotate", format!("y {d}"))?,+ _ => one("rotate", format!("z {d}"))?,+ }+ }+ "translate" | "translate-x" | "translate-y" | "translate-z" => {+ let t = negate(match v { "full" => "100%".into(), "px" => "1px".into(), _ => fraction(v).or_else(|| spacing(v))? });+ match root {+ "translate" => one("translate", format!("{t} {t}"))?,+ "translate-x" => one("translate", format!("{t} 0"))?,+ "translate-y" => one("translate", format!("0 {t}"))?,+ _ => one("translate", format!("0 0 {t}"))?,+ }+ }+ "skew" | "skew-x" | "skew-y" => {+ let d = negate(deg(v)?);+ match root {+ "skew" => one("transform", format!("skewX({d}) skewY({d})"))?,+ "skew-x" => one("transform", format!("skewX({d})"))?,+ _ => one("transform", format!("skewY({d})"))?,+ }+ }+ "origin" | "perspective-origin" if !neg => one(if root == "origin" { "transform-origin" } else { "perspective-origin" },+ position_kw(v).or_else(|| free(v).map(|f| f.1))?)?,+ "perspective" if !neg => one("perspective", match v {+ "none" => "none".into(),+ _ => theme(&format!("perspective-{v}")).map(String::from).or_else(|| free(v).map(|f| f.1))?,+ })?,+ "transform" if !neg => one("transform", free(v)?.1)?,+ // ---- transitions & animation+ "transition" if !neg => decls(&[("transition-property", &free(v)?.1),+ ("transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"),+ ("transition-duration", "150ms")])?,+ "duration" | "delay" if !neg => {+ let ms = match v.parse::<f32>() {+ Ok(n) => format!("{}ms", trim_num(n)),+ Err(_) if v == "initial" => "initial".into(),+ Err(_) => free(v)?.1,+ };+ one(if root == "duration" { "transition-duration" } else { "transition-delay" }, ms)?+ }+ "ease" if !neg => one("transition-timing-function", free(v)?.1)?,+ "animate" if !neg => {+ let (anim, kf): (String, &'static str) = match v {+ "spin" => (theme("animate-spin")?.into(), "@keyframes spin { to { transform: rotate(360deg) } }"),+ "ping" => (theme("animate-ping")?.into(),+ "@keyframes ping { 75%, 100% { transform: scale(2); opacity: 0 } }"),+ "pulse" => (theme("animate-pulse")?.into(), "@keyframes pulse { 50% { opacity: 0.5 } }"),+ "bounce" => (theme("animate-bounce")?.into(),+ "@keyframes bounce { 0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(0.8, 0, 1, 1) } 50% { transform: none; animation-timing-function: cubic-bezier(0, 0, 0.2, 1) } }"),+ _ => (free(v)?.1, ""),+ };+ Out { decls: vec![("animation".into(), anim)], child: None, keyframes: (!kf.is_empty()).then_some(kf) }+ }+ // ---- interactivity, svg, misc+ "cursor" if !neg => one("cursor", if CURSORS.contains(&v) { v.into() } else { free(v)?.1 })?,+ "accent" if !neg => one("accent-color", if v == "auto" { "auto".into() } else { color(v)? })?,+ "caret" if !neg => one("caret-color", color(v)?)?,+ "fill" if !neg => one("fill", if v == "none" { "none".into() } else { color(v)? })?,+ "stroke" if !neg => match color(v) {+ Some(c) => one("stroke", c)?,+ None => one("stroke-width", num_or_free(v)?)?,+ },+ "aspect" if !neg => one("aspect-ratio", match v {+ "auto" => "auto".into(),+ "square" => "1 / 1".into(),+ "video" => theme("aspect-video")?.into(),+ _ if v.contains('/') && !v.starts_with('[') => v.replace('/', " / "),+ _ => free(v)?.1,+ })?,+ "columns" if !neg => one("columns", match v {+ "auto" => "auto".into(),+ _ if v.parse::<u32>().is_ok() => v.into(),+ _ => theme(&format!("container-{v}")).map(String::from).or_else(|| free(v).map(|f| f.1))?,+ })?,+ "object" if !neg => one("object-position", position_kw(v).or_else(|| free(v).map(|f| f.1))?)?,+ "scroll-m" | "scroll-mx" | "scroll-my" | "scroll-ms" | "scroll-me" | "scroll-mt" | "scroll-mr" | "scroll-mb"+ | "scroll-ml" => {+ let s = sides(&root[8..])?;+ let val = negate(spacing(v)?);+ Out { decls: s.iter().map(|x| (format!("scroll-margin{x}"), val.clone())).collect(), child: None, keyframes: None }+ }+ "scroll-p" | "scroll-px" | "scroll-py" | "scroll-ps" | "scroll-pe" | "scroll-pt" | "scroll-pr" | "scroll-pb"+ | "scroll-pl" if !neg => {+ let s = sides(&root[8..])?;+ let val = spacing(v)?;+ Out { decls: s.iter().map(|x| (format!("scroll-padding{x}"), val.clone())).collect(), child: None, keyframes: None }+ }+ "will-change" if !neg => one("will-change", free(v)?.1)?,+ "touch" if !neg => one("touch-action", v.replace("pan-", "pan-"))?,+ "border-spacing" | "border-spacing-x" | "border-spacing-y" if !neg => one("border-spacing", spacing(v)?)?,+ "break-before" | "break-after" | "break-inside" if !neg => one(root, v.into())?,+ "mask" if !neg => one("mask-image", free(v)?.1)?,+ "outline-style" => return None,+ _ => return None,+ };+ Some(out)+}++/// Split `p-4` into (`p`, `4`) using the longest known root.+fn split_root(u: &str) -> Option<(&str, &str)> {+ const ROOTS: &[&str] = &[+ "backdrop-hue-rotate", "backdrop-brightness", "backdrop-contrast", "backdrop-grayscale", "backdrop-saturate",+ "backdrop-opacity", "backdrop-invert", "backdrop-sepia", "backdrop-blur", "perspective-origin",+ "underline-offset", "outline-offset", "border-spacing-x", "border-spacing-y", "border-spacing", "inset-shadow",+ "drop-shadow", "text-shadow", "justify-items", "justify-self", "place-content", "place-items", "place-self",+ "ring-offset", "inset-ring", "will-change", "line-clamp", "list-image", "hue-rotate", "break-before",+ "break-after", "break-inside", "min-inline", "max-inline", "min-block", "max-block", "translate-x",+ "translate-y", "translate-z", "grid-cols", "grid-rows", "col-start", "row-start", "auto-cols", "auto-rows",+ "brightness", "grayscale", "translate", "perspective", "col-span", "row-span", "col-end", "row-end",+ "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br",+ "rounded-bl", "rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded",+ "border-x", "border-y", "border-s", "border-e", "border-t", "border-r", "border-b", "border-l",+ "border-bs", "border-be", "divide-x", "divide-y", "scroll-mx", "scroll-my", "scroll-ms", "scroll-me",+ "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml", "scroll-px", "scroll-py", "scroll-ps", "scroll-pe",+ "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl", "scroll-m", "scroll-p", "rotate-x", "rotate-y",+ "rotate-z", "scale-x", "scale-y", "scale-z", "skew-x", "skew-y", "space-x", "space-y", "bg-blend",+ "mix-blend", "contrast", "saturate", "duration", "tracking", "leading", "opacity", "content", "columns",+ "inset-x", "inset-y", "transform", "transition", "animate", "decoration", "outline", "origin", "invert",+ "sepia", "divide", "border", "shadow", "rotate", "scale", "skew", "basis", "order", "accent", "caret",+ "cursor", "stroke", "aspect", "object", "indent", "gap-x", "gap-y", "min-w", "max-w", "min-h", "max-h",+ "inline", "block", "inset", "start", "items", "justify", "self", "align", "delay", "ease", "blur", "ring",+ "fill", "font", "text", "list", "mask", "touch", "size", "flex", "grow", "shrink", "from", "via", "top",+ "right", "bottom", "left", "end", "col", "row", "gap", "pbs", "pbe", "mbs", "mbe", "bg", "to", "z",+ "px", "py", "ps", "pe", "pt", "pr", "pb", "pl", "mx", "my", "ms", "me", "mt", "mr", "mb", "ml", "p", "m",+ "w", "h",+ ];+ for r in ROOTS {+ if let Some(rest) = u.strip_prefix(r) {+ if let Some(v) = rest.strip_prefix('-') {+ if !v.is_empty() {+ return Some((r, v));+ }+ }+ if rest.is_empty() {+ // bare roots with a default value+ return match *r {+ "border" | "border-x" | "border-y" | "border-s" | "border-e" | "border-t" | "border-r"+ | "border-b" | "border-l" | "outline" | "ring" | "inset-ring" | "divide-x" | "divide-y" => Some((r, "1")),+ "rounded" | "shadow" | "drop-shadow" | "blur" | "backdrop-blur" | "inset-shadow" => Some((r, "DEFAULT")),+ "grow" | "shrink" => Some((r, "1")),+ _ => None,+ };+ }+ }+ }+ None+}++/// Every `rgb(0 0 0 / x)` in a theme shadow with alpha `a`.+fn with_shadow_alpha(s: &str, a: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut rest = s;+ while let Some(k) = rest.find("rgb(0 0 0 / ") {+ out.push_str(&rest[..k + 12]);+ out.push_str(a);+ let after = &rest[k + 12..];+ let end = after.find(')').unwrap_or(after.len());+ rest = &after[end..];+ }+ out.push_str(rest);+ out+}++fn int_or_free(v: &str) -> Option<String> {+ if v.parse::<i32>().is_ok() {+ return Some(v.into());+ }+ free(v).map(|f| f.1)+}++fn num_or_free(v: &str) -> Option<String> {+ if v.parse::<f32>().is_ok() {+ return Some(v.into());+ }+ free(v).map(|f| f.1)+}++fn px_or_free(v: &str) -> Option<String> {+ if let Ok(n) = v.parse::<f32>() {+ return Some(format!("{}px", trim_num(n)));+ }+ free(v).map(|f| f.1)+}++fn pct_or_free(v: &str) -> Option<String> {+ if let Some(p) = v.strip_suffix('%') {+ return p.parse::<f32>().ok().map(|n| format!("{}%", trim_num(n)));+ }+ free(v).map(|f| f.1)+}++/// `150` -> `150%` (filters, scale), arbitrary as is.+fn pct_num(v: &str) -> Option<String> {+ if v == "DEFAULT" {+ return Some("100%".into());+ }+ if let Ok(n) = v.parse::<f32>() {+ return Some(format!("{}%", trim_num(n)));+ }+ free(v).map(|f| f.1)+}++fn deg(v: &str) -> Option<String> {+ if let Ok(n) = v.parse::<f32>() {+ return Some(format!("{}deg", trim_num(n)));+ }+ free(v).map(|f| f.1)+}++fn leading(v: &str) -> Option<String> {+ if v == "none" {+ return Some("1".into());+ }+ if let Some(l) = theme(&format!("leading-{v}")) {+ return Some(l.into());+ }+ spacing(v)+}++fn radius(v: &str) -> Option<String> {+ match v {+ "DEFAULT" => Some("0.25rem".into()),+ "none" => Some("0".into()),+ "full" => Some("calc(infinity * 1px)".into()),+ _ => theme(&format!("radius-{v}")).map(String::from).or_else(|| free(v).map(|f| f.1)),+ }+}++fn border_width(v: &str) -> Option<String> {+ if let Ok(n) = v.parse::<f32>() {+ return Some(format!("{}px", trim_num(n)));+ }+ match free(v) {+ Some((Some(h), a)) if h == "length" || h == "line-width" => Some(a),+ Some((None, a)) if a.ends_with("px") || a.ends_with("rem") || a.ends_with("em") || a == "thin"+ || a == "medium" || a == "thick" => Some(a),+ _ => None,+ }+}++fn dir_words(d: &str) -> Option<&'static str> {+ Some(match d {+ "t" => "top",+ "tr" => "top right",+ "r" => "right",+ "br" => "bottom right",+ "b" => "bottom",+ "bl" => "bottom left",+ "l" => "left",+ "tl" => "top left",+ _ => return None,+ })+}++fn position_kw(v: &str) -> Option<String> {+ Some(match v {+ "center" => "center",+ "top" => "top",+ "bottom" => "bottom",+ "left" => "left",+ "right" => "right",+ "top-left" | "left-top" => "left top",+ "top-right" | "right-top" => "right top",+ "bottom-left" | "left-bottom" => "left bottom",+ "bottom-right" | "right-bottom" => "right bottom",+ _ => return None,+ }.into())+}++fn align_kw(root: &str, v: &str) -> Option<String> {+ let base = v.trim_end_matches("-safe");+ let kw = match base {+ "start" => "flex-start",+ "end" => "flex-end",+ "center" => "center",+ "between" => "space-between",+ "around" => "space-around",+ "evenly" => "space-evenly",+ "stretch" => "stretch",+ "baseline" => "baseline",+ "baseline-last" => "last baseline",+ "normal" => "normal",+ "auto" => "auto",+ _ => return None,+ };+ // content alignment and flex item alignment use flex-start / flex-end;+ // justify-items, justify-self and place-items / place-self use start / end+ let kw = match (root, base) {+ ("justify-items" | "justify-self" | "place-items" | "place-self", "start") => "start",+ ("justify-items" | "justify-self" | "place-items" | "place-self", "end") => "end",+ _ => kw,+ };+ Some(if v.ends_with("-safe") { format!("safe {kw}") } else { kw.to_string() })+}++/// One variant: (new selector, wrapper at-rule, sort weight).+fn variant(v: &str, sel: &str) -> Option<(Option<String>, Option<String>, u32)> {+ let s = |suffix: &str| Some((Some(format!("{sel}{suffix}")), None, 10));+ let pseudo = |p: &str| -> Option<&'static str> {+ Some(match p {+ "hover" => ":hover",+ "focus" => ":focus",+ "focus-visible" => ":focus-visible",+ "focus-within" => ":focus-within",+ "active" => ":active",+ "visited" => ":visited",+ "target" => ":target",+ "first" => ":first-child",+ "last" => ":last-child",+ "only" => ":only-child",+ "odd" => ":nth-child(odd)",+ "even" => ":nth-child(even)",+ "first-of-type" => ":first-of-type",+ "last-of-type" => ":last-of-type",+ "only-of-type" => ":only-of-type",+ "empty" => ":empty",+ "disabled" => ":disabled",+ "enabled" => ":enabled",+ "checked" => ":checked",+ "indeterminate" => ":indeterminate",+ "default" => ":default",+ "optional" => ":optional",+ "required" => ":required",+ "valid" => ":valid",+ "invalid" => ":invalid",+ "user-valid" => ":user-valid",+ "user-invalid" => ":user-invalid",+ "in-range" => ":in-range",+ "out-of-range" => ":out-of-range",+ "placeholder-shown" => ":placeholder-shown",+ "autofill" => ":autofill",+ "read-only" => ":read-only",+ "read-write" => ":read-write",+ "open" => ":is([open], :popover-open, :open)",+ "inert" => ":is([inert], [inert] *)",+ "details-content" => "::details-content",+ _ => return None,+ })+ };+ if let Some(p) = pseudo(v) {+ return s(p);+ }+ let pe = |p: &str| -> Option<&'static str> {+ Some(match p {+ "before" => "::before",+ "after" => "::after",+ "placeholder" => "::placeholder",+ "file" => "::file-selector-button",+ "marker" => "::marker",+ "selection" => "::selection",+ "first-line" => "::first-line",+ "first-letter" => "::first-letter",+ "backdrop" => "::backdrop",+ _ => return None,+ })+ };+ if let Some(p) = pe(v) {+ return Some((Some(format!("{sel}{p}")), None, 60));+ }+ let bp = |name: &str| theme(&format!("breakpoint-{name}"));+ let media = |q: String, w: u32| Some((None, Some(format!("@media {q}")), w));+ match v {+ "*" => return Some((Some(format!(":is({sel} > *)")), None, 1)),+ "**" => return Some((Some(format!(":is({sel} *)")), None, 1)),+ "dark" => return media("(prefers-color-scheme: dark)".into(), 500),+ "motion-safe" => return media("(prefers-reduced-motion: no-preference)".into(), 300),+ "motion-reduce" => return media("(prefers-reduced-motion: reduce)".into(), 300),+ "contrast-more" => return media("(prefers-contrast: more)".into(), 300),+ "contrast-less" => return media("(prefers-contrast: less)".into(), 300),+ "print" => return media("print".into(), 510),+ "portrait" => return media("(orientation: portrait)".into(), 300),+ "landscape" => return media("(orientation: landscape)".into(), 300),+ "forced-colors" => return media("(forced-colors: active)".into(), 300),+ "inverted-colors" => return media("(inverted-colors: inverted)".into(), 300),+ "pointer-fine" => return media("(pointer: fine)".into(), 300),+ "pointer-coarse" => return media("(pointer: coarse)".into(), 300),+ "pointer-none" => return media("(pointer: none)".into(), 300),+ "any-pointer-fine" => return media("(any-pointer: fine)".into(), 300),+ "any-pointer-coarse" => return media("(any-pointer: coarse)".into(), 300),+ "noscript" => return media("(scripting: none)".into(), 300),+ "rtl" => return Some((Some(format!("{sel}:where(:dir(rtl), [dir=rtl], [dir=rtl] *)")), None, 20)),+ "ltr" => return Some((Some(format!("{sel}:where(:dir(ltr), [dir=ltr], [dir=ltr] *)")), None, 20)),+ "starting" => return Some((None, Some("@starting-style".into()), 600)),+ _ => {}+ }+ // breakpoints: sm md lg xl 2xl (ascending weight so larger wins), max-*, min-[..]+ for (k, name) in ["sm", "md", "lg", "xl", "2xl"].iter().enumerate() {+ if v == *name {+ return media(format!("(width >= {})", bp(name)?), 400 + k as u32 * 2);+ }+ if v.strip_prefix("max-") == Some(name) {+ return media(format!("(width < {})", bp(name)?), 399 - k as u32 * 2);+ }+ }+ if let Some(a) = v.strip_prefix("min-").and_then(arbitrary) {+ return media(format!("(width >= {a})"), 420);+ }+ if let Some(a) = v.strip_prefix("max-").and_then(arbitrary) {+ return media(format!("(width < {a})"), 380);+ }+ // container queries: @sm, @max-md, @min-[..], @[..], @md/name+ if let Some(c) = v.strip_prefix('@') {+ let (c, name) = match c.split_once('/') {+ Some((c, n)) => (c, format!("{n} ")),+ None => (c, String::new()),+ };+ let (op, size_name) = match c.strip_prefix("max-") {+ Some(r) => ("<", r),+ None => (">=", c.strip_prefix("min-").unwrap_or(c)),+ };+ let size = match arbitrary(size_name) {+ Some(a) => a,+ None => theme(&format!("container-{size_name}"))?.to_string(),+ };+ return Some((None, Some(format!("@container {name}(width {op} {size})")), 450));+ }+ // supports-[..], supports-grid+ if let Some(rest) = v.strip_prefix("supports-") {+ let cond = match arbitrary(rest) {+ Some(a) if a.contains(':') || a.starts_with('(') => if a.starts_with('(') { a } else { format!("({a})") },+ Some(a) => format!("({a}: var(--tw))"),+ None => format!("(display: {rest})"),+ };+ return Some((None, Some(format!("@supports {cond}")), 350));+ }+ // arbitrary variant [&>p] / [@media(...)]+ if v.starts_with('[') {+ let a = arbitrary(v)?;+ if a.starts_with('@') {+ return Some((None, Some(a), 700));+ }+ return Some((Some(if a.contains('&') { a.replace('&', sel) } else { format!("{sel}{a}") }), None, 30));+ }+ // data-*, aria-*+ if let Some(d) = v.strip_prefix("data-") {+ let attr = match arbitrary(d) {+ Some(a) => format!("[data-{a}]"),+ None => format!("[data-{d}]"),+ };+ return s(&attr);+ }+ if let Some(d) = v.strip_prefix("aria-") {+ let attr = match arbitrary(d) {+ Some(a) => format!("[aria-{a}]"),+ None => format!("[aria-{d}=\"true\"]"),+ };+ return s(&attr);+ }+ // nth-*+ for (name, pc) in [("nth-last-of-type-", "nth-last-of-type"), ("nth-of-type-", "nth-of-type"),+ ("nth-last-", "nth-last-child"), ("nth-", "nth-child")] {+ if let Some(n) = v.strip_prefix(name) {+ let n = arbitrary(n).unwrap_or_else(|| n.to_string());+ return s(&format!(":{pc}({n})"));+ }+ }+ // group-*, peer-* (optionally named: group-hover/item), has-*, not-*, in-*+ let inner_sel = |x: &str| -> Option<String> {+ if let Some(p) = pseudo(x) {+ return Some(p.to_string());+ }+ if let Some(a) = arbitrary(x) {+ return Some(if a.contains('&') { a.replace('&', "") } else { a });+ }+ if let Some(d) = x.strip_prefix("data-") {+ return Some(arbitrary(d).map(|a| format!("[data-{a}]")).unwrap_or_else(|| format!("[data-{d}]")));+ }+ if let Some(d) = x.strip_prefix("aria-") {+ return Some(arbitrary(d).map(|a| format!("[aria-{a}]")).unwrap_or_else(|| format!("[aria-{d}=\"true\"]")));+ }+ if let Some(h) = x.strip_prefix("has-") {+ let hs = pseudo(h).map(|p| format!("*{p}")).or_else(|| arbitrary(h))?;+ return Some(format!(":has({hs})"));+ }+ None+ };+ for (prefix, comb) in [("group-", " "), ("peer-", " ~ ")] {+ if let Some(rest) = v.strip_prefix(prefix) {+ let (state, name) = match rest.rsplit_once('/') {+ Some((s, n)) if !s.contains('[') || s.ends_with(']') => (s, format!("\\/{n}")),+ _ => (rest, String::new()),+ };+ let which = &prefix[..prefix.len() - 1];+ let st = inner_sel(state)?;+ return Some((Some(format!(":where(.{which}{name}){st}{comb}{sel}")), None, 40));+ }+ }+ if let Some(rest) = v.strip_prefix("has-") {+ let x = pseudo(rest).map(|p| format!("*{p}")).or_else(|| arbitrary(rest))?;+ return s(&format!(":has({x})"));+ }+ if let Some(rest) = v.strip_prefix("not-") {+ let x = inner_sel(rest)?;+ return s(&format!(":not({x})"));+ }+ if let Some(rest) = v.strip_prefix("in-") {+ let x = inner_sel(rest)?;+ return Some((Some(format!(":where(*{x}) {sel}")), None, 40));+ }+ None+}++/// Rank of a property in Tailwind's utility order: earlier properties+/// come first; shorthands before their longhands.+fn prop_rank(p: &str) -> u32 {+ const ORDER: &[&str] = &[+ "container-type", "pointer-events", "visibility", "position", "inset", "top", "right", "bottom", "left",+ "isolation", "z-index", "order", "grid-column", "grid-row", "float", "clear", "box-sizing", "margin",+ "display", "aspect-ratio", "width", "min-width", "max-width", "height", "min-height", "max-height",+ "flex", "flex-shrink", "flex-grow", "flex-basis", "table-layout", "caption-side", "border-collapse",+ "border-spacing", "transform-origin", "translate", "scale", "rotate", "transform", "animation", "cursor",+ "touch-action", "resize", "scroll-snap-type", "scroll-snap-align", "scroll-margin", "scroll-padding",+ "list-style-position", "list-style-type", "appearance", "columns", "grid-auto-columns", "grid-auto-flow",+ "grid-auto-rows", "grid-template-columns", "grid-template-rows", "flex-direction", "flex-wrap",+ "place-content", "place-items", "align-content", "align-items", "justify-content", "justify-items", "gap",+ "column-gap", "row-gap", "place-self", "align-self", "justify-self", "overflow", "overscroll-behavior",+ "scroll-behavior", "text-overflow", "white-space", "word-break", "border-radius", "border-width",+ "border-style", "border-color", "background-color", "background-image", "--tw-gradient-from",+ "--tw-gradient-via", "--tw-gradient-to", "background-size", "background-attachment", "background-clip",+ "background-position", "background-repeat", "background-origin", "fill", "stroke", "object-fit",+ "object-position", "padding", "text-align", "text-indent", "vertical-align", "font-family", "font-size",+ "line-height", "font-weight", "letter-spacing", "text-wrap", "overflow-wrap", "hyphens", "color",+ "text-transform", "font-style", "text-decoration-line", "text-decoration-color", "text-decoration-style",+ "text-decoration-thickness", "text-underline-offset", "opacity", "mix-blend-mode", "box-shadow",+ "outline", "filter", "backdrop-filter", "transition-property", "transition-delay", "transition-duration",+ "transition-timing-function", "will-change", "content",+ ];+ let base = p.split('-').take(2).collect::<Vec<_>>().join("-");+ let idx = ORDER.iter().position(|o| *o == p)+ .or_else(|| ORDER.iter().position(|o| *o == base))+ .or_else(|| ORDER.iter().position(|o| p.starts_with(o)))+ .unwrap_or(ORDER.len());+ idx as u32 * 8 + p.matches('-').count() as u32+}++#[cfg(test)]+mod tests {+ use super::*;++ fn body(class: &str) -> String {+ compile(class).unwrap_or_else(|| panic!("{class}")).css+ }++ #[test]+ fn utilities() {+ assert!(body("p-4").contains("padding: calc(0.25rem * 4)"));+ assert!(body("px-2.5").contains("padding-inline: calc(0.25rem * 2.5)"));+ assert!(body("-mt-8").contains("margin-top: calc(calc(0.25rem * 8) * -1)"));+ assert!(body("w-1/2").contains("width: 50%"));+ assert!(body("w-[calc(100%-2rem)]").contains("width: calc(100%-2rem)"));+ assert!(body("bg-sky-500/50").contains("color-mix(in oklab, oklch(68.5% 0.169 237.323) 50%, transparent)"));+ assert!(body("bg-(--brand)").contains("background-color: var(--brand)"));+ assert!(body("text-lg").contains("font-size: 1.125rem"));+ assert!(body("text-sm/6").contains("line-height: calc(0.25rem * 6)"));+ assert!(body("text-red-500").contains("color: oklch(63.7% 0.237 25.331)"));+ assert!(body("rounded-xl").contains("border-radius: 0.75rem"));+ assert!(body("grid-cols-3").contains("repeat(3, minmax(0, 1fr))"));+ assert!(body("shadow-lg").contains("box-shadow: 0 10px 15px -3px"));+ assert!(body("[mask-type:luminance]").contains("mask-type: luminance"));+ assert!(body("bg-linear-to-r").contains("linear-gradient(to right"));+ assert!(body("animate-spin").contains("@keyframes spin"));+ assert!(body("font-bold").contains("font-weight: 700"));+ assert!(body("border").contains("border-width: 1px"));+ assert!(body("p-4!").contains("!important"));+ assert!(compile("not-a-utility").is_none());+ assert!(compile("p-banana").is_none());+ }++ #[test]+ fn variants() {+ assert!(body("hover:bg-red-500").contains(".hover\\:bg-red-500:hover {"));+ assert!(body("md:flex").contains("@media (width >= 48rem)"));+ assert!(body("dark:md:hover:underline").contains("@media (prefers-color-scheme: dark)"));+ assert!(body("group-hover:text-white").contains(":where(.group):hover .group-hover\\:text-white"));+ assert!(body("group-hover/item:p-1").contains(":where(.group\\/item):hover"));+ assert!(body("peer-checked:block").contains(":where(.peer):checked ~ "));+ assert!(body("has-checked:ring-2").contains(":has(*:checked)"));+ assert!(body("data-[state=open]:p-2").contains("[data-state=open]"));+ assert!(body("aria-expanded:p-2").contains("[aria-expanded=\"true\"]"));+ assert!(body("*:p-2").contains(":is(.\\*\\:p-2 > *)"));+ assert!(body("[&>p]:mt-2").contains(r".\[\&\>p\]\:mt-2>p"));+ assert!(body("@md:grid").contains("@container (width >= 28rem)"));+ assert!(body("before:block").contains("::before { content: ''; display: block"));+ assert!(body("max-md:hidden").contains("(width < 48rem)"));+ assert!(compile("md:p-banana").is_none());+ assert!(compile("wat:p-4").is_none());+ // larger breakpoints sort after smaller ones, variants after base utilities+ assert!(compile("lg:p-1").unwrap().sort > compile("md:p-1").unwrap().sort);+ assert!(compile("p-1").unwrap().sort < compile("hover:p-1").unwrap().sort);+ assert!(compile("p-1").unwrap().sort < compile("px-1").unwrap().sort);+ }+}diff --git a/bindings/rust/blenderui-tailwind/src/theme.rs b/bindings/rust/blenderui-tailwind/src/theme.rsnew file mode 100644index 0000000..43162b2--- /dev/null+++ b/bindings/rust/blenderui-tailwind/src/theme.rs@@ -0,0 +1,412 @@+//! Tailwind CSS v4 default theme (generated from tailwindcss/theme.css; MIT licensed).++/// Theme variable name (without the leading dashes) -> value.+pub const THEME: &[(&str, &str)] = &[+ ("font-sans", "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'"),+ ("font-serif", "ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif"),+ ("font-mono", "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"),+ ("color-red-50", "oklch(97.1% 0.013 17.38)"),+ ("color-red-100", "oklch(93.6% 0.032 17.717)"),+ ("color-red-200", "oklch(88.5% 0.062 18.334)"),+ ("color-red-300", "oklch(80.8% 0.114 19.571)"),+ ("color-red-400", "oklch(70.4% 0.191 22.216)"),+ ("color-red-500", "oklch(63.7% 0.237 25.331)"),+ ("color-red-600", "oklch(57.7% 0.245 27.325)"),+ ("color-red-700", "oklch(50.5% 0.213 27.518)"),+ ("color-red-800", "oklch(44.4% 0.177 26.899)"),+ ("color-red-900", "oklch(39.6% 0.141 25.723)"),+ ("color-red-950", "oklch(25.8% 0.092 26.042)"),+ ("color-orange-50", "oklch(98% 0.016 73.684)"),+ ("color-orange-100", "oklch(95.4% 0.038 75.164)"),+ ("color-orange-200", "oklch(90.1% 0.076 70.697)"),+ ("color-orange-300", "oklch(83.7% 0.128 66.29)"),+ ("color-orange-400", "oklch(75% 0.183 55.934)"),+ ("color-orange-500", "oklch(70.5% 0.213 47.604)"),+ ("color-orange-600", "oklch(64.6% 0.222 41.116)"),+ ("color-orange-700", "oklch(55.3% 0.195 38.402)"),+ ("color-orange-800", "oklch(47% 0.157 37.304)"),+ ("color-orange-900", "oklch(40.8% 0.123 38.172)"),+ ("color-orange-950", "oklch(26.6% 0.079 36.259)"),+ ("color-amber-50", "oklch(98.7% 0.022 95.277)"),+ ("color-amber-100", "oklch(96.2% 0.059 95.617)"),+ ("color-amber-200", "oklch(92.4% 0.12 95.746)"),+ ("color-amber-300", "oklch(87.9% 0.169 91.605)"),+ ("color-amber-400", "oklch(82.8% 0.189 84.429)"),+ ("color-amber-500", "oklch(76.9% 0.188 70.08)"),+ ("color-amber-600", "oklch(66.6% 0.179 58.318)"),+ ("color-amber-700", "oklch(55.5% 0.163 48.998)"),+ ("color-amber-800", "oklch(47.3% 0.137 46.201)"),+ ("color-amber-900", "oklch(41.4% 0.112 45.904)"),+ ("color-amber-950", "oklch(27.9% 0.077 45.635)"),+ ("color-yellow-50", "oklch(98.7% 0.026 102.212)"),+ ("color-yellow-100", "oklch(97.3% 0.071 103.193)"),+ ("color-yellow-200", "oklch(94.5% 0.129 101.54)"),+ ("color-yellow-300", "oklch(90.5% 0.182 98.111)"),+ ("color-yellow-400", "oklch(85.2% 0.199 91.936)"),+ ("color-yellow-500", "oklch(79.5% 0.184 86.047)"),+ ("color-yellow-600", "oklch(68.1% 0.162 75.834)"),+ ("color-yellow-700", "oklch(55.4% 0.135 66.442)"),+ ("color-yellow-800", "oklch(47.6% 0.114 61.907)"),+ ("color-yellow-900", "oklch(42.1% 0.095 57.708)"),+ ("color-yellow-950", "oklch(28.6% 0.066 53.813)"),+ ("color-lime-50", "oklch(98.6% 0.031 120.757)"),+ ("color-lime-100", "oklch(96.7% 0.067 122.328)"),+ ("color-lime-200", "oklch(93.8% 0.127 124.321)"),+ ("color-lime-300", "oklch(89.7% 0.196 126.665)"),+ ("color-lime-400", "oklch(84.1% 0.238 128.85)"),+ ("color-lime-500", "oklch(76.8% 0.233 130.85)"),+ ("color-lime-600", "oklch(64.8% 0.2 131.684)"),+ ("color-lime-700", "oklch(53.2% 0.157 131.589)"),+ ("color-lime-800", "oklch(45.3% 0.124 130.933)"),+ ("color-lime-900", "oklch(40.5% 0.101 131.063)"),+ ("color-lime-950", "oklch(27.4% 0.072 132.109)"),+ ("color-green-50", "oklch(98.2% 0.018 155.826)"),+ ("color-green-100", "oklch(96.2% 0.044 156.743)"),+ ("color-green-200", "oklch(92.5% 0.084 155.995)"),+ ("color-green-300", "oklch(87.1% 0.15 154.449)"),+ ("color-green-400", "oklch(79.2% 0.209 151.711)"),+ ("color-green-500", "oklch(72.3% 0.219 149.579)"),+ ("color-green-600", "oklch(62.7% 0.194 149.214)"),+ ("color-green-700", "oklch(52.7% 0.154 150.069)"),+ ("color-green-800", "oklch(44.8% 0.119 151.328)"),+ ("color-green-900", "oklch(39.3% 0.095 152.535)"),+ ("color-green-950", "oklch(26.6% 0.065 152.934)"),+ ("color-emerald-50", "oklch(97.9% 0.021 166.113)"),+ ("color-emerald-100", "oklch(95% 0.052 163.051)"),+ ("color-emerald-200", "oklch(90.5% 0.093 164.15)"),+ ("color-emerald-300", "oklch(84.5% 0.143 164.978)"),+ ("color-emerald-400", "oklch(76.5% 0.177 163.223)"),+ ("color-emerald-500", "oklch(69.6% 0.17 162.48)"),+ ("color-emerald-600", "oklch(59.6% 0.145 163.225)"),+ ("color-emerald-700", "oklch(50.8% 0.118 165.612)"),+ ("color-emerald-800", "oklch(43.2% 0.095 166.913)"),+ ("color-emerald-900", "oklch(37.8% 0.077 168.94)"),+ ("color-emerald-950", "oklch(26.2% 0.051 172.552)"),+ ("color-teal-50", "oklch(98.4% 0.014 180.72)"),+ ("color-teal-100", "oklch(95.3% 0.051 180.801)"),+ ("color-teal-200", "oklch(91% 0.096 180.426)"),+ ("color-teal-300", "oklch(85.5% 0.138 181.071)"),+ ("color-teal-400", "oklch(77.7% 0.152 181.912)"),+ ("color-teal-500", "oklch(70.4% 0.14 182.503)"),+ ("color-teal-600", "oklch(60% 0.118 184.704)"),+ ("color-teal-700", "oklch(51.1% 0.096 186.391)"),+ ("color-teal-800", "oklch(43.7% 0.078 188.216)"),+ ("color-teal-900", "oklch(38.6% 0.063 188.416)"),+ ("color-teal-950", "oklch(27.7% 0.046 192.524)"),+ ("color-cyan-50", "oklch(98.4% 0.019 200.873)"),+ ("color-cyan-100", "oklch(95.6% 0.045 203.388)"),+ ("color-cyan-200", "oklch(91.7% 0.08 205.041)"),+ ("color-cyan-300", "oklch(86.5% 0.127 207.078)"),+ ("color-cyan-400", "oklch(78.9% 0.154 211.53)"),+ ("color-cyan-500", "oklch(71.5% 0.143 215.221)"),+ ("color-cyan-600", "oklch(60.9% 0.126 221.723)"),+ ("color-cyan-700", "oklch(52% 0.105 223.128)"),+ ("color-cyan-800", "oklch(45% 0.085 224.283)"),+ ("color-cyan-900", "oklch(39.8% 0.07 227.392)"),+ ("color-cyan-950", "oklch(30.2% 0.056 229.695)"),+ ("color-sky-50", "oklch(97.7% 0.013 236.62)"),+ ("color-sky-100", "oklch(95.1% 0.026 236.824)"),+ ("color-sky-200", "oklch(90.1% 0.058 230.902)"),+ ("color-sky-300", "oklch(82.8% 0.111 230.318)"),+ ("color-sky-400", "oklch(74.6% 0.16 232.661)"),+ ("color-sky-500", "oklch(68.5% 0.169 237.323)"),+ ("color-sky-600", "oklch(58.8% 0.158 241.966)"),+ ("color-sky-700", "oklch(50% 0.134 242.749)"),+ ("color-sky-800", "oklch(44.3% 0.11 240.79)"),+ ("color-sky-900", "oklch(39.1% 0.09 240.876)"),+ ("color-sky-950", "oklch(29.3% 0.066 243.157)"),+ ("color-blue-50", "oklch(97% 0.014 254.604)"),+ ("color-blue-100", "oklch(93.2% 0.032 255.585)"),+ ("color-blue-200", "oklch(88.2% 0.059 254.128)"),+ ("color-blue-300", "oklch(80.9% 0.105 251.813)"),+ ("color-blue-400", "oklch(70.7% 0.165 254.624)"),+ ("color-blue-500", "oklch(62.3% 0.214 259.815)"),+ ("color-blue-600", "oklch(54.6% 0.245 262.881)"),+ ("color-blue-700", "oklch(48.8% 0.243 264.376)"),+ ("color-blue-800", "oklch(42.4% 0.199 265.638)"),+ ("color-blue-900", "oklch(37.9% 0.146 265.522)"),+ ("color-blue-950", "oklch(28.2% 0.091 267.935)"),+ ("color-indigo-50", "oklch(96.2% 0.018 272.314)"),+ ("color-indigo-100", "oklch(93% 0.034 272.788)"),+ ("color-indigo-200", "oklch(87% 0.065 274.039)"),+ ("color-indigo-300", "oklch(78.5% 0.115 274.713)"),+ ("color-indigo-400", "oklch(67.3% 0.182 276.935)"),+ ("color-indigo-500", "oklch(58.5% 0.233 277.117)"),+ ("color-indigo-600", "oklch(51.1% 0.262 276.966)"),+ ("color-indigo-700", "oklch(45.7% 0.24 277.023)"),+ ("color-indigo-800", "oklch(39.8% 0.195 277.366)"),+ ("color-indigo-900", "oklch(35.9% 0.144 278.697)"),+ ("color-indigo-950", "oklch(25.7% 0.09 281.288)"),+ ("color-violet-50", "oklch(96.9% 0.016 293.756)"),+ ("color-violet-100", "oklch(94.3% 0.029 294.588)"),+ ("color-violet-200", "oklch(89.4% 0.057 293.283)"),+ ("color-violet-300", "oklch(81.1% 0.111 293.571)"),+ ("color-violet-400", "oklch(70.2% 0.183 293.541)"),+ ("color-violet-500", "oklch(60.6% 0.25 292.717)"),+ ("color-violet-600", "oklch(54.1% 0.281 293.009)"),+ ("color-violet-700", "oklch(49.1% 0.27 292.581)"),+ ("color-violet-800", "oklch(43.2% 0.232 292.759)"),+ ("color-violet-900", "oklch(38% 0.189 293.745)"),+ ("color-violet-950", "oklch(28.3% 0.141 291.089)"),+ ("color-purple-50", "oklch(97.7% 0.014 308.299)"),+ ("color-purple-100", "oklch(94.6% 0.033 307.174)"),+ ("color-purple-200", "oklch(90.2% 0.063 306.703)"),+ ("color-purple-300", "oklch(82.7% 0.119 306.383)"),+ ("color-purple-400", "oklch(71.4% 0.203 305.504)"),+ ("color-purple-500", "oklch(62.7% 0.265 303.9)"),+ ("color-purple-600", "oklch(55.8% 0.288 302.321)"),+ ("color-purple-700", "oklch(49.6% 0.265 301.924)"),+ ("color-purple-800", "oklch(43.8% 0.218 303.724)"),+ ("color-purple-900", "oklch(38.1% 0.176 304.987)"),+ ("color-purple-950", "oklch(29.1% 0.149 302.717)"),+ ("color-fuchsia-50", "oklch(97.7% 0.017 320.058)"),+ ("color-fuchsia-100", "oklch(95.2% 0.037 318.852)"),+ ("color-fuchsia-200", "oklch(90.3% 0.076 319.62)"),+ ("color-fuchsia-300", "oklch(83.3% 0.145 321.434)"),+ ("color-fuchsia-400", "oklch(74% 0.238 322.16)"),+ ("color-fuchsia-500", "oklch(66.7% 0.295 322.15)"),+ ("color-fuchsia-600", "oklch(59.1% 0.293 322.896)"),+ ("color-fuchsia-700", "oklch(51.8% 0.253 323.949)"),+ ("color-fuchsia-800", "oklch(45.2% 0.211 324.591)"),+ ("color-fuchsia-900", "oklch(40.1% 0.17 325.612)"),+ ("color-fuchsia-950", "oklch(29.3% 0.136 325.661)"),+ ("color-pink-50", "oklch(97.1% 0.014 343.198)"),+ ("color-pink-100", "oklch(94.8% 0.028 342.258)"),+ ("color-pink-200", "oklch(89.9% 0.061 343.231)"),+ ("color-pink-300", "oklch(82.3% 0.12 346.018)"),+ ("color-pink-400", "oklch(71.8% 0.202 349.761)"),+ ("color-pink-500", "oklch(65.6% 0.241 354.308)"),+ ("color-pink-600", "oklch(59.2% 0.249 0.584)"),+ ("color-pink-700", "oklch(52.5% 0.223 3.958)"),+ ("color-pink-800", "oklch(45.9% 0.187 3.815)"),+ ("color-pink-900", "oklch(40.8% 0.153 2.432)"),+ ("color-pink-950", "oklch(28.4% 0.109 3.907)"),+ ("color-rose-50", "oklch(96.9% 0.015 12.422)"),+ ("color-rose-100", "oklch(94.1% 0.03 12.58)"),+ ("color-rose-200", "oklch(89.2% 0.058 10.001)"),+ ("color-rose-300", "oklch(81% 0.117 11.638)"),+ ("color-rose-400", "oklch(71.2% 0.194 13.428)"),+ ("color-rose-500", "oklch(64.5% 0.246 16.439)"),+ ("color-rose-600", "oklch(58.6% 0.253 17.585)"),+ ("color-rose-700", "oklch(51.4% 0.222 16.935)"),+ ("color-rose-800", "oklch(45.5% 0.188 13.697)"),+ ("color-rose-900", "oklch(41% 0.159 10.272)"),+ ("color-rose-950", "oklch(27.1% 0.105 12.094)"),+ ("color-slate-50", "oklch(98.4% 0.003 247.858)"),+ ("color-slate-100", "oklch(96.8% 0.007 247.896)"),+ ("color-slate-200", "oklch(92.9% 0.013 255.508)"),+ ("color-slate-300", "oklch(86.9% 0.022 252.894)"),+ ("color-slate-400", "oklch(70.4% 0.04 256.788)"),+ ("color-slate-500", "oklch(55.4% 0.046 257.417)"),+ ("color-slate-600", "oklch(44.6% 0.043 257.281)"),+ ("color-slate-700", "oklch(37.2% 0.044 257.287)"),+ ("color-slate-800", "oklch(27.9% 0.041 260.031)"),+ ("color-slate-900", "oklch(20.8% 0.042 265.755)"),+ ("color-slate-950", "oklch(12.9% 0.042 264.695)"),+ ("color-gray-50", "oklch(98.5% 0.002 247.839)"),+ ("color-gray-100", "oklch(96.7% 0.003 264.542)"),+ ("color-gray-200", "oklch(92.8% 0.006 264.531)"),+ ("color-gray-300", "oklch(87.2% 0.01 258.338)"),+ ("color-gray-400", "oklch(70.7% 0.022 261.325)"),+ ("color-gray-500", "oklch(55.1% 0.027 264.364)"),+ ("color-gray-600", "oklch(44.6% 0.03 256.802)"),+ ("color-gray-700", "oklch(37.3% 0.034 259.733)"),+ ("color-gray-800", "oklch(27.8% 0.033 256.848)"),+ ("color-gray-900", "oklch(21% 0.034 264.665)"),+ ("color-gray-950", "oklch(13% 0.028 261.692)"),+ ("color-zinc-50", "oklch(98.5% 0 none)"),+ ("color-zinc-100", "oklch(96.7% 0.001 286.375)"),+ ("color-zinc-200", "oklch(92% 0.004 286.32)"),+ ("color-zinc-300", "oklch(87.1% 0.006 286.286)"),+ ("color-zinc-400", "oklch(70.5% 0.015 286.067)"),+ ("color-zinc-500", "oklch(55.2% 0.016 285.938)"),+ ("color-zinc-600", "oklch(44.2% 0.017 285.786)"),+ ("color-zinc-700", "oklch(37% 0.013 285.805)"),+ ("color-zinc-800", "oklch(27.4% 0.006 286.033)"),+ ("color-zinc-900", "oklch(21% 0.006 285.885)"),+ ("color-zinc-950", "oklch(14.1% 0.005 285.823)"),+ ("color-neutral-50", "oklch(98.5% 0 none)"),+ ("color-neutral-100", "oklch(97% 0 none)"),+ ("color-neutral-200", "oklch(92.2% 0 none)"),+ ("color-neutral-300", "oklch(87% 0 none)"),+ ("color-neutral-400", "oklch(70.8% 0 none)"),+ ("color-neutral-500", "oklch(55.6% 0 none)"),+ ("color-neutral-600", "oklch(43.9% 0 none)"),+ ("color-neutral-700", "oklch(37.1% 0 none)"),+ ("color-neutral-800", "oklch(26.9% 0 none)"),+ ("color-neutral-900", "oklch(20.5% 0 none)"),+ ("color-neutral-950", "oklch(14.5% 0 none)"),+ ("color-stone-50", "oklch(98.5% 0.001 106.423)"),+ ("color-stone-100", "oklch(97% 0.001 106.424)"),+ ("color-stone-200", "oklch(92.3% 0.003 48.717)"),+ ("color-stone-300", "oklch(86.9% 0.005 56.366)"),+ ("color-stone-400", "oklch(70.9% 0.01 56.259)"),+ ("color-stone-500", "oklch(55.3% 0.013 58.071)"),+ ("color-stone-600", "oklch(44.4% 0.011 73.639)"),+ ("color-stone-700", "oklch(37.4% 0.01 67.558)"),+ ("color-stone-800", "oklch(26.8% 0.007 34.298)"),+ ("color-stone-900", "oklch(21.6% 0.006 56.043)"),+ ("color-stone-950", "oklch(14.7% 0.004 49.25)"),+ ("color-mauve-50", "oklch(98.5% 0 none)"),+ ("color-mauve-100", "oklch(96% 0.003 325.6)"),+ ("color-mauve-200", "oklch(92.2% 0.005 325.62)"),+ ("color-mauve-300", "oklch(86.5% 0.012 325.68)"),+ ("color-mauve-400", "oklch(71.1% 0.019 323.02)"),+ ("color-mauve-500", "oklch(54.2% 0.034 322.5)"),+ ("color-mauve-600", "oklch(43.5% 0.029 321.78)"),+ ("color-mauve-700", "oklch(36.4% 0.029 323.89)"),+ ("color-mauve-800", "oklch(26.3% 0.024 320.12)"),+ ("color-mauve-900", "oklch(21.2% 0.019 322.12)"),+ ("color-mauve-950", "oklch(14.5% 0.008 326)"),+ ("color-olive-50", "oklch(98.8% 0.003 106.5)"),+ ("color-olive-100", "oklch(96.6% 0.005 106.5)"),+ ("color-olive-200", "oklch(93% 0.007 106.5)"),+ ("color-olive-300", "oklch(88% 0.011 106.6)"),+ ("color-olive-400", "oklch(73.7% 0.021 106.9)"),+ ("color-olive-500", "oklch(58% 0.031 107.3)"),+ ("color-olive-600", "oklch(46.6% 0.025 107.3)"),+ ("color-olive-700", "oklch(39.4% 0.023 107.4)"),+ ("color-olive-800", "oklch(28.6% 0.016 107.4)"),+ ("color-olive-900", "oklch(22.8% 0.013 107.4)"),+ ("color-olive-950", "oklch(15.3% 0.006 107.1)"),+ ("color-mist-50", "oklch(98.7% 0.002 197.1)"),+ ("color-mist-100", "oklch(96.3% 0.002 197.1)"),+ ("color-mist-200", "oklch(92.5% 0.005 214.3)"),+ ("color-mist-300", "oklch(87.2% 0.007 219.6)"),+ ("color-mist-400", "oklch(72.3% 0.014 214.4)"),+ ("color-mist-500", "oklch(56% 0.021 213.5)"),+ ("color-mist-600", "oklch(45% 0.017 213.2)"),+ ("color-mist-700", "oklch(37.8% 0.015 216)"),+ ("color-mist-800", "oklch(27.5% 0.011 216.9)"),+ ("color-mist-900", "oklch(21.8% 0.008 223.9)"),+ ("color-mist-950", "oklch(14.8% 0.004 228.8)"),+ ("color-taupe-50", "oklch(98.6% 0.002 67.8)"),+ ("color-taupe-100", "oklch(96% 0.002 17.2)"),+ ("color-taupe-200", "oklch(92.2% 0.005 34.3)"),+ ("color-taupe-300", "oklch(86.8% 0.007 39.5)"),+ ("color-taupe-400", "oklch(71.4% 0.014 41.2)"),+ ("color-taupe-500", "oklch(54.7% 0.021 43.1)"),+ ("color-taupe-600", "oklch(43.8% 0.017 39.3)"),+ ("color-taupe-700", "oklch(36.7% 0.016 35.7)"),+ ("color-taupe-800", "oklch(26.8% 0.011 36.5)"),+ ("color-taupe-900", "oklch(21.4% 0.009 43.1)"),+ ("color-taupe-950", "oklch(14.7% 0.004 49.3)"),+ ("color-black", "#000"),+ ("color-white", "#fff"),+ ("spacing", "0.25rem"),+ ("breakpoint-sm", "40rem"),+ ("breakpoint-md", "48rem"),+ ("breakpoint-lg", "64rem"),+ ("breakpoint-xl", "80rem"),+ ("breakpoint-2xl", "96rem"),+ ("container-3xs", "16rem"),+ ("container-2xs", "18rem"),+ ("container-xs", "20rem"),+ ("container-sm", "24rem"),+ ("container-md", "28rem"),+ ("container-lg", "32rem"),+ ("container-xl", "36rem"),+ ("container-2xl", "42rem"),+ ("container-3xl", "48rem"),+ ("container-4xl", "56rem"),+ ("container-5xl", "64rem"),+ ("container-6xl", "72rem"),+ ("container-7xl", "80rem"),+ ("text-xs", "0.75rem"),+ ("text-xs--line-height", "calc(1 / 0.75)"),+ ("text-sm", "0.875rem"),+ ("text-sm--line-height", "calc(1.25 / 0.875)"),+ ("text-base", "1rem"),+ ("text-base--line-height", "calc(1.5 / 1)"),+ ("text-lg", "1.125rem"),+ ("text-lg--line-height", "calc(1.75 / 1.125)"),+ ("text-xl", "1.25rem"),+ ("text-xl--line-height", "calc(1.75 / 1.25)"),+ ("text-2xl", "1.5rem"),+ ("text-2xl--line-height", "calc(2 / 1.5)"),+ ("text-3xl", "1.875rem"),+ ("text-3xl--line-height", "calc(2.25 / 1.875)"),+ ("text-4xl", "2.25rem"),+ ("text-4xl--line-height", "calc(2.5 / 2.25)"),+ ("text-5xl", "3rem"),+ ("text-5xl--line-height", "1"),+ ("text-6xl", "3.75rem"),+ ("text-6xl--line-height", "1"),+ ("text-7xl", "4.5rem"),+ ("text-7xl--line-height", "1"),+ ("text-8xl", "6rem"),+ ("text-8xl--line-height", "1"),+ ("text-9xl", "8rem"),+ ("text-9xl--line-height", "1"),+ ("font-weight-thin", "100"),+ ("font-weight-extralight", "200"),+ ("font-weight-light", "300"),+ ("font-weight-normal", "400"),+ ("font-weight-medium", "500"),+ ("font-weight-semibold", "600"),+ ("font-weight-bold", "700"),+ ("font-weight-extrabold", "800"),+ ("font-weight-black", "900"),+ ("tracking-tighter", "-0.05em"),+ ("tracking-tight", "-0.025em"),+ ("tracking-normal", "0em"),+ ("tracking-wide", "0.025em"),+ ("tracking-wider", "0.05em"),+ ("tracking-widest", "0.1em"),+ ("leading-tight", "1.25"),+ ("leading-snug", "1.375"),+ ("leading-normal", "1.5"),+ ("leading-relaxed", "1.625"),+ ("leading-loose", "2"),+ ("radius-xs", "0.125rem"),+ ("radius-sm", "0.25rem"),+ ("radius-md", "0.375rem"),+ ("radius-lg", "0.5rem"),+ ("radius-xl", "0.75rem"),+ ("radius-2xl", "1rem"),+ ("radius-3xl", "1.5rem"),+ ("radius-4xl", "2rem"),+ ("shadow-2xs", "0 1px rgb(0 0 0 / 0.05)"),+ ("shadow-xs", "0 1px 2px 0 rgb(0 0 0 / 0.05)"),+ ("shadow-sm", "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)"),+ ("shadow-md", "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"),+ ("shadow-lg", "0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"),+ ("shadow-xl", "0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"),+ ("shadow-2xl", "0 25px 50px -12px rgb(0 0 0 / 0.25)"),+ ("inset-shadow-2xs", "inset 0 1px rgb(0 0 0 / 0.05)"),+ ("inset-shadow-xs", "inset 0 1px 1px rgb(0 0 0 / 0.05)"),+ ("inset-shadow-sm", "inset 0 2px 4px rgb(0 0 0 / 0.05)"),+ ("drop-shadow-xs", "0 1px 1px rgb(0 0 0 / 0.05)"),+ ("drop-shadow-sm", "0 1px 2px rgb(0 0 0 / 0.15)"),+ ("drop-shadow-md", "0 3px 3px rgb(0 0 0 / 0.12)"),+ ("drop-shadow-lg", "0 4px 4px rgb(0 0 0 / 0.15)"),+ ("drop-shadow-xl", "0 9px 7px rgb(0 0 0 / 0.1)"),+ ("drop-shadow-2xl", "0 25px 25px rgb(0 0 0 / 0.15)"),+ ("text-shadow-2xs", "0px 1px 0px rgb(0 0 0 / 0.15)"),+ ("text-shadow-xs", "0px 1px 1px rgb(0 0 0 / 0.2)"),+ ("text-shadow-sm", "0px 1px 0px rgb(0 0 0 / 0.075), 0px 1px 1px rgb(0 0 0 / 0.075), 0px 2px 2px rgb(0 0 0 / 0.075)"),+ ("text-shadow-md", "0px 1px 1px rgb(0 0 0 / 0.1), 0px 1px 2px rgb(0 0 0 / 0.1), 0px 2px 4px rgb(0 0 0 / 0.1)"),+ ("text-shadow-lg", "0px 1px 2px rgb(0 0 0 / 0.1), 0px 3px 2px rgb(0 0 0 / 0.1), 0px 4px 8px rgb(0 0 0 / 0.1)"),+ ("ease-in", "cubic-bezier(0.4, 0, 1, 1)"),+ ("ease-out", "cubic-bezier(0, 0, 0.2, 1)"),+ ("ease-in-out", "cubic-bezier(0.4, 0, 0.2, 1)"),+ ("animate-spin", "spin 1s linear infinite"),+ ("animate-ping", "ping 1s cubic-bezier(0, 0, 0.2, 1) infinite"),+ ("animate-pulse", "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"),+ ("animate-bounce", "bounce 1s infinite"),+ ("blur-xs", "4px"),+ ("blur-sm", "8px"),+ ("blur-md", "12px"),+ ("blur-lg", "16px"),+ ("blur-xl", "24px"),+ ("blur-2xl", "40px"),+ ("blur-3xl", "64px"),+ ("perspective-dramatic", "100px"),+ ("perspective-near", "300px"),+ ("perspective-normal", "500px"),+ ("perspective-midrange", "800px"),+ ("perspective-distant", "1200px"),+ ("aspect-video", "16 / 9"),+ ("default-transition-duration", "150ms"),+ ("default-transition-timing-function", "cubic-bezier(0.4, 0, 0.2, 1)"),+];diff --git a/bindings/rust/blenderui/Cargo.toml b/bindings/rust/blenderui/Cargo.tomlindex bb8abc9..c36bfb6 100644--- a/bindings/rust/blenderui/Cargo.toml+++ b/bindings/rust/blenderui/Cargo.toml@@ -13,7 +13,13 @@ readme = "README.md"[dependencies]blenderui-sys = { path = "../blenderui-sys", version = "0.1.0" }blenderui-macros = { path = "../blenderui-macros", version = "0.1.0" }-taffy = { version = "0.6", default-features = false, features = ["std", "flexbox", "grid", "block_layout", "taffy_tree", "content_size"] }+blenderui-tailwind = { path = "../blenderui-tailwind", version = "0.1.0" }+taffy = { version = "0.15", default-features = false, features = ["std", "taffy_tree", "flexbox", "flexbox_balance", "grid", "block_layout", "float_layout", "calc", "content_size"] }paste = "1"smallvec = { version = "1", features = ["union", "const_generics"] }png = "0.17"++[features]+# Draw text with the portable stb_truetype engine on Windows too (it's always+# used on Linux, macOS and wasm).+portable-text = ["blenderui-sys/portable-text"]diff --git a/bindings/rust/blenderui/README.md b/bindings/rust/blenderui/README.mdindex 30ca812..e16c70e 100644--- a/bindings/rust/blenderui/README.md+++ b/bindings/rust/blenderui/README.md@@ -30,5 +30,15 @@ fn main() {}```+**GPU rendering:** windows draw on the CPU by default. Use+`Application::new().gpu(true)` (or `WindowOptions { gpu: Some(true), .. }`, or+run with `BUI_GPU=1`) to draw them with Direct3D 11. This produces the same+pixels at a fraction of the CPU cost: 11.6 ms vs 22.0 ms per frame for+3000 animated cells, where gpui-fast needs 31.9 ms.++**Text** works on every platform: GDI on Windows and a bundled stb_truetype+engine elsewhere (the `portable-text` feature selects it on Windows).+Register fonts with `blenderui::add_font` where there are none (wasm).+Guide, CSS coverage and limitations:[docs/rust.md](https://github.com/ppmpreetham/BUI/blob/main/docs/rust.md).diff --git a/bindings/rust/blenderui/src/calc.rs b/bindings/rust/blenderui/src/calc.rsnew file mode 100644index 0000000..054a600--- /dev/null+++ b/bindings/rust/blenderui/src/calc.rs@@ -0,0 +1,547 @@+//! CSS math: `calc()`, `min()`, `max()`, `clamp()`, `round()`, `mod()`,+//! `rem()`, `abs()`, `sign()`, trigonometry, `pow()`, `sqrt()`, `hypot()`,+//! `log()`, `exp()` and the constants `e`, `pi`, `infinity`, `NaN`, over+//! every length unit and angles.+//!+//! Expressions are interned: each distinct one is parsed once and lives for+//! the rest of the process, so lengths can hold a `&'static Calc` (they stay+//! `Copy`) and taffy can carry a resolved copy as its opaque calc pointer+//! (`tree.rs` evaluates it against the percentage basis during layout).++use crate::css::Tok;+use crate::geometry::{Units, ROOT_FONT_SIZE};+use std::hash::{Hash, Hasher};+use std::sync::{Mutex, OnceLock};++/// A math expression. Leaves keep their unit until [`Calc::resolve`]+/// bakes the font size and viewport in, leaving only px and %.+#[derive(Debug, PartialEq)]+#[repr(align(8))]+pub enum Calc {+ Num(f32),+ Px(f32),+ Pct(f32),+ Em(f32),+ Rem(f32),+ Vw(f32),+ Vh(f32),+ Vmin(f32),+ Vmax(f32),+ Add(Box<Calc>, Box<Calc>),+ Sub(Box<Calc>, Box<Calc>),+ Mul(Box<Calc>, Box<Calc>),+ Div(Box<Calc>, Box<Calc>),+ Min(Vec<Calc>),+ Max(Vec<Calc>),+ Clamp(Box<Calc>, Box<Calc>, Box<Calc>),+ /// round(strategy, value, step)+ Round(RoundMode, Box<Calc>, Box<Calc>),+ Mod(Box<Calc>, Box<Calc>),+ Rem2(Box<Calc>, Box<Calc>),+ Fn1(Fn1, Box<Calc>),+ Pow(Box<Calc>, Box<Calc>),+ Atan2(Box<Calc>, Box<Calc>),+ Log(Box<Calc>, Option<Box<Calc>>),+ Hypot(Vec<Calc>),+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum RoundMode {+ Nearest,+ Up,+ Down,+ ToZero,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Fn1 {+ Abs,+ Sign,+ Sqrt,+ Exp,+ Sin,+ Cos,+ Tan,+ Asin,+ Acos,+ Atan,+}++/// Names of functions that start a math expression.+pub fn is_math_fn(name: &str) -> bool {+ matches!(name, "calc" | "min" | "max" | "clamp" | "round" | "mod" | "rem" | "abs" | "sign"+ | "sqrt" | "exp" | "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "atan2" | "pow"+ | "hypot" | "log" | "-webkit-calc" | "-moz-calc")+}++impl Calc {+ /// Parse a math function (`calc(...)`, `min(...)` ...) into an interned expression.+ pub fn parse_fn(name: &str, args: &[Vec<Tok>]) -> Option<&'static Calc> {+ let c = Parser::function(name, args)?;+ Some(intern(c))+ }++ /// Whether the value depends on the percentage basis.+ pub fn has_pct(&self) -> bool {+ use Calc::*;+ match self {+ Pct(_) => true,+ Num(_) | Px(_) | Em(_) | Rem(_) | Vw(_) | Vh(_) | Vmin(_) | Vmax(_) => false,+ Add(a, b) | Sub(a, b) | Mul(a, b) | Div(a, b) | Mod(a, b) | Rem2(a, b) | Pow(a, b)+ | Atan2(a, b) | Round(_, a, b) => a.has_pct() || b.has_pct(),+ Min(v) | Max(v) | Hypot(v) => v.iter().any(Calc::has_pct),+ Clamp(a, b, c) => a.has_pct() || b.has_pct() || c.has_pct(),+ Fn1(_, a) => a.has_pct(),+ Log(a, b) => a.has_pct() || b.as_ref().is_some_and(|b| b.has_pct()),+ }+ }++ /// The value in px, percentages taken of `basis`.+ pub fn eval_units(&self, u: &Units, basis: f32) -> f32 {+ use Calc::*;+ let e = |c: &Calc| c.eval_units(u, basis);+ match self {+ Num(v) | Px(v) => *v,+ Pct(p) => p * basis / 100.0,+ Em(v) => v * u.font_size,+ Rem(v) => v * ROOT_FONT_SIZE,+ Vw(v) => v * u.viewport.0 / 100.0,+ Vh(v) => v * u.viewport.1 / 100.0,+ Vmin(v) => v * u.viewport.0.min(u.viewport.1) / 100.0,+ Vmax(v) => v * u.viewport.0.max(u.viewport.1) / 100.0,+ Add(a, b) => e(a) + e(b),+ Sub(a, b) => e(a) - e(b),+ Mul(a, b) => e(a) * e(b),+ Div(a, b) => e(a) / e(b),+ Min(v) => v.iter().map(e).fold(f32::INFINITY, f32::min),+ Max(v) => v.iter().map(e).fold(f32::NEG_INFINITY, f32::max),+ // clamp(MIN, VAL, MAX) = max(MIN, min(VAL, MAX))+ Clamp(lo, v, hi) => e(lo).max(e(v).min(e(hi))),+ Round(m, v, s) => round(*m, e(v), e(s)),+ Mod(a, b) => {+ let (a, b) = (e(a), e(b));+ a - b * (a / b).floor()+ }+ Rem2(a, b) => e(a) % e(b),+ Fn1(f, a) => {+ let a = e(a);+ match f {+ self::Fn1::Abs => a.abs(),+ self::Fn1::Sign => if a == 0.0 { 0.0 } else { a.signum() },+ self::Fn1::Sqrt => a.sqrt(),+ self::Fn1::Exp => a.exp(),+ self::Fn1::Sin => a.sin(),+ self::Fn1::Cos => a.cos(),+ self::Fn1::Tan => a.tan(),+ self::Fn1::Asin => a.asin(),+ self::Fn1::Acos => a.acos(),+ self::Fn1::Atan => a.atan(),+ }+ }+ Pow(a, b) => e(a).powf(e(b)),+ Atan2(a, b) => e(a).atan2(e(b)),+ Log(a, b) => match b {+ Some(b) => e(a).ln() / e(b).ln(),+ None => e(a).ln(),+ },+ Hypot(v) => v.iter().map(|c| e(c).powi(2)).sum::<f32>().sqrt(),+ }+ }++ /// Pixels when the value doesn't need a percentage basis.+ pub fn to_px(&self, u: &Units) -> Option<f32> {+ (!self.has_pct()).then(|| self.eval_units(u, 0.0))+ }++ /// A copy with font-relative and viewport units baked in (px and %+ /// remain), interned: what taffy evaluates during layout.+ pub fn resolve(&self, u: &Units) -> &'static Resolved {+ Resolved::new(intern(self.bake(u)))+ }++ fn bake(&self, u: &Units) -> Calc {+ self.bake_with(&|leaf| match leaf {+ Calc::Num(x) => Calc::Num(*x),+ Calc::Pct(x) => Calc::Pct(*x),+ other => Calc::Px(other.eval_units(u, 0.0)),+ })+ }++ /// A copy with every leaf mapped by `f`.+ fn bake_with(&self, f: &dyn Fn(&Calc) -> Calc) -> Calc {+ use Calc::*;+ let b = |c: &Calc| Box::new(c.bake_with(f));+ let v = |l: &[Calc]| l.iter().map(|c| c.bake_with(f)).collect();+ match self {+ Num(_) | Pct(_) | Px(_) | Em(_) | Rem(_) | Vw(_) | Vh(_) | Vmin(_) | Vmax(_) => f(self),+ Add(a, c) => Add(b(a), b(c)),+ Sub(a, c) => Sub(b(a), b(c)),+ Mul(a, c) => Mul(b(a), b(c)),+ Div(a, c) => Div(b(a), b(c)),+ Min(l) => Min(v(l)),+ Max(l) => Max(v(l)),+ Clamp(a, c, d) => Clamp(b(a), b(c), b(d)),+ Round(m, a, c) => Round(*m, b(a), b(c)),+ Mod(a, c) => Mod(b(a), b(c)),+ Rem2(a, c) => Rem2(b(a), b(c)),+ Fn1(f, a) => Fn1(*f, b(a)),+ Pow(a, c) => Pow(b(a), b(c)),+ Atan2(a, c) => Atan2(b(a), b(c)),+ Log(a, c) => Log(b(a), c.as_ref().map(|c| b(c))),+ Hypot(l) => Hypot(v(l)),+ }+ }++ fn hash_into<H: Hasher>(&self, h: &mut H) {+ use Calc::*;+ std::mem::discriminant(self).hash(h);+ match self {+ Num(x) | Px(x) | Pct(x) | Em(x) | Rem(x) | Vw(x) | Vh(x) | Vmin(x) | Vmax(x) => {+ x.to_bits().hash(h)+ }+ Add(a, b) | Sub(a, b) | Mul(a, b) | Div(a, b) | Mod(a, b) | Rem2(a, b) | Pow(a, b)+ | Atan2(a, b) => {+ a.hash_into(h);+ b.hash_into(h);+ }+ Round(m, a, b) => {+ m.hash(h);+ a.hash_into(h);+ b.hash_into(h);+ }+ Min(v) | Max(v) | Hypot(v) => {+ v.len().hash(h);+ v.iter().for_each(|c| c.hash_into(h));+ }+ Clamp(a, b, c) => {+ a.hash_into(h);+ b.hash_into(h);+ c.hash_into(h);+ }+ Fn1(f, a) => {+ f.hash(h);+ a.hash_into(h);+ }+ Log(a, b) => {+ a.hash_into(h);+ if let Some(b) = b {+ b.hash_into(h);+ }+ }+ }+ }+}++fn clone_calc(c: &Calc) -> Calc {+ c.bake_with(&|leaf| match *leaf {+ Calc::Num(x) => Calc::Num(x),+ Calc::Px(x) => Calc::Px(x),+ Calc::Pct(x) => Calc::Pct(x),+ Calc::Em(x) => Calc::Em(x),+ Calc::Rem(x) => Calc::Rem(x),+ Calc::Vw(x) => Calc::Vw(x),+ Calc::Vh(x) => Calc::Vh(x),+ Calc::Vmin(x) => Calc::Vmin(x),+ Calc::Vmax(x) => Calc::Vmax(x),+ _ => Calc::Num(0.0), // bake_with only passes leaves+ })+}++fn round(m: RoundMode, v: f32, step: f32) -> f32 {+ if step == 0.0 || !step.is_finite() {+ return if step == 0.0 { f32::NAN } else { v };+ }+ let q = v / step;+ let r = match m {+ RoundMode::Nearest => (q + 0.5).floor(),+ RoundMode::Up => q.ceil(),+ RoundMode::Down => q.floor(),+ RoundMode::ToZero => q.trunc(),+ };+ r * step+}++/// A baked expression in taffy's calc slot: px and % only.+#[repr(transparent)]+pub struct Resolved(Calc);++impl Resolved {+ fn new(c: &'static Calc) -> &'static Resolved {+ // SAFETY: Resolved is a transparent wrapper around Calc.+ unsafe { &*(c as *const Calc as *const Resolved) }+ }++ /// The opaque pointer taffy stores (8-byte aligned, as it requires).+ pub fn as_ptr(&'static self) -> *const () {+ self as *const Resolved as *const ()+ }++ /// # Safety+ /// `ptr` must come from [`Resolved::as_ptr`].+ pub unsafe fn from_ptr(ptr: *const ()) -> &'static Resolved {+ unsafe { &*(ptr as *const Resolved) }+ }++ pub fn eval(&self, basis: f32) -> f32 {+ let u = Units { font_size: 16.0, viewport: (0.0, 0.0) };+ let v = self.0.eval_units(&u, basis);+ if v.is_nan() { 0.0 } else { v }+ }+}++/// Every distinct expression, kept for the life of the process (they are+/// few: the stylesheets' and styles' calc() values).+fn intern(c: Calc) -> &'static Calc {+ static MAP: OnceLock<Mutex<crate::style::FnvMap<u64, Vec<&'static Calc>>>> = OnceLock::new();+ let mut h = crate::style::Fnv::default();+ c.hash_into(&mut h);+ let key = h.finish();+ let mut map = MAP.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());+ let bucket = map.entry(key).or_default();+ if let Some(found) = bucket.iter().find(|x| ***x == c) {+ return found;+ }+ let leaked: &'static Calc = Box::leak(Box::new(c));+ bucket.push(leaked);+ leaked+}++/// Recursive-descent parser over a function's argument tokens.+struct Parser<'a> {+ toks: &'a [Tok],+ i: usize,+}++impl<'a> Parser<'a> {+ fn function(name: &str, args: &[Vec<Tok>]) -> Option<Calc> {+ let sum = |a: &Vec<Tok>| Parser::sum_all(a);+ let two = |f: fn(Box<Calc>, Box<Calc>) -> Calc| -> Option<Calc> {+ Some(f(Box::new(sum(args.first()?)?), Box::new(sum(args.get(1)?)?)))+ };+ Some(match name {+ "calc" | "-webkit-calc" | "-moz-calc" => sum(args.first()?)?,+ "min" => Calc::Min(args.iter().map(sum).collect::<Option<_>>()?),+ "max" => Calc::Max(args.iter().map(sum).collect::<Option<_>>()?),+ "hypot" => Calc::Hypot(args.iter().map(sum).collect::<Option<_>>()?),+ "clamp" if args.len() == 3 => Calc::Clamp(Box::new(sum(&args[0])?), Box::new(sum(&args[1])?),+ Box::new(sum(&args[2])?)),+ "round" => {+ let (mode, rest) = match args.first()?.as_slice() {+ [Tok::Ident(m)] => (match m.as_ref() {+ "nearest" => RoundMode::Nearest,+ "up" => RoundMode::Up,+ "down" => RoundMode::Down,+ "to-zero" => RoundMode::ToZero,+ _ => return None,+ }, &args[1..]),+ _ => (RoundMode::Nearest, args),+ };+ let v = sum(rest.first()?)?;+ let step = match rest.get(1) {+ Some(s) => sum(s)?,+ None => Calc::Num(1.0),+ };+ Calc::Round(mode, Box::new(v), Box::new(step))+ }+ "mod" => two(Calc::Mod)?,+ "rem" => two(Calc::Rem2)?,+ "pow" => two(Calc::Pow)?,+ "atan2" => two(Calc::Atan2)?,+ "log" => Calc::Log(Box::new(sum(args.first()?)?),+ match args.get(1) { Some(b) => Some(Box::new(sum(b)?)), None => None }),+ f => {+ let op = match f {+ "abs" => Fn1::Abs,+ "sign" => Fn1::Sign,+ "sqrt" => Fn1::Sqrt,+ "exp" => Fn1::Exp,+ "sin" => Fn1::Sin,+ "cos" => Fn1::Cos,+ "tan" => Fn1::Tan,+ "asin" => Fn1::Asin,+ "acos" => Fn1::Acos,+ "atan" => Fn1::Atan,+ _ => return None,+ };+ Calc::Fn1(op, Box::new(sum(args.first()?)?))+ }+ })+ }++ fn sum_all(toks: &'a [Tok]) -> Option<Calc> {+ let mut p = Parser { toks, i: 0 };+ let v = p.sum()?;+ (p.i == toks.len()).then_some(v)+ }++ fn peek(&self) -> Option<&'a Tok> {+ self.toks.get(self.i)+ }++ fn sum(&mut self) -> Option<Calc> {+ let mut acc = self.product()?;+ loop {+ match self.peek() {+ Some(Tok::Delim('+')) => {+ self.i += 1;+ acc = Calc::Add(Box::new(acc), Box::new(self.product()?));+ }+ Some(t) if is_minus(t) => {+ self.i += 1;+ acc = Calc::Sub(Box::new(acc), Box::new(self.product()?));+ }+ // `100%-2rem` (no spaces, as Tailwind writes it): the tokenizer+ // reads a signed number; treat it as a sum+ Some(Tok::Num(v) | Tok::Dim(v, _) | Tok::Pct(v)) if *v < 0.0 => {+ acc = Calc::Add(Box::new(acc), Box::new(self.product()?));+ }+ _ => return Some(acc),+ }+ }+ }++ fn product(&mut self) -> Option<Calc> {+ let mut acc = self.unary()?;+ loop {+ match self.peek() {+ Some(Tok::Delim('*')) => {+ self.i += 1;+ acc = Calc::Mul(Box::new(acc), Box::new(self.unary()?));+ }+ Some(Tok::Slash) => {+ self.i += 1;+ acc = Calc::Div(Box::new(acc), Box::new(self.unary()?));+ }+ _ => return Some(acc),+ }+ }+ }++ fn unary(&mut self) -> Option<Calc> {+ let t = self.peek()?;+ self.i += 1;+ Some(match t {+ Tok::Delim('(') => {+ let v = self.sum()?;+ match self.peek() {+ Some(Tok::Delim(')')) => self.i += 1,+ _ => return None,+ }+ v+ }+ t if is_minus(t) => Calc::Mul(Box::new(Calc::Num(-1.0)), Box::new(self.unary()?)),+ Tok::Delim('+') => self.unary()?,+ Tok::Num(v) => Calc::Num(*v),+ Tok::Pct(v) => Calc::Pct(*v),+ Tok::Dim(v, unit) => leaf(*v, unit)?,+ Tok::Ident(s) => match s.as_ref() {+ "e" => Calc::Num(std::f32::consts::E),+ "pi" => Calc::Num(std::f32::consts::PI),+ "infinity" => Calc::Num(f32::INFINITY),+ "-infinity" => Calc::Num(f32::NEG_INFINITY),+ "nan" => Calc::Num(f32::NAN),+ "-e" => Calc::Num(-std::f32::consts::E),+ "-pi" => Calc::Num(-std::f32::consts::PI),+ _ => return None,+ },+ Tok::Func(fx) => Parser::function(&fx.name, &fx.args)?,+ Tok::Calc(c) => clone_calc(c),+ _ => return None,+ })+ }+}++/// `-` between spaces tokenizes as an identifier (it can start one).+fn is_minus(t: &Tok) -> bool {+ matches!(t, Tok::Delim('-')) || matches!(t, Tok::Ident(s) if s == "-")+}++/// One dimension as an expression leaf (angles become radians, times seconds).+pub fn leaf(v: f32, unit: &str) -> Option<Calc> {+ use std::f32::consts::PI;+ Some(match unit {+ "px" => Calc::Px(v),+ "rem" => Calc::Rem(v),+ "em" => Calc::Em(v),+ "ex" | "rex" => Calc::Em(v * 0.5),+ "ch" | "rch" => Calc::Em(v * 0.55),+ "cap" | "rcap" => Calc::Em(v * 0.7),+ "ic" | "ric" => Calc::Em(v),+ "lh" => Calc::Em(v * 1.3),+ "rlh" => Calc::Px(v * ROOT_FONT_SIZE * 1.3),+ "vw" | "svw" | "lvw" | "dvw" | "vi" | "svi" | "lvi" | "dvi" | "cqw" | "cqi" => Calc::Vw(v),+ "vh" | "svh" | "lvh" | "dvh" | "vb" | "svb" | "lvb" | "dvb" | "cqh" | "cqb" => Calc::Vh(v),+ "vmin" | "svmin" | "lvmin" | "dvmin" | "cqmin" => Calc::Vmin(v),+ "vmax" | "svmax" | "lvmax" | "dvmax" | "cqmax" => Calc::Vmax(v),+ "pt" => Calc::Px(v * 4.0 / 3.0),+ "pc" => Calc::Px(v * 16.0),+ "in" => Calc::Px(v * 96.0),+ "cm" => Calc::Px(v * 96.0 / 2.54),+ "mm" => Calc::Px(v * 96.0 / 25.4),+ "q" => Calc::Px(v * 96.0 / 101.6),+ "deg" => Calc::Num(v * PI / 180.0),+ "grad" => Calc::Num(v * PI / 200.0),+ "rad" => Calc::Num(v),+ "turn" => Calc::Num(v * 2.0 * PI),+ "s" => Calc::Num(v),+ "ms" => Calc::Num(v / 1000.0),+ "x" | "dppx" => Calc::Num(v),+ "dpi" => Calc::Num(v / 96.0),+ "dpcm" => Calc::Num(v * 2.54 / 96.0),+ "fr" => return None,+ _ => return None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::css::tokenize;++ fn eval(s: &str, basis: f32) -> f32 {+ let t = tokenize(s);+ let Tok::Func(fx) = &t[0] else { panic!("{s}") };+ let c = Calc::parse_fn(&fx.name, &fx.args).unwrap_or_else(|| panic!("parse {s}"));+ c.eval_units(&Units { font_size: 10.0, viewport: (1000.0, 500.0) }, basis)+ }++ #[test]+ fn arithmetic_and_units() {+ assert_eq!(eval("calc(100% - 2rem)", 200.0), 168.0);+ assert_eq!(eval("calc(100%-2rem)", 200.0), 168.0);+ assert_eq!(eval("calc((1px + 2px) * 3)", 0.0), 9.0);+ assert_eq!(eval("calc(10px * 2 / 4)", 0.0), 5.0);+ assert_eq!(eval("calc(2em + 10vw)", 0.0), 120.0);+ assert_eq!(eval("calc(-1 * 5px)", 0.0), -5.0);+ assert_eq!(eval("calc(50vmin)", 0.0), 250.0);+ }++ #[test]+ fn functions() {+ assert_eq!(eval("min(10px, 5px, 20px)", 0.0), 5.0);+ assert_eq!(eval("max(10%, 30px)", 100.0), 30.0);+ assert_eq!(eval("clamp(10px, 50%, 40px)", 200.0), 40.0);+ assert_eq!(eval("round(up, 11px, 5px)", 0.0), 15.0);+ assert_eq!(eval("round(12.4px, 1px)", 0.0), 12.0);+ assert_eq!(eval("mod(-7px, 3px)", 0.0), 2.0);+ assert_eq!(eval("rem(-7px, 3px)", 0.0), -1.0);+ assert_eq!(eval("abs(-4px)", 0.0), 4.0);+ assert_eq!(eval("calc(sign(-3px) * 2px)", 0.0), -2.0);+ assert!((eval("calc(sin(90deg) * 10px)", 0.0) - 10.0).abs() < 1e-4);+ assert_eq!(eval("calc(pow(2, 3) * 1px)", 0.0), 8.0);+ assert_eq!(eval("hypot(3px, 4px)", 0.0), 5.0);+ assert!((eval("calc(pi * 1px)", 0.0) - std::f32::consts::PI).abs() < 1e-6);+ }++ #[test]+ fn interned_and_resolved() {+ let t = tokenize("calc(100% - 1em)");+ let Tok::Func(fx) = &t[0] else { panic!() };+ let a = Calc::parse_fn(&fx.name, &fx.args).unwrap();+ let b = Calc::parse_fn(&fx.name, &fx.args).unwrap();+ assert!(std::ptr::eq(a, b));+ let r = a.resolve(&Units { font_size: 20.0, viewport: (0.0, 0.0) });+ assert_eq!(r.eval(100.0), 80.0);+ assert_eq!(r.as_ptr() as usize % 8, 0);+ }+}diff --git a/bindings/rust/blenderui/src/color.rs b/bindings/rust/blenderui/src/color.rsindex c3fdd85..4971ad3 100644--- a/bindings/rust/blenderui/src/color.rs+++ b/bindings/rust/blenderui/src/color.rs@@ -137,9 +137,10 @@ pub(crate) const NAMED: &[(&str, u32)] = &[("yellow", 0xffff00), ("yellowgreen", 0x9acd32),];-/// Parse a CSS color: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()`,-/// `hsl()`/`hsla()` (comma or space syntax, `/ alpha`), named colors and-/// `transparent`. `currentcolor` is resolved by the cascade.+/// Parse a CSS color: hex, named and system colors, `transparent`, and every+/// CSS Color 4/5 function (`rgb`, `hsl`, `hwb`, `lab`, `lch`, `oklab`,+/// `oklch`, `color()`, `color-mix()`, relative colors, `light-dark()`).+/// `currentcolor` is resolved by the cascade.pub fn parse_color(s: &str) -> Option<Rgba> {let s = s.trim().to_ascii_lowercase();if s == "transparent" {@@ -156,32 +157,9 @@ pub fn parse_color(s: &str) -> Option<Rgba> {_ => return None,});}- if let Some((name, rest)) = s.split_once('(') {- let args: Vec<&str> = rest- .trim_end_matches(')')- .split(|c: char| c == ',' || c == '/' || c.is_whitespace())- .filter(|a| !a.is_empty())- .collect();- let num = |a: &str, scale: f32| -> Option<f32> {- match a.strip_suffix('%') {- Some(p) => p.parse::<f32>().ok().map(|v| v / 100.0),- None => a.trim_end_matches("deg").parse::<f32>().ok().map(|v| v / scale),- }- };- let alpha = args.get(3).and_then(|a| num(a, 1.0)).unwrap_or(1.0);- return match name.trim() {- "rgb" | "rgba" => Some(Rgba {- r: num(args.first()?, 255.0)?,- g: num(args.get(1)?, 255.0)?,- b: num(args.get(2)?, 255.0)?,- a: alpha,- }),- "hsl" | "hsla" => Some(hsla(- num(args.first()?, 360.0)?,- num(args.get(1)?, 100.0)?,- num(args.get(2)?, 100.0)?,- alpha,- )),+ if s.contains('(') {+ return match crate::css::tokenize(&s).as_slice() {+ [crate::css::Tok::Func(fx)] => crate::color4::color_fn(fx, Rgba::TRANSPARENT),_ => None,};}diff --git a/bindings/rust/blenderui/src/color4.rs b/bindings/rust/blenderui/src/color4.rsnew file mode 100644index 0000000..1487b6a--- /dev/null+++ b/bindings/rust/blenderui/src/color4.rs@@ -0,0 +1,661 @@+//! CSS Color Level 4 / 5 on tokens: `rgb()` / `hsl()` (legacy and modern+//! syntax, `none`), `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`,+//! `color()` in every predefined space, `color-mix()` (all interpolation+//! spaces and hue methods, premultiplied), relative colors+//! (`oklch(from var(--c) calc(l + 0.1) c h / 50%)`), `light-dark()`,+//! system colors, `calc()` in channels, and CSS gamut mapping (chroma+//! reduction in OKLCh) into sRGB.++use crate::color::Rgba;+use crate::css::{FuncTok, Tok};++type V3 = [f64; 3];++fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 {+ [+ m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],+ m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],+ m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],+ ]+}++const SRGB_TO_XYZ: [[f64; 3]; 3] = [+ [0.41239079926595934, 0.357584339383878, 0.1804807884018343],+ [0.21263900587151027, 0.715168678767756, 0.07219231536073371],+ [0.01933081871559182, 0.11919477979462598, 0.9505321522496607],+];+const XYZ_TO_SRGB: [[f64; 3]; 3] = [+ [3.2409699419045226, -1.537383177570094, -0.4986107602930034],+ [-0.9692436362808796, 1.8759675015077202, 0.04155505740717559],+ [0.05563007969699366, -0.20397695888897652, 1.0569715142428786],+];+const D65_TO_D50: [[f64; 3]; 3] = [+ [1.0479298208405488, 0.022946793341019088, -0.05019222954313557],+ [0.029627815688159344, 0.990434484573249, -0.01707382502938514],+ [-0.009243058152591178, 0.015055144896577895, 0.7518742899580008],+];+const D50_TO_D65: [[f64; 3]; 3] = [+ [0.9554734527042182, -0.023098536874261423, 0.0632593086610217],+ [-0.028369706963208136, 1.0099954580058226, 0.021041398966943008],+ [0.012314001688319899, -0.020507696433477912, 1.3303659366080753],+];+const XYZ_TO_LMS: [[f64; 3]; 3] = [+ [0.8190224379967030, 0.3619062600528904, -0.1288737815209879],+ [0.0329836539323885, 0.9292868615863434, 0.0361446663506424],+ [0.0481771893596242, 0.2642395317527308, 0.6335478284694309],+];+const LMS_TO_OKLAB: [[f64; 3]; 3] = [+ [0.2104542683093140, 0.7936177747023054, -0.0040720430116193],+ [1.9779985324311684, -2.4285922420485799, 0.4505937096174110],+ [0.0259040424655478, 0.7827717124575296, -0.8086757549230774],+];+const OKLAB_TO_LMS: [[f64; 3]; 3] = [+ [1.0, 0.3963377773761749, 0.2158037573099136],+ [1.0, -0.1055613458156586, -0.0638541728258133],+ [1.0, -0.0894841775298119, -1.2914855480194092],+];+const LMS_TO_XYZ: [[f64; 3]; 3] = [+ [1.2268798758459243, -0.5578149944602171, 0.2813910456659647],+ [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164],+ [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816],+];+const P3_TO_XYZ: [[f64; 3]; 3] = [+ [0.48657094864821626, 0.26566769316909294, 0.1982172852343625],+ [0.22897456406974884, 0.6917385218365062, 0.079286914093745],+ [0.0, 0.045113381858902575, 1.0439443689009757],+];+const A98_TO_XYZ: [[f64; 3]; 3] = [+ [0.5766690429101305, 0.1855582379065463, 0.1882286462349947],+ [0.29734497525053605, 0.6273635662554661, 0.07529145849399788],+ [0.02703136138641234, 0.07068885253582723, 0.9913375368376388],+];+const PROPHOTO_TO_XYZ50: [[f64; 3]; 3] = [+ [0.7977666449006423, 0.13518129740053308, 0.0313477341283922],+ [0.2880748288194013, 0.711835234241873, 0.00008993693872564],+ [0.0, 0.0, 0.8251046025104602],+];+const REC2020_TO_XYZ: [[f64; 3]; 3] = [+ [0.6369580483012914, 0.14461690358620832, 0.1688809751641721],+ [0.2627002120112671, 0.6779980715188708, 0.05930171646986196],+ [0.0, 0.028072693049087428, 1.060985057710791],+];+const D50_WHITE: V3 = [0.3457 / 0.3585, 1.0, (1.0 - 0.3457 - 0.3585) / 0.3585];++fn inv(m: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {+ let [[a, b, c], [d, e, f], [g, h, i]] = *m;+ let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);+ let k = 1.0 / det;+ [+ [(e * i - f * h) * k, (c * h - b * i) * k, (b * f - c * e) * k],+ [(f * g - d * i) * k, (a * i - c * g) * k, (c * d - a * f) * k],+ [(d * h - e * g) * k, (b * g - a * h) * k, (a * e - b * d) * k],+ ]+}++fn srgb_to_lin(v: f64) -> f64 {+ let a = v.abs();+ let r = if a <= 0.04045 { a / 12.92 } else { ((a + 0.055) / 1.055).powf(2.4) };+ r.copysign(v)+}+fn lin_to_srgb(v: f64) -> f64 {+ let a = v.abs();+ let r = if a > 0.0031308 { 1.055 * a.powf(1.0 / 2.4) - 0.055 } else { 12.92 * a };+ r.copysign(v)+}++/// The color spaces CSS can name, for `color()` and `color-mix()`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Space {+ Srgb,+ SrgbLinear,+ DisplayP3,+ A98,+ ProPhoto,+ Rec2020,+ XyzD50,+ XyzD65,+ Lab,+ Lch,+ Oklab,+ Oklch,+ Hsl,+ Hwb,+}++impl Space {+ pub fn named(s: &str) -> Option<Space> {+ Some(match s {+ "srgb" => Space::Srgb,+ "srgb-linear" => Space::SrgbLinear,+ "display-p3" | "display-p3-linear" => Space::DisplayP3,+ "a98-rgb" => Space::A98,+ "prophoto-rgb" => Space::ProPhoto,+ "rec2020" => Space::Rec2020,+ "xyz-d50" => Space::XyzD50,+ "xyz" | "xyz-d65" => Space::XyzD65,+ "lab" => Space::Lab,+ "lch" => Space::Lch,+ "oklab" => Space::Oklab,+ "oklch" => Space::Oklch,+ "hsl" => Space::Hsl,+ "hwb" => Space::Hwb,+ _ => return None,+ })+ }++ fn hue_index(self) -> Option<usize> {+ match self {+ Space::Lch | Space::Oklch => Some(2),+ Space::Hsl | Space::Hwb => Some(0),+ _ => None,+ }+ }++ /// Coordinates in this space -> CIE XYZ (D65).+ pub fn to_xyz(self, c: V3) -> V3 {+ match self {+ Space::Srgb => mul(&SRGB_TO_XYZ, c.map(srgb_to_lin)),+ Space::SrgbLinear => mul(&SRGB_TO_XYZ, c),+ Space::DisplayP3 => mul(&P3_TO_XYZ, c.map(srgb_to_lin)),+ Space::A98 => mul(&A98_TO_XYZ, c.map(|v| v.abs().powf(563.0 / 256.0).copysign(v))),+ Space::ProPhoto => {+ let lin = c.map(|v| {+ let a = v.abs();+ (if a <= 16.0 / 512.0 { a / 16.0 } else { a.powf(1.8) }).copysign(v)+ });+ mul(&D50_TO_D65, mul(&PROPHOTO_TO_XYZ50, lin))+ }+ Space::Rec2020 => {+ const A: f64 = 1.09929682680944;+ const B: f64 = 0.018053968510807;+ let lin = c.map(|v| {+ let a = v.abs();+ (if a < B * 4.5 { a / 4.5 } else { ((a + A - 1.0) / A).powf(1.0 / 0.45) }).copysign(v)+ });+ mul(&REC2020_TO_XYZ, lin)+ }+ Space::XyzD65 => c,+ Space::XyzD50 => mul(&D50_TO_D65, c),+ Space::Lab => mul(&D50_TO_D65, lab_to_xyz50(c)),+ Space::Lch => Space::Lab.to_xyz(lch_to_lab(c)),+ Space::Oklab => oklab_to_xyz(c),+ Space::Oklch => oklab_to_xyz(lch_to_lab(c)),+ Space::Hsl => Space::Srgb.to_xyz(hsl_to_srgb(c)),+ Space::Hwb => Space::Srgb.to_xyz(hwb_to_srgb(c)),+ }+ }++ /// CIE XYZ (D65) -> coordinates in this space.+ pub fn from_xyz(self, x: V3) -> V3 {+ match self {+ Space::Srgb => mul(&XYZ_TO_SRGB, x).map(lin_to_srgb),+ Space::SrgbLinear => mul(&XYZ_TO_SRGB, x),+ Space::DisplayP3 => mul(&inv(&P3_TO_XYZ), x).map(lin_to_srgb),+ Space::A98 => mul(&inv(&A98_TO_XYZ), x).map(|v| v.abs().powf(256.0 / 563.0).copysign(v)),+ Space::ProPhoto => mul(&inv(&PROPHOTO_TO_XYZ50), mul(&D65_TO_D50, x)).map(|v| {+ let a = v.abs();+ (if a >= 1.0 / 512.0 { a.powf(1.0 / 1.8) } else { 16.0 * a }).copysign(v)+ }),+ Space::Rec2020 => {+ const A: f64 = 1.09929682680944;+ const B: f64 = 0.018053968510807;+ mul(&inv(&REC2020_TO_XYZ), x).map(|v| {+ let a = v.abs();+ (if a > B { A * a.powf(0.45) - (A - 1.0) } else { 4.5 * a }).copysign(v)+ })+ }+ Space::XyzD65 => x,+ Space::XyzD50 => mul(&D65_TO_D50, x),+ Space::Lab => xyz50_to_lab(mul(&D65_TO_D50, x)),+ Space::Lch => lab_to_lch(Space::Lab.from_xyz(x)),+ Space::Oklab => xyz_to_oklab(x),+ Space::Oklch => lab_to_lch(xyz_to_oklab(x)),+ Space::Hsl => srgb_to_hsl(Space::Srgb.from_xyz(x)),+ Space::Hwb => srgb_to_hwb(Space::Srgb.from_xyz(x)),+ }+ }+}++fn lab_to_xyz50(lab: V3) -> V3 {+ const K: f64 = 24389.0 / 27.0;+ const E: f64 = 216.0 / 24389.0;+ let f1 = (lab[0] + 16.0) / 116.0;+ let f0 = lab[1] / 500.0 + f1;+ let f2 = f1 - lab[2] / 200.0;+ let x = if f0.powi(3) > E { f0.powi(3) } else { (116.0 * f0 - 16.0) / K };+ let y = if lab[0] > K * E { ((lab[0] + 16.0) / 116.0).powi(3) } else { lab[0] / K };+ let z = if f2.powi(3) > E { f2.powi(3) } else { (116.0 * f2 - 16.0) / K };+ [x * D50_WHITE[0], y * D50_WHITE[1], z * D50_WHITE[2]]+}++fn xyz50_to_lab(x: V3) -> V3 {+ const K: f64 = 24389.0 / 27.0;+ const E: f64 = 216.0 / 24389.0;+ let f = |v: f64| if v > E { v.cbrt() } else { (K * v + 16.0) / 116.0 };+ let [fx, fy, fz] = [f(x[0] / D50_WHITE[0]), f(x[1] / D50_WHITE[1]), f(x[2] / D50_WHITE[2])];+ [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]+}++fn oklab_to_xyz(lab: V3) -> V3 {+ mul(&LMS_TO_XYZ, mul(&OKLAB_TO_LMS, lab).map(|v| v * v * v))+}++fn xyz_to_oklab(x: V3) -> V3 {+ mul(&LMS_TO_OKLAB, mul(&XYZ_TO_LMS, x).map(f64::cbrt))+}++fn lch_to_lab(c: V3) -> V3 {+ let h = c[2].to_radians();+ [c[0], c[1] * h.cos(), c[1] * h.sin()]+}++fn lab_to_lch(c: V3) -> V3 {+ let ch = (c[1] * c[1] + c[2] * c[2]).sqrt();+ let h = if ch < 1e-6 { 0.0 } else { c[2].atan2(c[1]).to_degrees().rem_euclid(360.0) };+ [c[0], ch, h]+}++/// hsl(h deg, s 0..1, l 0..1) -> sRGB 0..1+fn hsl_to_srgb(c: V3) -> V3 {+ let (h, s, l) = (c[0].rem_euclid(360.0), c[1], c[2]);+ let f = |n: f64| {+ let k = (n + h / 30.0) % 12.0;+ let a = s * l.min(1.0 - l);+ l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)+ };+ [f(0.0), f(8.0), f(4.0)]+}++fn srgb_to_hsl(c: V3) -> V3 {+ let (r, g, b) = (c[0], c[1], c[2]);+ let (mx, mn) = (r.max(g).max(b), r.min(g).min(b));+ let l = (mx + mn) / 2.0;+ let d = mx - mn;+ if d.abs() < 1e-9 {+ return [0.0, 0.0, l];+ }+ let s = if l == 0.0 || l == 1.0 { 0.0 } else { (mx - l) / l.min(1.0 - l) };+ let h = if mx == r {+ (g - b) / d + if g < b { 6.0 } else { 0.0 }+ } else if mx == g {+ (b - r) / d + 2.0+ } else {+ (r - g) / d + 4.0+ };+ [h * 60.0, s, l]+}++fn hwb_to_srgb(c: V3) -> V3 {+ let (w, b) = (c[1], c[2]);+ if w + b >= 1.0 {+ let g = w / (w + b);+ return [g, g, g];+ }+ hsl_to_srgb([c[0], 1.0, 0.5]).map(|v| v * (1.0 - w - b) + w)+}++fn srgb_to_hwb(c: V3) -> V3 {+ let h = srgb_to_hsl(c)[0];+ let w = c[0].min(c[1]).min(c[2]);+ let b = 1.0 - c[0].max(c[1]).max(c[2]);+ [h, w, b]+}++/// CSS Color 4 gamut mapping: reduce OKLCh chroma until the color is in+/// sRGB (within a just-noticeable difference), instead of plain clipping.+fn gamut_map_srgb(xyz: V3) -> V3 {+ let rgb = Space::Srgb.from_xyz(xyz);+ let inside = |c: &V3| c.iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(v));+ if inside(&rgb) {+ return rgb.map(|v| v.clamp(0.0, 1.0));+ }+ let lch = Space::Oklch.from_xyz(xyz);+ if lch[0] >= 1.0 {+ return [1.0; 3];+ }+ if lch[0] <= 0.0 {+ return [0.0; 3];+ }+ let clip = |c: V3| c.map(|v| v.clamp(0.0, 1.0));+ let delta = |a: V3, b: V3| {+ let (x, y) = (xyz_to_oklab(Space::Srgb.to_xyz(a)), xyz_to_oklab(Space::Srgb.to_xyz(b)));+ ((x[0] - y[0]).powi(2) + (x[1] - y[1]).powi(2) + (x[2] - y[2]).powi(2)).sqrt()+ };+ let (mut lo, mut hi) = (0.0, lch[1]);+ let mut best = clip(rgb);+ for _ in 0..24 {+ let mid = (lo + hi) / 2.0;+ let cand = Space::Srgb.from_xyz(Space::Oklch.to_xyz([lch[0], mid, lch[2]]));+ if inside(&cand) {+ lo = mid;+ best = clip(cand);+ } else {+ let clipped = clip(cand);+ if delta(clipped, cand) < 0.02 {+ return clipped;+ }+ hi = mid;+ }+ }+ best+}++fn to_rgba(space: Space, c: V3, alpha: f64) -> Rgba {+ let rgb = if space == Space::Srgb && c.iter().all(|v| (0.0..=1.0).contains(v)) {+ c+ } else {+ gamut_map_srgb(space.to_xyz(c))+ };+ Rgba { r: rgb[0] as f32, g: rgb[1] as f32, b: rgb[2] as f32, a: alpha.clamp(0.0, 1.0) as f32 }+}++fn coords(space: Space, c: Rgba) -> V3 {+ let rgb = [c.r as f64, c.g as f64, c.b as f64];+ if space == Space::Srgb { rgb } else { space.from_xyz(Space::Srgb.to_xyz(rgb)) }+}++// -- parsing ---------------------------------------------------------------------------++/// What `light-dark()` picks: the UI is dark.+pub const DARK: bool = true;++/// A system color (`Canvas`, `LinkText` ...), in the kit's dark theme.+pub fn system(name: &str) -> Option<Rgba> {+ use crate::color::rgb;+ Some(match name {+ "canvas" | "field" | "window" | "background" | "appworkspace" => rgb(0x282828),+ "canvastext" | "fieldtext" | "windowtext" | "captiontext" | "infotext" | "menutext"+ | "buttontext" => rgb(0xe6e6e6),+ "linktext" => rgb(0x5c9ce6),+ "visitedtext" => rgb(0xb07ce6),+ "activetext" => rgb(0xe65c5c),+ "buttonface" | "buttonhighlight" | "buttonshadow" | "threedface" | "threedhighlight"+ | "threedshadow" | "threeddarkshadow" | "threedlightshadow" | "menu" | "scrollbar" => rgb(0x545454),+ "buttonborder" | "activeborder" | "inactiveborder" | "windowframe" => rgb(0x3d3d3d),+ "highlight" | "selecteditem" | "accentcolor" | "activecaption" => rgb(0x4772b3),+ "highlighttext" | "selecteditemtext" | "accentcolortext" | "inactivecaptiontext" => rgb(0xffffff),+ "mark" => rgb(0xe6c84a),+ "marktext" => rgb(0x000000),+ "graytext" | "inactivecaption" | "infobackground" | "inactiveborder2" => rgb(0x8c8c8c),+ _ => return None,+ })+}++/// Channel keywords of a relative color (`from <color>`), in the target space.+type Channels = [(&'static str, f64); 4];++/// One component: number, percentage (of `pct_ref`), angle (hue), `none`,+/// `calc()`, or a channel keyword of a relative color.+fn component(toks: &[Tok], pct_ref: f64, hue: bool, ch: Option<&Channels>) -> Option<f64> {+ let t = match toks {+ [t] => t,+ _ => return None,+ };+ let chan = |name: &str| ch.and_then(|c| c.iter().find(|(n, _)| *n == name).map(|(_, v)| *v));+ Some(match t {+ Tok::Num(v) => *v as f64,+ Tok::Pct(p) => *p as f64 / 100.0 * pct_ref,+ Tok::Dim(v, u) if hue => match u.as_ref() {+ "deg" => *v as f64,+ "rad" => (*v as f64).to_degrees(),+ "grad" => *v as f64 * 0.9,+ "turn" => *v as f64 * 360.0,+ _ => return None,+ },+ Tok::Ident(s) if s == "none" => 0.0,+ Tok::Ident(s) => chan(s)?,+ Tok::Func(fx) if crate::calc::is_math_fn(&fx.name) => {+ // channel keywords inside calc() become their numbers+ let args: Vec<Vec<Tok>> = fx.args.iter().map(|a| a.iter().map(|t| match t {+ Tok::Ident(s) => chan(s).map(|v| Tok::Num(v as f32)).unwrap_or_else(|| t.clone()),+ other => other.clone(),+ }).collect()).collect();+ let c = crate::calc::Calc::parse_fn(&fx.name, &args)?;+ let u = crate::geometry::Units { font_size: 16.0, viewport: (0.0, 0.0) };+ let v = c.eval_units(&u, 100.0) as f64;+ // a percentage inside calc resolves against 100: rescale it+ if c.has_pct() { v / 100.0 * pct_ref } else { v }+ }+ _ => return None,+ })+}++/// Components of a color function: (c1, c2, c3, alpha tokens), modern+/// (`a b c / d`) or legacy (`a, b, c, d`) syntax.+fn split_components(args: &[Vec<Tok>]) -> Option<(Vec<Vec<Tok>>, Option<Vec<Tok>>)> {+ if args.len() >= 3 {+ let parts: Vec<Vec<Tok>> = args.iter().take(3).cloned().collect();+ return Some((parts, args.get(3).cloned()));+ }+ let toks = args.first()?;+ let (main, alpha) = match toks.iter().position(|t| matches!(t, Tok::Slash)) {+ Some(i) => (&toks[..i], Some(toks[i + 1..].to_vec())),+ None => (&toks[..], None),+ };+ Some((main.iter().map(|t| vec![t.clone()]).collect(), alpha))+}++/// A color function token (`rgb(...)`, `color-mix(...)` ...).+pub fn color_fn(fx: &FuncTok, current: Rgba) -> Option<Rgba> {+ let name = fx.name.as_ref();+ match name {+ "light-dark" => {+ let pick = if DARK { fx.args.get(1)? } else { fx.args.first()? };+ return color_toks(pick, current);+ }+ "color-mix" => return color_mix(fx, current),+ _ => {}+ }+ // relative color: `from <color>` first+ let (base, args): (Option<Rgba>, Vec<Vec<Tok>>) = match fx.args.first().and_then(|a| a.first()) {+ Some(Tok::Ident(s)) if s == "from" => {+ let a0 = fx.args.first()?;+ let base = color_toks(&a0[1..2], current)?;+ let mut rest = vec![a0[2..].to_vec()];+ rest.extend(fx.args[1..].iter().cloned());+ (Some(base), rest)+ }+ _ => (None, fx.args.clone()),+ };+ let (space, args) = if name == "color" {+ let first = args.first()?;+ let sp = Space::named(first.first()?.ident()?)?;+ let mut rest = vec![first[1..].to_vec()];+ rest.extend(args[1..].iter().cloned());+ (sp, rest)+ } else {+ (match name {+ "rgb" | "rgba" => Space::Srgb,+ "hsl" | "hsla" => Space::Hsl,+ "hwb" => Space::Hwb,+ "lab" => Space::Lab,+ "lch" => Space::Lch,+ "oklab" => Space::Oklab,+ "oklch" => Space::Oklch,+ _ => return None,+ }, args)+ };+ let (parts, alpha) = split_components(&args)?;+ if parts.len() != 3 {+ return None;+ }+ // channel keywords for relative colors, in the units the syntax uses+ let channels: Option<Channels> = base.map(|b| {+ let c = coords(space, b);+ let a = b.a as f64;+ match name {+ "rgb" | "rgba" => [("r", c[0] * 255.0), ("g", c[1] * 255.0), ("b", c[2] * 255.0), ("alpha", a)],+ "hsl" | "hsla" => [("h", c[0]), ("s", c[1] * 100.0), ("l", c[2] * 100.0), ("alpha", a)],+ "hwb" => [("h", c[0]), ("w", c[1] * 100.0), ("b", c[2] * 100.0), ("alpha", a)],+ "lab" | "oklab" => [("l", c[0]), ("a", c[1]), ("b", c[2]), ("alpha", a)],+ "lch" | "oklch" => [("l", c[0]), ("c", c[1]), ("h", c[2]), ("alpha", a)],+ _ => match space {+ Space::XyzD50 | Space::XyzD65 => [("x", c[0]), ("y", c[1]), ("z", c[2]), ("alpha", a)],+ _ => [("r", c[0]), ("g", c[1]), ("b", c[2]), ("alpha", a)],+ },+ }+ });+ let ch = channels.as_ref();+ let comp = |i: usize, pct: f64, hue: bool| component(&parts[i], pct, hue, ch);+ let c = match name {+ "rgb" | "rgba" => [comp(0, 255.0, false)? / 255.0, comp(1, 255.0, false)? / 255.0,+ comp(2, 255.0, false)? / 255.0],+ // s / l (w / b) as percentages; bare numbers in modern syntax mean percent too+ "hsl" | "hsla" | "hwb" => [comp(0, 0.0, true)?, comp(1, 100.0, false)? / 100.0,+ comp(2, 100.0, false)? / 100.0],+ "lab" => [comp(0, 100.0, false)?, comp(1, 125.0, false)?, comp(2, 125.0, false)?],+ "lch" => [comp(0, 100.0, false)?, comp(1, 150.0, false)?, comp(2, 0.0, true)?],+ "oklab" => [comp(0, 1.0, false)?, comp(1, 0.4, false)?, comp(2, 0.4, false)?],+ "oklch" => [comp(0, 1.0, false)?, comp(1, 0.4, false)?, comp(2, 0.0, true)?],+ _ => [comp(0, 1.0, false)?, comp(1, 1.0, false)?, comp(2, 1.0, false)?],+ };+ let a = match &alpha {+ Some(t) => component(t, 1.0, false, ch)?,+ None => base.map(|b| b.a as f64).unwrap_or(1.0),+ };+ let c = match space {+ Space::Lch | Space::Oklch => [c[0], c[1].max(0.0), c[2]],+ Space::Lab | Space::Oklab => c,+ _ => c,+ };+ Some(to_rgba(space, c, a.clamp(0.0, 1.0)))+}++/// A color from a token list (one color value).+pub fn color_toks(toks: &[Tok], current: Rgba) -> Option<Rgba> {+ match toks {+ [t] => crate::style::color(t, current),+ _ => None,+ }+}++#[derive(Clone, Copy)]+enum HueMethod {+ Shorter,+ Longer,+ Increasing,+ Decreasing,+}++fn color_mix(fx: &FuncTok, current: Rgba) -> Option<Rgba> {+ // in <space> [<method> hue], <color> [<pct>], <color> [<pct>]+ let head = fx.args.first()?;+ if head.first()?.ident()? != "in" {+ return None;+ }+ let space = Space::named(head.get(1)?.ident()?)?;+ let method = match head.get(2).and_then(Tok::ident) {+ Some("longer") => HueMethod::Longer,+ Some("increasing") => HueMethod::Increasing,+ Some("decreasing") => HueMethod::Decreasing,+ _ => HueMethod::Shorter,+ };+ let item = |toks: &Vec<Tok>| -> Option<(Rgba, Option<f64>)> {+ let pct = toks.iter().find_map(|t| match t {+ Tok::Pct(p) => Some(*p as f64 / 100.0),+ _ => None,+ });+ let col: Vec<Tok> = toks.iter().filter(|t| !matches!(t, Tok::Pct(_))).cloned().collect();+ Some((color_toks(&col, current)?, pct))+ };+ let (c1, p1) = item(fx.args.get(1)?)?;+ let (c2, p2) = item(fx.args.get(2)?)?;+ let (mut p1, mut p2) = match (p1, p2) {+ (None, None) => (0.5, 0.5),+ (Some(a), None) => (a, 1.0 - a),+ (None, Some(b)) => (1.0 - b, b),+ (Some(a), Some(b)) => (a, b),+ };+ let sum = p1 + p2;+ if sum <= 0.0 {+ return None;+ }+ let alpha_mult = sum.min(1.0);+ p1 /= sum;+ p2 /= sum;+ let (mut a, mut b) = (coords(space, c1), coords(space, c2));+ if let Some(h) = space.hue_index() {+ let (h1, h2) = (a[h].rem_euclid(360.0), b[h].rem_euclid(360.0));+ let d = h2 - h1;+ let h2 = match method {+ HueMethod::Shorter if d > 180.0 => h2 - 360.0,+ HueMethod::Shorter if d < -180.0 => h2 + 360.0,+ HueMethod::Longer if (0.0..=180.0).contains(&d) && d != 0.0 => h2 - 360.0,+ HueMethod::Longer if (-180.0..0.0).contains(&d) => h2 + 360.0,+ HueMethod::Increasing if d < 0.0 => h2 + 360.0,+ HueMethod::Decreasing if d > 0.0 => h2 - 360.0,+ _ => h2,+ };+ a[h] = h1;+ b[h] = h2;+ }+ // premultiplied interpolation (hue is not premultiplied)+ let (a1, a2) = (c1.a as f64, c2.a as f64);+ let alpha = a1 * p1 + a2 * p2;+ let mut out = [0.0; 3];+ for k in 0..3 {+ out[k] = if Some(k) == space.hue_index() {+ a[k] * p1 + b[k] * p2+ } else if alpha > 0.0 {+ (a[k] * a1 * p1 + b[k] * a2 * p2) / alpha+ } else {+ a[k] * p1 + b[k] * p2+ };+ }+ Some(to_rgba(space, out, alpha * alpha_mult))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::css::tokenize;++ fn col(s: &str) -> Rgba {+ let t = tokenize(s);+ crate::style::color(&t[0], Rgba::TRANSPARENT).unwrap_or_else(|| panic!("{s}"))+ }++ fn hex(c: Rgba) -> u32 {+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u32;+ (q(c.r) << 16) | (q(c.g) << 8) | q(c.b)+ }++ #[test]+ fn modern_functions() {+ assert_eq!(hex(col("rgb(255 0 0 / 50%)")), 0xff0000);+ assert_eq!(col("rgb(255 0 0 / 50%)").a, 0.5);+ assert_eq!(hex(col("rgb(100% 50% 0%)")), 0xff8000);+ assert_eq!(hex(col("hsl(120deg 100% 50%)")), 0x00ff00);+ assert_eq!(hex(col("hsl(0.5turn 100 50)")), 0x00ffff);+ assert_eq!(hex(col("hwb(0 0% 0%)")), 0xff0000);+ assert_eq!(hex(col("lab(100 0 0)")), 0xffffff);+ assert_eq!(hex(col("lch(0% 0 0)")), 0x000000);+ assert_eq!(hex(col("oklab(1 0 0)")), 0xffffff);+ assert_eq!(hex(col("oklch(62.8% 0.2577 29.23)")), 0xff0000);+ assert_eq!(hex(col("color(srgb 1 0.5 0)")), 0xff8000);+ assert_eq!(hex(col("color(srgb-linear 1 1 1)")), 0xffffff);+ assert_eq!(hex(col("color(xyz-d65 0.9505 1 1.089)")), 0xffffff);+ assert_eq!(hex(col("rgb(none 0 0)")), 0x000000);+ }++ #[test]+ fn out_of_gamut_is_mapped() {+ // display-p3 pure red is outside sRGB: chroma-reduced, still clearly red+ let c = col("color(display-p3 1 0 0)");+ assert!(c.r > 0.95 && c.g < 0.25 && c.b < 0.25, "{c:?}");+ }++ #[test]+ fn mixing_and_relative_colors() {+ assert_eq!(hex(col("color-mix(in srgb, red, blue)")), 0x800080);+ assert_eq!(hex(col("color-mix(in srgb, red 25%, blue)")), 0x4000bf);+ let m = col("color-mix(in srgb, red 30%, blue 30%)");+ assert!((m.a - 0.6).abs() < 1e-3);+ let ok = col("color-mix(in oklch, red, blue)");+ assert!(ok.r > 0.5 && ok.b > 0.5, "{ok:?}");+ assert_eq!(hex(col("rgb(from red r g 255)")), 0xff00ff);+ assert_eq!(hex(col("rgb(from #808080 calc(r * 2) g b)")), 0xff8080);+ assert_eq!(col("hsl(from red h s l / 0.25)").a, 0.25);+ assert_eq!(hex(col("light-dark(white, black)")), 0x000000);+ }+}diff --git a/bindings/rust/blenderui/src/css.rs b/bindings/rust/blenderui/src/css.rsindex 9765890..1399b08 100644--- a/bindings/rust/blenderui/src/css.rs+++ b/bindings/rust/blenderui/src/css.rs@@ -27,6 +27,8 @@ pub enum Tok {Func(Box<FuncTok>),/// A color given as a value (typed style methods: `.bg(rgb(..))`).Color(crate::color::Rgba),+ /// A parsed math expression (typed style methods: `.w(calc(..))`).+ Calc(&'static crate::calc::Calc),Comma,Slash,Delim(char),@@ -56,6 +58,9 @@ impl Tok {Length::Em(v) => Tok::Dim(v, Cow::Borrowed("em")),Length::Vw(v) => Tok::Dim(v, Cow::Borrowed("vw")),Length::Vh(v) => Tok::Dim(v, Cow::Borrowed("vh")),+ Length::Vmin(v) => Tok::Dim(v, Cow::Borrowed("vmin")),+ Length::Vmax(v) => Tok::Dim(v, Cow::Borrowed("vmax")),+ Length::Calc(c) => Tok::Calc(c),Length::Percent(v) => Tok::Pct(v),Length::Auto => Tok::Ident(Cow::Borrowed("auto")),}@@ -78,6 +83,7 @@ impl std::hash::Hash for Tok {}Tok::Color(c) => [c.r, c.g, c.b, c.a].map(f32::to_bits).hash(h),Tok::Delim(c) => c.hash(h),+ Tok::Calc(c) => (*c as *const crate::calc::Calc as usize).hash(h),Tok::Comma | Tok::Slash => {}}}@@ -219,7 +225,7 @@ pub(crate) fn split_top(s: &str, sep: char) -> Vec<&str> {/// A CSS property, as an index into the property table (`style::HANDLERS`,/// then `style::ACCEPTED`). Style methods resolve it at compile time with/// [`Prop::named`]; parsed CSS with [`Prop::lookup`].-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]pub struct Prop(pub(crate) u16);const fn str_eq(a: &str, b: &str) -> bool {@@ -240,8 +246,35 @@ const fn str_eq(a: &str, b: &str) -> bool {impl Prop {/// Not a property this engine knows.pub const UNKNOWN: Prop = Prop(u16::MAX);- /// A custom property (`--name`): accepted, no effect.+ /// A custom property whose name isn't known yet (`const` contexts).pub const CUSTOM: Prop = Prop(u16::MAX - 1);+ /// Custom properties (`--name`) are interned at run time from here up.+ pub(crate) const CUSTOM_BASE: u16 = 0x4000;++ /// Whether this is a custom property (`--name`).+ pub fn is_custom(self) -> bool {+ self.0 >= Prop::CUSTOM_BASE && self != Prop::UNKNOWN+ }++ /// The property for custom property `name` (`--x`), interned.+ pub fn custom(name: &str) -> Prop {+ use std::sync::{Mutex, OnceLock};+ type Names = (crate::style::FnvMap<&'static str, u16>, Vec<&'static str>);+ static NAMES: OnceLock<Mutex<Names>> = OnceLock::new();+ let mut t = NAMES.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());+ if let Some(&i) = t.0.get(name) {+ return Prop(Prop::CUSTOM_BASE + i);+ }+ let n = t.1.len() as u16;+ if Prop::CUSTOM_BASE as u32 + n as u32 >= (u16::MAX - 1) as u32 {+ return Prop::CUSTOM;+ }+ let leaked: &'static str = Box::leak(name.to_string().into_boxed_str());+ t.0.insert(leaked, n);+ t.1.push(leaked);+ CUSTOM_NAMES.get_or_init(|| Mutex::new(Vec::new())).lock().unwrap_or_else(|e| e.into_inner()).push(leaked);+ Prop(Prop::CUSTOM_BASE + n)+ }/// The property called `name`, evaluated at compile time in `const`/// contexts (an unknown name there is a compile error).@@ -274,8 +307,13 @@ impl Prop {crate::style::prop_index(name)}- /// The property's name ("" for unknown and custom properties).+ /// The property's name ("" for unknown properties).pub fn name(self) -> &'static str {+ if self.is_custom() && self != Prop::CUSTOM {+ let names = CUSTOM_NAMES.get_or_init(|| std::sync::Mutex::new(Vec::new()));+ let names = names.lock().unwrap_or_else(|e| e.into_inner());+ return names.get((self.0 - Prop::CUSTOM_BASE) as usize).copied().unwrap_or("");+ }let (h, a) = (crate::style::HANDLERS, crate::style::ACCEPTED);let i = self.0 as usize;if i < h.len() {@@ -294,6 +332,9 @@ impl std::fmt::Display for Prop {}}+/// Custom property names by index (`Prop::custom`).+static CUSTOM_NAMES: std::sync::OnceLock<std::sync::Mutex<Vec<&'static str>>> = std::sync::OnceLock::new();+/// A declaration's tokens: one inline token (typed style methods), a slice/// parsed once for the whole program (fixed style methods), or parsed CSS.#[derive(Clone, Debug)]@@ -400,498 +441,11 @@ pub(crate) fn strip_comments(s: &str) -> String {// ==========================================================================// Selectors-#[derive(Clone, Debug, PartialEq)]-enum AttrOp {- Exists,- Eq,- Word,- Prefix,- Suffix,- Contains,- Dash,-}--#[derive(Clone, Debug, PartialEq)]-enum Simple {- Universal,- Tag(String),- Id(String),- Class(String),- Attr(String, AttrOp, String),- Pseudo(String),- NthChild(i32, i32, bool), // an+b, from the end- Not(Vec<Simple>),-}--#[derive(Clone, Copy, Debug, PartialEq)]-enum Combinator {- Descendant,- Child,- Adjacent,- Sibling,-}--/// Where a rule is filed in a stylesheet's index.-enum Bucket {- Id(String),- Class(String),- Tag(String),- Universal,-}--/// A complex selector: compounds joined by combinators (stored right to left).-#[derive(Clone, Debug, PartialEq)]-pub struct Selector {- parts: Vec<(Vec<Simple>, Option<Combinator>)>,- pub specificity: (u16, u16, u16),-}--/// What a selector can ask about an element.-pub trait Subject: Sized {- fn tag(&self) -> &str;- fn id(&self) -> Option<&str>;- fn has_class(&self, class: &str) -> bool;- fn attr(&self, name: &str) -> Option<&str>;- fn state(&self, pseudo: &str) -> bool;- fn parent(&self) -> Option<Self>;- fn prev_sibling(&self) -> Option<Self>;- /// 1-based position among element siblings, and their count.- fn position(&self) -> (usize, usize);- fn is_empty(&self) -> bool;- /// The `class` attribute (used to find candidate rules quickly).- fn class_attr(&self) -> Option<&str> {- self.attr("class")- }-}--impl Selector {- /// Parse one complex selector; None for unsupported syntax- /// (pseudo-elements), so the rule is skipped as browsers do.- pub fn parse(s: &str) -> Option<Selector> {- let s = s.trim();- if s.is_empty() || s.contains("::") {- return None;- }- let mut parts: Vec<(Vec<Simple>, Option<Combinator>)> = Vec::new();- let mut pending: Option<Combinator> = None;- let mut i = 0;- let b = s.as_bytes();- while i < b.len() {- let c = b[i] as char;- if c.is_whitespace() {- i += 1;- if pending.is_none() && !parts.is_empty() {- pending = Some(Combinator::Descendant);- }- continue;- }- if matches!(c, '>' | '+' | '~') {- pending = Some(match c {- '>' => Combinator::Child,- '+' => Combinator::Adjacent,- _ => Combinator::Sibling,- });- i += 1;- continue;- }- let (compound, next) = parse_compound(s, i)?;- if let Some(last) = parts.last_mut() {- last.1 = Some(pending.unwrap_or(Combinator::Descendant));- }- parts.push((compound, None));- pending = None;- i = next;- }- if parts.is_empty() {- return None;- }- parts.reverse(); // match from the subject outwards- let mut spec = (0u16, 0u16, 0u16);- for (compound, _) in &parts {- add_specificity(compound, &mut spec);- }- // the combinator stored with a compound links it to the *previous* one (leftwards)- let n = parts.len();- let combs: Vec<Option<Combinator>> = parts.iter().map(|p| p.1).collect();- for k in 0..n {- parts[k].1 = if k + 1 < n { combs[k + 1] } else { None };- }- Some(Selector { parts, specificity: spec })- }-- /// The bucket a rule is filed under: its subject's id, class, tag, or "*".- fn bucket(&self) -> Bucket {- let subject = &self.parts[0].0;- subject.iter().find_map(|s| match s {- Simple::Id(i) => Some(Bucket::Id(i.clone())),- _ => None,- }).or_else(|| subject.iter().find_map(|s| match s {- Simple::Class(c) => Some(Bucket::Class(c.clone())),- _ => None,- })).or_else(|| subject.iter().find_map(|s| match s {- Simple::Tag(t) => Some(Bucket::Tag(t.to_ascii_lowercase())),- _ => None,- })).unwrap_or(Bucket::Universal)- }-- pub fn matches<S: Subject + Clone>(&self, el: &S) -> bool {- match_from(&self.parts, 0, el)- }-}--fn add_specificity(compound: &[Simple], spec: &mut (u16, u16, u16)) {- for s in compound {- match s {- Simple::Id(_) => spec.0 += 1,- Simple::Class(_) | Simple::Attr(..) | Simple::Pseudo(_) | Simple::NthChild(..) => {- spec.1 += 1- }- Simple::Tag(_) => spec.2 += 1,- Simple::Not(inner) => add_specificity(inner, spec),- Simple::Universal => {}- }- }-}--fn match_from<S: Subject + Clone>(parts: &[(Vec<Simple>, Option<Combinator>)], k: usize, el: &S)- -> bool {- let (compound, comb) = &parts[k];- if !compound.iter().all(|s| match_simple(s, el)) {- return false;- }- let Some(comb) = comb else { return true };- match comb {- Combinator::Child => el.parent().is_some_and(|p| match_from(parts, k + 1, &p)),- Combinator::Descendant => {- let mut cur = el.parent();- while let Some(p) = cur {- if match_from(parts, k + 1, &p) {- return true;- }- cur = p.parent();- }- false- }- Combinator::Adjacent => el.prev_sibling().is_some_and(|p| match_from(parts, k + 1, &p)),- Combinator::Sibling => {- let mut cur = el.prev_sibling();- while let Some(p) = cur {- if match_from(parts, k + 1, &p) {- return true;- }- cur = p.prev_sibling();- }- false- }- }-}--fn match_simple<S: Subject + Clone>(s: &Simple, el: &S) -> bool {- match s {- Simple::Universal => true,- Simple::Tag(t) => el.tag().eq_ignore_ascii_case(t),- Simple::Id(id) => el.id() == Some(id.as_str()),- Simple::Class(c) => el.has_class(c),- Simple::Attr(name, op, val) => match (el.attr(name), op) {- (None, _) => false,- (Some(_), AttrOp::Exists) => true,- (Some(v), AttrOp::Eq) => v == val,- (Some(v), AttrOp::Word) => v.split_whitespace().any(|w| w == val),- (Some(v), AttrOp::Prefix) => v.starts_with(val.as_str()),- (Some(v), AttrOp::Suffix) => v.ends_with(val.as_str()),- (Some(v), AttrOp::Contains) => v.contains(val.as_str()),- (Some(v), AttrOp::Dash) => v == val || v.starts_with(&format!("{val}-")),- },- Simple::Pseudo(p) => match p.as_str() {- "first-child" => el.position().0 == 1,- "last-child" => {- let (i, n) = el.position();- i == n- }- "only-child" => el.position().1 == 1,- "root" => el.parent().is_none(),- "empty" => el.is_empty(),- "first-of-type" | "last-of-type" => {- // approximated with element position- let (i, n) = el.position();- if p == "first-of-type" { i == 1 } else { i == n }- }- other => el.state(other),- },- Simple::NthChild(a, b, from_end) => {- let (i, n) = el.position();- let pos = if *from_end { (n + 1 - i) as i32 } else { i as i32 };- if *a == 0 {- pos == *b- } else {- (pos - b) % a == 0 && (pos - b) / a >= 0- }- }- Simple::Not(inner) => !inner.iter().all(|s| match_simple(s, el)),- }-}--fn parse_compound(s: &str, mut i: usize) -> Option<(Vec<Simple>, usize)> {- let b = s.as_bytes();- let mut out = Vec::new();- while i < b.len() {- let c = b[i] as char;- match c {- '*' => {- out.push(Simple::Universal);- i += 1;- }- '#' | '.' => {- let end = scan_name(s, i + 1);- let name = s[i + 1..end].to_string();- out.push(if c == '#' { Simple::Id(name) } else { Simple::Class(name) });- i = end;- }- '[' => {- let close = s[i..].find(']')? + i;- out.push(parse_attr(&s[i + 1..close])?);- i = close + 1;- }- ':' => {- let end = scan_name(s, i + 1);- let name = s[i + 1..end].to_ascii_lowercase();- if b.get(end) == Some(&b'(') {- let close = matching_paren(s, end);- let arg = s[end + 1..close].trim();- out.push(match name.as_str() {- "not" => Simple::Not(parse_compound(arg, 0)?.0),- "nth-child" | "nth-last-child" | "nth-of-type" | "nth-last-of-type" => {- let (a, bb) = parse_nth(arg)?;- Simple::NthChild(a, bb, name.contains("last"))- }- "is" | "where" => {- // first alternative only (simple and common)- let first = split_top(arg, ',')[0];- Simple::Not(vec![Simple::Not(parse_compound(first.trim(), 0)?.0)])- }- _ => return None,- });- i = close + 1;- } else {- out.push(Simple::Pseudo(name));- i = end;- }- }- c if is_name_start(c) => {- let end = scan_name(s, i);- out.push(Simple::Tag(s[i..end].to_ascii_lowercase()));- i = end;- }- _ => break,- }- }- (!out.is_empty()).then_some((out, i))-}--fn parse_attr(inner: &str) -> Option<Simple> {- for (op, kind) in [("~=", AttrOp::Word), ("^=", AttrOp::Prefix), ("$=", AttrOp::Suffix),- ("*=", AttrOp::Contains), ("|=", AttrOp::Dash), ("=", AttrOp::Eq)] {- if let Some((name, val)) = inner.split_once(op) {- let val = val.trim().trim_matches(['"', '\'']).to_string();- return Some(Simple::Attr(name.trim().to_ascii_lowercase(), kind, val));- }- }- Some(Simple::Attr(inner.trim().to_ascii_lowercase(), AttrOp::Exists, String::new()))-}--fn parse_nth(arg: &str) -> Option<(i32, i32)> {- let a = arg.replace(' ', "").to_ascii_lowercase();- match a.as_str() {- "odd" => return Some((2, 1)),- "even" => return Some((2, 0)),- _ => {}- }- if let Some((x, y)) = a.split_once('n') {- let x = match x {- "" | "+" => 1,- "-" => -1,- v => v.parse().ok()?,- };- let y = if y.is_empty() { 0 } else { y.parse().ok()? };- Some((x, y))- } else {- Some((0, a.parse().ok()?))- }-}--// ==========================================================================-// Stylesheets--/// One rule: a selector with its declarations, in source order.-#[derive(Clone, Debug)]-pub struct Rule {- pub selector: Selector,- pub decls: Vec<Decl>,- pub order: usize,- media: Option<Media>,-}--#[derive(Clone, Debug, PartialEq)]-struct Media {- min_width: Option<f32>,- max_width: Option<f32>,- min_height: Option<f32>,- max_height: Option<f32>,- dark: Option<bool>,-}--impl Media {- fn parse(q: &str) -> Media {- let mut m = Media { min_width: None, max_width: None, min_height: None, max_height: None,- dark: None };- for part in q.split("and") {- let part = part.trim().trim_matches(['(', ')']).trim();- if let Some((k, v)) = part.split_once(':') {- let v = v.trim();- let px = v.trim_end_matches("px").parse::<f32>().ok();- match k.trim() {- "min-width" => m.min_width = px,- "max-width" => m.max_width = px,- "min-height" => m.min_height = px,- "max-height" => m.max_height = px,- "prefers-color-scheme" => m.dark = Some(v == "dark"),- _ => {}- }- }- }- m- }-- fn applies(&self, viewport: (f32, f32)) -> bool {- self.min_width.is_none_or(|w| viewport.0 >= w)- && self.max_width.is_none_or(|w| viewport.0 <= w)- && self.min_height.is_none_or(|h| viewport.1 >= h)- && self.max_height.is_none_or(|h| viewport.1 <= h)- && self.dark.is_none_or(|d| d) // Blender's theme is dark- }-}--/// A parsed stylesheet.-#[derive(Clone, Debug, Default)]-pub struct Stylesheet {- pub rules: Vec<Rule>,- /// Rule indices by the subject's id / class / tag, or universal (rebuilt- /// when `rules` changes length). Looked up by `&str`: no key building.- by_id: std::collections::HashMap<String, Vec<usize>>,- by_class: std::collections::HashMap<String, Vec<usize>>,- by_tag: std::collections::HashMap<String, Vec<usize>>,- universal: Vec<usize>,- indexed: usize,-}--/// Rules matching one element: on the stack for the usual handful.-pub(crate) type Matches<'a> = smallvec::SmallVec<[&'a Rule; 8]>;--impl Stylesheet {- /// Parse CSS text (rules, `@media` blocks; other at-rules are skipped).- pub fn parse(css: &str) -> Stylesheet {- let mut sheet = Stylesheet::default();- sheet.parse_into(&strip_comments(css), None);- sheet.reindex();- sheet- }-- fn reindex(&mut self) {- self.by_id.clear();- self.by_class.clear();- self.by_tag.clear();- self.universal.clear();- for (k, r) in self.rules.iter().enumerate() {- match r.selector.bucket() {- Bucket::Id(s) => self.by_id.entry(s).or_default().push(k),- Bucket::Class(s) => self.by_class.entry(s).or_default().push(k),- Bucket::Tag(s) => self.by_tag.entry(s).or_default().push(k),- Bucket::Universal => self.universal.push(k),- }- }- self.indexed = self.rules.len();- }-- fn parse_into(&mut self, css: &str, media: Option<Media>) {- let mut rest = css;- while let Some(open) = rest.find('{') {- let prelude = rest[..open].trim();- let close = block_end(rest, open);- let body = &rest[open + 1..close.min(rest.len())];- if let Some(q) = prelude.strip_prefix("@media") {- self.parse_into(body, Some(Media::parse(q)));- } else if !prelude.starts_with('@') {- let decls = parse_declarations(body);- for sel in split_top(prelude, ',') {- if let Some(selector) = Selector::parse(sel) {- let order = self.rules.len();- self.rules.push(Rule { selector, decls: decls.clone(), order,- media: media.clone() });- }- }- }- rest = &rest[(close + 1).min(rest.len())..];- }- }-- /// Declarations of every matching rule, in cascade order.- pub fn matching<'a, S: Subject + Clone>(&'a self, el: &S, viewport: (f32, f32))- -> Vec<&'a Rule> {- self.matches(el, viewport).into_vec()- }-- /// [`Self::matching`] without heap allocation for the usual few rules.- pub(crate) fn matches<'a, S: Subject + Clone>(&'a self, el: &S, viewport: (f32, f32)) -> Matches<'a> {- let ok = |r: &&Rule| r.media.as_ref().is_none_or(|m| m.applies(viewport)) && r.selector.matches(el);- let mut hits: Matches<'a> = if self.indexed != self.rules.len() {- self.rules.iter().filter(ok).collect() // `rules` edited by hand: scan all- } else {- let mut cand: smallvec::SmallVec<[usize; 16]> = smallvec::SmallVec::new();- cand.extend_from_slice(&self.universal);- let tag = el.tag();- let found = if tag.bytes().any(|b| b.is_ascii_uppercase()) {- self.by_tag.get(&tag.to_ascii_lowercase())- } else {- self.by_tag.get(tag)- };- if let Some(v) = found {- cand.extend_from_slice(v);- }- if let Some(v) = el.id().and_then(|id| self.by_id.get(id)) {- cand.extend_from_slice(v);- }- if let Some(classes) = el.class_attr() {- for c in classes.split_whitespace() {- if let Some(v) = self.by_class.get(c) {- cand.extend_from_slice(v);- }- }- }- cand.sort_unstable();- cand.dedup();- cand.into_iter().map(|k| &self.rules[k]).filter(ok).collect()- };- hits.sort_by_key(|r| (r.selector.specificity, r.order));- hits- }-}--fn block_end(s: &str, open: usize) -> usize {- let mut depth = 0;- for (k, c) in s[open..].char_indices() {- match c {- '{' => depth += 1,- '}' => {- depth -= 1;- if depth == 0 {- return open + k;- }- }- _ => {}- }- }- s.len()-}+pub use crate::selector::{+ has_match, Combinator, ContainerQuery, HasEntry, FontFace, Keyframes, MediaEnv, MediaQuery, PropertyRule,+ PseudoElement, RelSelector, Rule, Selector, Stylesheet, Subject,+};+pub(crate) use crate::selector::Matches;#[cfg(test)]mod tests {@@ -922,7 +476,7 @@ mod tests {fn selector_specificity() {let s = Selector::parse("ul > li.item:hover a#x").unwrap();assert_eq!(s.specificity, (1, 2, 3));- assert!(Selector::parse("p::before").is_none());+ assert_eq!(Selector::parse("p::before").unwrap().pseudo, Some(PseudoElement::Before));let sheet = Stylesheet::parse("@media (max-width: 100px) { p { color: red } } a { b: c }");assert_eq!(sheet.rules.len(), 2);}diff --git a/bindings/rust/blenderui/src/geometry.rs b/bindings/rust/blenderui/src/geometry.rsindex 7e40a29..802d7a1 100644--- a/bindings/rust/blenderui/src/geometry.rs+++ b/bindings/rust/blenderui/src/geometry.rs@@ -32,6 +32,10 @@ pub enum Length {Percent(f32),Vw(f32),Vh(f32),+ Vmin(f32),+ Vmax(f32),+ /// Any CSS math (`calc()`, `min()`, `clamp()` ...), interned.+ Calc(&'static crate::calc::Calc),#[default]Auto,}@@ -70,6 +74,9 @@ impl Length {Length::Em(v) => Some(v * u.font_size),Length::Vw(v) => Some(v * u.viewport.0 / 100.0),Length::Vh(v) => Some(v * u.viewport.1 / 100.0),+ Length::Vmin(v) => Some(v * u.viewport.0.min(u.viewport.1) / 100.0),+ Length::Vmax(v) => Some(v * u.viewport.0.max(u.viewport.1) / 100.0),+ Length::Calc(c) => c.to_px(u),Length::Percent(_) | Length::Auto => None,}}@@ -78,6 +85,7 @@ impl Length {pub(crate) fn resolve(self, u: &Units, basis: f32) -> f32 {match self {Length::Percent(p) => p * basis / 100.0,+ Length::Calc(c) => c.eval_units(u, basis),Length::Auto => 0.0,other => other.to_px(u).unwrap_or(0.0),}diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rsindex 0f838ac..d83d29b 100644--- a/bindings/rust/blenderui/src/layout.rs+++ b/bindings/rust/blenderui/src/layout.rs@@ -25,6 +25,7 @@ use crate::geometry::{rect, Bounds, Units};use crate::html::{tag_kind, ua_stylesheet, TagKind};use crate::paint::{Image, ImageCache};use crate::prof::{span, Phase};+use crate::style::ContentPart;use crate::style::{apply, Computed, DisplayKind, Fnv, FnvMap, TextAlign, TextTransform, VAlign, WhiteSpace};use crate::text::{self, TextCache};use crate::widgets::WidgetSpec;@@ -98,11 +99,13 @@ struct StyleKey {pub(crate) struct StyleStore {styles: Vec<Computed>,cache: FnvMap<u64, Vec<(StyleKey, StyleId)>>,+ /// Custom property maps the styles point into (`Computed::vars`).+ vars: crate::vars::Vars,}impl Default for StyleStore {fn default() -> Self {- StyleStore { styles: vec![Computed::default()], cache: Default::default() }+ StyleStore { styles: vec![Computed::default()], cache: Default::default(), vars: Default::default() }}}@@ -120,6 +123,7 @@ impl StyleStore {if self.styles.len() > 20_000 {self.styles.truncate(1);self.cache.clear();+ self.vars.clear();}}@@ -130,6 +134,55 @@ impl StyleStore {}/// The author stylesheet (all `<style>` elements), reparsed only when its text changes.+/// Tailwind classes seen so far, compiled to CSS (like Tailwind's JIT):+/// each distinct `class` attribute is scanned once.+#[derive(Default)]+pub(crate) struct TwJit {+ on: bool,+ seen: FnvMap<u64, ()>,+ known: FnvMap<String, ()>,+ rules: Vec<((u32, u32), usize, String)>,+ css: String,+ dirty: bool,+}++/// Whether class names compile as Tailwind utilities (on by default).+pub(crate) static TAILWIND: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);++impl TwJit {+ fn scan(&mut self, classes: &str) {+ let h = fnv(&[classes.as_bytes()]);+ if self.seen.insert(h, ()).is_some() {+ return;+ }+ for c in classes.split_whitespace() {+ if self.known.contains_key(c) {+ continue;+ }+ self.known.insert(c.to_string(), ());+ if let Some(r) = crate::tailwind::compile(c) {+ let n = self.rules.len();+ self.rules.push((r.sort, n, r.css));+ self.dirty = true;+ }+ }+ }++ /// The utilities, in Tailwind's order.+ fn css(&mut self) -> &str {+ if self.dirty {+ self.rules.sort_by_key(|r| (r.0, r.1));+ self.css.clear();+ for r in &self.rules {+ self.css.push_str(&r.2);+ self.css.push('\n');+ }+ self.dirty = false;+ }+ &self.css+ }+}+#[derive(Default)]pub(crate) struct AuthorSheet {hash: u64,@@ -166,6 +219,8 @@ pub(crate) struct ElData {pub id: Option<SharedString>,pub attrs: Vec<(SharedString, SharedString)>,pub listeners: Option<Box<Listeners>>,+ /// Which of the author sheet's `:has()` hold here (bit = index).+ pub has: u64,}const NONE: u32 = u32::MAX;@@ -191,6 +246,8 @@ pub(crate) struct BoxNode {fp: u64,pub taffy: Option<NodeId>,pub pos: (usize, usize),+ /// Position among siblings of the same tag, and their count.+ pub tpos: (u32, u32),pub marker: Option<String>,// filled after layoutpub bounds: Bounds<f32>,@@ -240,7 +297,7 @@ pub(crate) struct LayoutCaches {pub text: TextCache,pub images: ImageCache,pub author: AuthorSheet,- pub taffy: TaffyTree<Measure>,+ pub(crate) taffy: crate::tree::LayoutTree<Measure>,/// Box index of each taffy node (by slot), rebuilt in place each frame.box_of: Vec<u32>,/// Scratch for `finish`.@@ -251,6 +308,7 @@ pub(crate) struct LayoutCaches {recon: Recon,/// Measured text leaves: key -> box index, this frame.text_box: FnvMap<Key, usize>,+ tw: TwJit,}/// Rule indices (`Rule::order`) in the UA and author sheets.@@ -269,12 +327,13 @@ impl Default for LayoutCaches {text: TextCache::default(),images: ImageCache::default(),author: AuthorSheet::default(),- taffy: TaffyTree::new(),+ taffy: Default::default(),box_of: Vec::new(),acc: Vec::new(),matched: MatchCache::default(),recon: Recon::default(),text_box: FnvMap::default(),+ tw: TwJit::default(),}}}@@ -282,7 +341,7 @@ impl Default for LayoutCaches {struct Builder<'a> {nodes: Vec<BoxNode>,els: Vec<ElData>,- taffy: &'a mut TaffyTree<Measure>,+ taffy: &'a mut crate::tree::LayoutTree<Measure>,styles: &'a mut StyleStore,text: &'a mut TextCache,images: &'a mut ImageCache,@@ -291,8 +350,13 @@ struct Builder<'a> {text_box: &'a mut FnvMap<Key, usize>,/// Set when a node changed while building the current subtree.changed: bool,+ /// `tpos` for the element about to be built.+ next_tpos: (u32, u32),author: &'a Stylesheet,author_hash: u64,+ /// Media query results of the UA and author sheets this frame.+ ua_media: Vec<bool>,+ au_media: Vec<bool>,state: &'a UiState,viewport: (f32, f32),title: Option<String>,@@ -303,9 +367,9 @@ struct Builder<'a> {type Kids = smallvec::SmallVec<[usize; 8]>;type NodeList = smallvec::SmallVec<[NodeId; 8]>;-/// The slot index of a taffy node (dense from 0 after `TaffyTree::clear`).+/// The slot index of a layout node (dense: the tree reuses freed slots).fn slot(id: NodeId) -> usize {- (u64::from(id) & 0xffff_ffff) as usize+ u64::from(id) as usize}/// Children of box `i` in the arena `nodes`.@@ -346,6 +410,11 @@ impl NodeRef<'_> {fn own_attr(&self, name: &str) -> Option<&str> {el_attr(self.nodes, self.els, self.i, name)}+ /// A `::before` / `::after` box (invisible to sibling selectors).+ fn is_generated(&self, k: usize) -> bool {+ let e = self.nodes[k].el;+ e != NONE && self.els[e as usize].tag.starts_with("::")+ }}impl Subject for NodeRef<'_> {@@ -394,7 +463,7 @@ impl Subject for NodeRef<'_> {fn prev_sibling(&self) -> Option<Self> {let mut k = self.nodes[self.i].prev;while k != NONE {- if self.nodes[k as usize].el != NONE {+ if self.nodes[k as usize].el != NONE && !self.is_generated(k as usize) {return Some(NodeRef { i: k as usize, ..self.clone() });}k = self.nodes[k as usize].prev;@@ -404,15 +473,169 @@ impl Subject for NodeRef<'_> {fn position(&self) -> (usize, usize) {self.nodes[self.i].pos}+ fn type_position(&self) -> (usize, usize) {+ let t = self.nodes[self.i].tpos;+ (t.0 as usize, t.1 as usize)+ }fn is_empty(&self) -> bool {self.nodes[self.i].first == NONE}+ fn has(&self, id: u16) -> bool {+ id < 64 && self.el().is_some_and(|e| e.has & (1 << id) != 0)+ }+ fn same(&self, o: &Self) -> bool {+ self.i == o.i+ }+ fn next_sibling(&self) -> Option<Self> {+ let mut k = self.nodes[self.i].next;+ while k != NONE {+ if self.nodes[k as usize].el != NONE && !self.is_generated(k as usize) {+ return Some(NodeRef { i: k as usize, ..self.clone() });+ }+ k = self.nodes[k as usize].next;+ }+ None+ }+ fn first_child(&self) -> Option<Self> {+ let k = self.nodes[self.i].first;+ if k == NONE {+ return None;+ }+ let c = NodeRef { i: k as usize, ..self.clone() };+ if self.nodes[k as usize].el != NONE && !self.is_generated(k as usize) { Some(c) } else { c.next_sibling() }+ }+}++/// An element of a not-yet-built subtree (for `:has()`): its tag, id,+/// attributes and tree links, flattened from the declarative children.+struct Flat<'d> {+ tag: &'static str,+ id: Option<&'d str>,+ attrs: &'d [(SharedString, SharedString)],+ parent: u32,+ first: u32,+ next: u32,+ prev: u32,+ pos: (usize, usize),+ tpos: (usize, usize),+ key: Key,+}++/// (same-tag siblings before `k`, same-tag siblings in all) for `:has()`+/// subtrees (small: linear scans are fine there).+fn type_counts(els: &[&Div], k: usize) -> (usize, usize) {+ let tag = els[k].tag;+ let before = els[..k].iter().filter(|e| e.tag == tag).count();+ (before, before + els[k..].iter().filter(|e| e.tag == tag).count())+}++/// Flatten `div`'s element subtree (index 0 = `div` itself, the anchor).+fn flatten<'d>(div: &'d Div, key: Key, out: &mut Vec<Flat<'d>>) {+ out.push(Flat { tag: div.tag, id: None, attrs: &[], parent: NONE, first: NONE, next: NONE, prev: NONE,+ pos: (1, 1), tpos: (1, 1), key });+ fn kids<'d>(div: &'d Div, me: u32, key: Key, out: &mut Vec<Flat<'d>>) {+ let els: smallvec::SmallVec<[&'d Div; 16]> = div.children.iter().filter_map(|c| match c {+ AnyElement::Element(d) => Some(d),+ _ => None,+ }).collect();+ let mut prev = NONE;+ for (k, d) in els.iter().enumerate() {+ let ck = match &d.id {+ Some(id) => id_key(id),+ None => child_key(key, d.tag, k + 1),+ };+ let (before, total) = type_counts(&els, k);+ let idx = out.len() as u32;+ out.push(Flat { tag: d.tag, id: d.id.as_deref(), attrs: &d.attrs, parent: me, first: NONE, next: NONE,+ prev, pos: (k + 1, els.len()), tpos: (before + 1, total), key: ck });+ if prev == NONE {+ out[me as usize].first = idx;+ } else {+ out[prev as usize].next = idx;+ }+ prev = idx;+ kids(d, idx, ck, out);+ }+ }+ kids(div, 0, key, out);+}++#[derive(Clone)]+struct DivSubject<'f, 'd> {+ flat: &'f [Flat<'d>],+ state: &'f UiState,+ i: usize,+}++impl DivSubject<'_, '_> {+ fn at(&self, k: u32) -> Option<Self> {+ (k != NONE).then(|| DivSubject { i: k as usize, ..self.clone() })+ }+}++impl Subject for DivSubject<'_, '_> {+ fn tag(&self) -> &str {+ self.flat[self.i].tag+ }+ fn id(&self) -> Option<&str> {+ self.flat[self.i].id+ }+ fn has_class(&self, class: &str) -> bool {+ self.attr("class").is_some_and(|c| c.split_whitespace().any(|w| w == class))+ }+ fn attr(&self, name: &str) -> Option<&str> {+ self.flat[self.i].attrs.iter().find(|(k, _)| k.as_ref() == name).map(|(_, v)| v.as_ref())+ }+ fn state(&self, pseudo: &str) -> bool {+ let key = self.flat[self.i].key;+ match pseudo {+ "hover" => self.state.hovered.contains(&key),+ "active" => self.state.active.contains(&key),+ "focus" | "focus-visible" => self.state.focused == Some(key),+ "focus-within" => self.state.focus_path.contains(&key),+ "checked" => self.state.checked.get(&key).copied().unwrap_or(self.attr("checked").is_some()),+ "disabled" => self.attr("disabled").is_some(),+ "enabled" => self.attr("disabled").is_none(),+ "required" => self.attr("required").is_some(),+ "link" | "any-link" => self.tag() == "a" && self.attr("href").is_some(),+ _ => false,+ }+ }+ fn parent(&self) -> Option<Self> {+ self.at(self.flat[self.i].parent)+ }+ fn prev_sibling(&self) -> Option<Self> {+ self.at(self.flat[self.i].prev)+ }+ fn next_sibling(&self) -> Option<Self> {+ self.at(self.flat[self.i].next)+ }+ fn first_child(&self) -> Option<Self> {+ self.at(self.flat[self.i].first)+ }+ fn position(&self) -> (usize, usize) {+ self.flat[self.i].pos+ }+ fn type_position(&self) -> (usize, usize) {+ self.flat[self.i].tpos+ }+ fn is_empty(&self) -> bool {+ self.flat[self.i].first == NONE+ }+ fn same(&self, o: &Self) -> bool {+ self.i == o.i+ }}// -- building --------------------------------------------------------------------------------fn collect_styles(el: &AnyElement, css: &mut String, title: &mut Option<String>) {+fn collect_styles(el: &AnyElement, css: &mut String, title: &mut Option<String>, jit: &mut TwJit) {if let AnyElement::Element(d) = el {+ if jit.on {+ if let Some((_, classes)) = d.attrs.iter().find(|(k, _)| k.as_ref() == "class") {+ jit.scan(classes);+ }+ }let text = || d.children.iter().filter_map(|c| match c {AnyElement::Text(t) => Some(t.as_ref()),_ => None,@@ -423,7 +646,7 @@ fn collect_styles(el: &AnyElement, css: &mut String, title: &mut Option<String>)_ => {}}for c in &d.children {- collect_styles(c, css, title);+ collect_styles(c, css, title, jit);}}}@@ -515,8 +738,8 @@ impl<'a> Builder<'a> {a.iter().map(|&k| &author.rules[k as usize]).collect());}let subj = self.subject(i);- let ua = ua_sheet.matches(&subj, self.viewport);- let au = author.matches(&subj, self.viewport);+ let ua = ua_sheet.matches(&subj, &self.ua_media, None);+ let au = author.matches(&subj, &self.au_media, None);self.matched.map.insert(memo, (ua.iter().map(|r| r.order as u32).collect(),au.iter().map(|r| r.order as u32).collect()));(ua, au)@@ -534,7 +757,9 @@ impl<'a> Builder<'a> {}(if k == NONE { 0 } else { self.nodes[k as usize].fp }).hash(&mut h);n.pos.hash(&mut h);+ n.tpos.hash(&mut h);if let Some(e) = (n.el != NONE).then(|| &self.els[n.el as usize]) {+ e.has.hash(&mut h);e.tag.hash(&mut h);e.id.as_deref().hash(&mut h);for (a, v) in &e.attrs {@@ -572,22 +797,65 @@ impl<'a> Builder<'a> {decls}- fn compute(&self, parent: StyleId, decls: &[&Decl]) -> Computed {+ fn compute(&mut self, parent: StyleId, decls: &[&Decl]) -> Computed {+ // custom properties first: other declarations may reference them+ let pvars = self.styles[parent].vars;+ let vars = if decls.iter().any(|d| d.prop.is_custom()) {+ let mut map: Vec<(Prop, Box<[crate::css::Tok]>)> = self.styles.vars.get(pvars).to_vec();+ for important in [false, true] {+ for d in decls.iter().filter(|d| d.important == important && d.prop.is_custom()) {+ let v: Box<[crate::css::Tok]> = if crate::vars::uses_vars(&d.value) {+ match crate::vars::substitute(&d.value, &map) {+ Some(v) => v.into_boxed_slice(),+ None => Box::new([]), // guaranteed-invalid: falls back+ }+ } else {+ d.value.to_vec().into_boxed_slice()+ };+ match map.binary_search_by_key(&d.prop, |e| e.0) {+ Ok(i) => map[i].1 = v,+ Err(i) => map.insert(i, (d.prop, v)),+ }+ }+ }+ self.styles.vars.add(map.into_boxed_slice())+ } else {+ pvars+ };let parent = &self.styles[parent];let mut c = Computed::inherit(parent);+ c.vars = vars;+ let map = self.styles.vars.get(vars);+ let subst = |d: &Decl| -> Option<Decl> {+ crate::vars::substitute(&d.value, map).map(|v| Decl {+ prop: d.prop,+ value: crate::css::Value::Owned(v.into_boxed_slice()),+ important: d.important,+ })+ };const FONT_SIZE: Prop = Prop::named("font-size");const FONT: Prop = Prop::named("font");let font_first = |d: &&Decl| d.prop == FONT_SIZE || d.prop == FONT;+ let units = |fs: f32| Units { font_size: fs, viewport: self.viewport };+ let run = |c: &mut Computed, u: Units, d: &Decl| {+ if crate::vars::uses_vars(&d.value) {+ if let Some(d) = subst(d) {+ apply(c, parent, u, &d);+ }+ } else {+ apply(c, parent, u, d);+ }+ };for important in [false, true] {// font-size first: em lengths in the other properties depend on itfor d in decls.iter().filter(|d| d.important == important && font_first(d)) {- apply(&mut c, parent, self.units(parent.font_size), d);+ run(&mut c, units(parent.font_size), d);}}- let u = self.units(c.font_size);+ let u = units(c.font_size);for important in [false, true] {for d in decls.iter().filter(|d| d.important == important && !font_first(d)) {- apply(&mut c, parent, u, d);+ run(&mut c, u, d);}}c@@ -620,6 +888,7 @@ impl<'a> Builder<'a> {fp: 0,taffy: None,pos: (1, 1),+ tpos: (1, 1),marker: None,bounds: rect(0.0, 0.0, 0.0, 0.0),clip: None,@@ -665,13 +934,36 @@ impl<'a> Builder<'a> {let parent_style = parent.map(|p| self.nodes[p].style).unwrap_or(ROOT_STYLE);let i = self.push(parent, Content::Element, None, parent_style, key, true);self.nodes[i].pos = pos;+ self.nodes[i].tpos = std::mem::replace(&mut self.next_tpos, (1, 1));self.nodes[i].el = self.els.len() as u32;self.els.push(ElData {tag: div.tag,id: div.id.take(),attrs: std::mem::take(&mut div.attrs),listeners: std::mem::take(&mut div.listeners),+ has: 0,});+ if !self.author.has.is_empty() {+ // :has() looks at the element's subtree, which isn't built yet:+ // evaluate it on the declarative children instead+ let mut bits = 0u64;+ let mut flat = Vec::new();+ for (id, entry) in self.author.has.iter().enumerate().take(64) {+ if !entry.host_matches(&self.subject(i)) {+ continue;+ }+ if flat.is_empty() {+ flatten(&div, key, &mut flat);+ }+ let anchor = DivSubject { flat: &flat, state: self.state, i: 0 };+ if crate::css::has_match(&entry.rels, &anchor) {+ bits |= 1 << id;+ }+ }+ if let Some(e) = self.els.last_mut() {+ e.has = bits;+ }+ }self.nodes[i].fp = self.fingerprint(i);let kind = tag_kind(div.tag);// widgets and replaced elements are atomic inlines; flex/grid items are blockified@@ -731,12 +1023,88 @@ impl<'a> Builder<'a> {children.insert(0, AnyElement::Text(open.into()));children.push(AnyElement::Text(close.into()));}+ let pseudo = self.author.uses_pseudo() || ua_stylesheet().uses_pseudo();+ if pseudo {+ self.generated(i, crate::css::PseudoElement::Before);+ }self.children(i, children);+ if pseudo {+ self.generated(i, crate::css::PseudoElement::After);+ }}}Some(i)}+ /// The `::before` / `::after` box of element `i`, when a rule gives it content.+ fn generated(&mut self, i: usize, pe: crate::css::PseudoElement) {+ let ua_sheet = ua_stylesheet();+ let author: &'a Stylesheet = self.author;+ let (ua, au) = {+ let subj = self.subject(i);+ (ua_sheet.matches(&subj, &self.ua_media, Some(pe)), author.matches(&subj, &self.au_media, Some(pe)))+ };+ if ua.is_empty() && au.is_empty() {+ return;+ }+ let parent = self.nodes[i].style;+ let tag = if pe == crate::css::PseudoElement::Before { "::before" } else { "::after" };+ // shared like element styles: same parent + same rules = same style+ let hash = {+ let mut h = Fnv::default();+ (parent, tag, self.author_hash).hash(&mut h);+ for r in ua.iter().chain(au.iter()) {+ (*r as *const Rule as usize).hash(&mut h);+ }+ h.finish()+ };+ let rule_ids: Vec<usize> = ua.iter().chain(au.iter()).map(|r| *r as *const Rule as usize).collect();+ let fixup = if pe == crate::css::PseudoElement::Before { 3 } else { 4 };+ let viewport = (self.viewport.0.to_bits(), self.viewport.1.to_bits());+ let found = self.styles.cache.get(&hash).and_then(|b| b.iter().find(|(k, _)| {+ k.parent == parent && k.fixup == fixup && k.viewport == viewport && k.author == self.author_hash+ && k.rules == rule_ids+ })).map(|(_, id)| *id);+ let sid = match found {+ Some(id) => id,+ None => {+ let decls: smallvec::SmallVec<[&Decl; 24]> =+ ua.iter().chain(au.iter()).flat_map(|r| r.decls.iter()).collect();+ let mut c = self.compute(parent, &decls);+ if matches!(self.st(i).display, DisplayKind::Flex | DisplayKind::InlineFlex+ | DisplayKind::Grid | DisplayKind::InlineGrid) && c.display == DisplayKind::Inline {+ c.display = DisplayKind::Block; // flex / grid items are blockified+ }+ let id = self.styles.add(c);+ let key = StyleKey { parent, viewport, author: self.author_hash, rules: rule_ids, decls: Vec::new(), fixup };+ self.styles.cache.entry(hash).or_default().push((key, id));+ id+ }+ };+ let st = &self.styles[sid];+ let Some(parts) = st.content.as_ref() else { return };+ if st.display == DisplayKind::None {+ return;+ }+ let quotes = st.quotes.clone().unwrap_or_else(|| ("\u{201c}".into(), "\u{201d}".into()));+ let mut text = String::new();+ for p in parts.iter() {+ match p {+ ContentPart::Text(t) => text.push_str(t),+ ContentPart::Attr(n) => text.push_str(self.attr(i, n).unwrap_or("")),+ ContentPart::OpenQuote => text.push_str("es.0),+ ContentPart::CloseQuote => text.push_str("es.1),+ }+ }+ let key = child_key(self.nodes[i].key, tag, 0);+ let g = self.push(Some(i), Content::Element, None, sid, key, true);+ self.nodes[g].el = self.els.len() as u32;+ self.els.push(ElData { tag, id: None, attrs: Vec::new(), listeners: None, has: 0 });+ if !text.is_empty() {+ self.push(Some(g), Content::Text(text), Some(g), sid, child_key(key, "#text", 1), true);+ }+ }+/// Children of element `i`: elements and text, keyed by position.fn children(&mut self, i: usize, mut children: Vec<AnyElement>) {// list markers: painted outside the box, or inline text when `inside`@@ -760,6 +1128,17 @@ impl<'a> Builder<'a> {}}let count = children.iter().filter(|c| matches!(c, AnyElement::Element(_))).count();+ // positions among siblings of the same tag (`:nth-of-type`, `:last-of-type`):+ // totals per tag (few distinct tags), then running counters, O(n)+ let mut tag_counts: smallvec::SmallVec<[(&'static str, u32, u32); 8]> = smallvec::SmallVec::new();+ for c in &children {+ if let AnyElement::Element(d) = c {+ match tag_counts.iter_mut().find(|t| std::ptr::eq(t.0, d.tag) || t.0 == d.tag) {+ Some(t) => t.1 += 1,+ None => tag_counts.push((d.tag, 1, 0)),+ }+ }+ }let (mut k, mut n) = (0, 0);let parent_key = self.nodes[i].key;for child in children {@@ -771,6 +1150,10 @@ impl<'a> Builder<'a> {Some(id) => id_key(id),None => child_key(parent_key, d.tag, k),};+ if let Some(t) = tag_counts.iter_mut().find(|t| std::ptr::eq(t.0, d.tag) || t.0 == d.tag) {+ t.2 += 1;+ self.next_tpos = (t.2, t.1);+ }self.element(d, Some(i), key, (k, count));}AnyElement::Text(t) => {@@ -800,11 +1183,11 @@ impl<'a> Builder<'a> {DisplayKind::Table | DisplayKind::TableRowGroup => {s.flex_direction = FlexDirection::Column;let sp = if c.border_collapse { 0.0 } else { c.border_spacing.1 };- s.gap.height = LengthPercentage::Length(sp);+ s.gap.height = LengthPercentage::length(sp);if c.display == DisplayKind::Table && !c.border_collapse {- let pad = |v: LengthPercentage, add: f32| match v {- LengthPercentage::Length(p) => LengthPercentage::Length(p + add),- other => other,+ let pad = |v: LengthPercentage, add: f32| match v.into_raw() {+ r if r.tag() == taffy::CompactLength::LENGTH_TAG => LengthPercentage::length(r.value() + add),+ _ => v,};let (h, v) = c.border_spacing;s.padding = Rect { left: pad(s.padding.left, h), right: pad(s.padding.right, h),@@ -814,16 +1197,17 @@ impl<'a> Builder<'a> {}DisplayKind::TableRow => {s.flex_direction = FlexDirection::Row;- s.gap.width = LengthPercentage::Length(if c.border_collapse { 0.0 } else { c.border_spacing.0 });+ s.gap.width = LengthPercentage::length(if c.border_collapse { 0.0 } else { c.border_spacing.0 });Display::Flex}+ _ if c.layout.display == Display::FlowRoot => Display::FlowRoot,_ => Display::Block,};- if c.display == DisplayKind::TableCell && s.size.width == Dimension::Auto {+ if c.display == DisplayKind::TableCell && s.size.width == Dimension::auto() {let span = self.attr(i, "colspan").and_then(|v| v.parse::<f32>().ok()).unwrap_or(1.0);s.flex_grow = span;s.flex_shrink = 1.0;- s.flex_basis = Dimension::Percent(0.0);+ s.flex_basis = Dimension::percent(0.0);}s}@@ -835,13 +1219,13 @@ impl<'a> Builder<'a> {// nowrap / pre text arrives as unbreakable pieces; wrapping only// happens at forced breaks (<br>, newlines) and between inline boxess.flex_wrap = FlexWrap::Wrap;- s.align_items = Some(AlignItems::FlexEnd);- s.align_content = Some(AlignContent::FlexStart);- s.justify_content = Some(match c.text_align {- TextAlign::Center => JustifyContent::Center,- TextAlign::Right => JustifyContent::FlexEnd,- _ => JustifyContent::FlexStart,- });+ s.align_items = AlignItems::FLEX_END;+ s.align_content = AlignContent::FLEX_START;+ s.justify_content = match c.text_align {+ TextAlign::Center => JustifyContent::CENTER,+ TextAlign::Right => JustifyContent::FLEX_END,+ _ => JustifyContent::FLEX_START,+ };s}@@ -859,25 +1243,23 @@ impl<'a> Builder<'a> {};let t = &mut *self.taffy;if let Some(id) = reuse {- if t.style(id).map(|s| *s != style).unwrap_or(true) {- let _ = t.set_style(id, style);+ if *t.style(id) != style {+ t.set_style(id, style);self.changed = true;}- let same_kids = t.child_count(id) == children.len()- && children.iter().enumerate().all(|(k, c)| t.child_at_index(id, k).ok() == Some(*c));- if !same_kids {- let _ = t.set_children(id, children);+ if t.children(id) != children {+ t.set_children(id, children);self.changed = true;}- if t.get_node_context(id) != ctx.as_ref() {- let _ = t.set_node_context(id, ctx);+ if t.context(id) != ctx.as_ref() {+ t.set_context(id, ctx);self.changed = true;}return id;}let id = match ctx {- Some(m) => t.new_leaf_with_context(style, m).unwrap(),- None => t.new_with_children(style, children).unwrap(),+ Some(m) => t.new_leaf_with_context(style, m),+ None => t.new_with_children(style, children),};self.changed = true;match self.recon.map.entry(key) {@@ -923,7 +1305,7 @@ impl<'a> Builder<'a> {let outer = std::mem::replace(&mut self.changed, false);let id = self.layout_node_inner(i);if self.changed {- let _ = self.taffy.mark_dirty(id);+ self.taffy.mark_dirty(id);}self.changed |= outer;id@@ -933,19 +1315,19 @@ impl<'a> Builder<'a> {let mut base = self.base_style(i);if i == 0 {// the root fills the viewport- base.min_size = Size { width: Dimension::Length(self.viewport.0),- height: Dimension::Length(self.viewport.1) };+ base.min_size = Size { width: LengthPercentageAuto::length(self.viewport.0),+ height: LengthPercentageAuto::length(self.viewport.1) };}let sid = self.nodes[i].style;match &self.nodes[i].content {Content::Widget(spec) => {let (w, h) = (self.widgets)(self.nodes[i].key, spec);let mut s = base;- if s.size.width == Dimension::Auto {- s.size.width = Dimension::Length(w);+ if s.size.width == Dimension::auto() {+ s.size.width = Dimension::length(w);}- if s.size.height == Dimension::Auto {- s.size.height = Dimension::Length(h);+ if s.size.height == Dimension::auto() {+ s.size.height = Dimension::length(h);}return self.leaf(i, s);}@@ -957,14 +1339,14 @@ impl<'a> Builder<'a> {let attr = |n: &str| self.attr(i, n).and_then(|v| v.trim_end_matches("px").parse::<f32>().ok());let mut s = base;let (aw, ah) = (attr("width"), attr("height"));- if s.size.width == Dimension::Auto {- s.size.width = Dimension::Length(aw.unwrap_or(match ah {+ if s.size.width == Dimension::auto() {+ s.size.width = Dimension::length(aw.unwrap_or(match ah {Some(h) if ih > 0.0 => h * iw / ih,_ => iw,}));}- if s.size.height == Dimension::Auto {- s.size.height = Dimension::Length(ah.unwrap_or(match aw {+ if s.size.height == Dimension::auto() {+ s.size.height = Dimension::length(ah.unwrap_or(match aw {Some(w) if iw > 0.0 => w * ih / iw,_ => ih,}));@@ -972,7 +1354,7 @@ impl<'a> Builder<'a> {return self.leaf(i, s);}Content::LineBreak => {- let s = Style { size: Size { width: Dimension::Percent(1.0), height: Dimension::Length(0.0) },+ let s = Style { size: Size { width: Dimension::percent(1.0), height: Dimension::length(0.0) },flex_shrink: 0.0, ..Default::default() };return self.leaf(i, s);}@@ -1117,7 +1499,7 @@ impl<'a> Builder<'a> {let ls = Self::line_style(&self.styles[style], Style::default());let id = self.node(key, ls, None, &line);if self.changed {- let _ = self.taffy.mark_dirty(id);+ self.taffy.mark_dirty(id);}self.nodes[anon].taffy = Some(id);out.push(id);@@ -1216,9 +1598,9 @@ impl<'a> Builder<'a> {let content = Content::Word { src: src as u32, start: a as u32, end: b as u32 };let node = self.push(Some(owner), content, Some(owner), sid, child_key(src_key, "#w", n), false);let s = Style {- size: Size { width: Dimension::Length(w.ceil()), height: Dimension::Length(line_h) },+ size: Size { width: Dimension::length(w.ceil()), height: Dimension::length(line_h) },flex_shrink: 0.0,- margin: Rect { left: LengthPercentageAuto::Length(if n == 0 { indent } else { 0.0 }),+ margin: Rect { left: LengthPercentageAuto::length(if n == 0 { indent } else { 0.0 }),..Rect::zero() },..Default::default()};@@ -1227,7 +1609,7 @@ impl<'a> Builder<'a> {let br = self.push(Some(owner), Content::LineBreak, Some(owner), sid,child_key(src_key, "#br", n), false);line.push(self.leaf(br, Style {- size: Size { width: Dimension::Percent(1.0), height: Dimension::Length(0.0) },+ size: Size { width: Dimension::percent(1.0), height: Dimension::length(0.0) },flex_shrink: 0.0,..Default::default()}));@@ -1289,7 +1671,12 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, carecycle: Frame, widgets: &mut dyn FnMut(Key, &WidgetSpec) -> (f32, f32)) -> Frame {let mut css = String::new();let mut title = None;- collect_styles(&root, &mut css, &mut title);+ caches.tw.on = TAILWIND.load(std::sync::atomic::Ordering::Relaxed);+ collect_styles(&root, &mut css, &mut title, &mut caches.tw);+ if caches.tw.on && !caches.tw.rules.is_empty() {+ css.push('\n');+ css.push_str(caches.tw.css());+ }let css_hash = fnv(&[css.as_bytes()]);if css_hash != caches.author.hash {caches.author = AuthorSheet { hash: css_hash, sheet: Stylesheet::parse(&css) };@@ -1297,7 +1684,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, cacaches.styles.begin_frame();// the taffy tree persists: drop last frame's duplicates, start a new stampfor id in caches.recon.extra.drain(..) {- let _ = caches.taffy.remove(id);+ caches.taffy.remove(id);}caches.recon.stamp = caches.recon.stamp.wrapping_add(1);caches.text_box.clear();@@ -1308,7 +1695,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, cacaches.matched.map.clear();caches.matched.author = caches.author.hash;}- let LayoutCaches { styles, text, images, author, taffy, box_of, acc, matched, recon, text_box } = caches;+ let LayoutCaches { styles, text, images, author, taffy, box_of, acc, matched, recon, text_box, .. } = caches;let mut b = Builder {nodes,els,@@ -1320,8 +1707,11 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, carecon,text_box,changed: false,+ next_tpos: (1, 1),author: &author.sheet,author_hash: author.hash,+ ua_media: ua_stylesheet().media_results(&crate::css::MediaEnv::viewport(viewport)),+ au_media: author.sheet.media_results(&crate::css::MediaEnv::viewport(viewport)),state,viewport,title,@@ -1354,16 +1744,15 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, caif *st == stamp {return true;}- let _ = taffy_ref.remove(*id);+ taffy_ref.remove(*id);false});let avail = Size { width: AvailableSpace::Definite(viewport.0),height: AvailableSpace::Definite(viewport.1) };let Builder { nodes, els, taffy, styles, text: tc, title, text_box, .. } = b;- taffy- .compute_layout_with_measure(root_id, avail, |known, available, _id, ctx, _style| {+ taffy.compute(root_id, avail, |known, available, ctx| {match ctx {- Some(Measure::Text { key, size, flags, line, nowrap, .. }) => {+ Measure::Text { key, size, flags, line, nowrap, .. } => {let text = match text_box.get(key).map(|&k| &nodes[k].content) {Some(Content::Text(t)) => t.as_str(),_ => "",@@ -1384,10 +1773,8 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, caSize { width: known.width.unwrap_or(w.ceil()),height: known.height.unwrap_or(*line * lines.len().max(1) as f32) }}- None => Size::ZERO,}- })- .unwrap();+ });drop(s);let _s = span(Phase::Place);let mut frame = Frame { nodes, els, title, by_key: Default::default() };@@ -1402,7 +1789,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca}}let mut walk = Walk { t: taffy, box_of, state, vp: viewport, styles, text: tc };- walk.place(&mut frame.nodes, root_id, 0.0, 0.0, None);+ walk.place(&mut frame.nodes, root_id, 0.0, 0.0, None, (0.0, 0.0));finish(&mut frame.nodes, styles, acc);frame}@@ -1410,7 +1797,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca/// Positions follow the taffy tree (words live in line containers, which may/// be anonymous); translate and scroll offsets shift whole subtrees.struct Walk<'a> {- t: &'a TaffyTree<Measure>,+ t: &'a crate::tree::LayoutTree<Measure>,box_of: &'a [u32],state: &'a UiState,vp: (f32, f32),@@ -1419,11 +1806,11 @@ struct Walk<'a> {}impl Walk<'_> {- fn place(&mut self, nodes: &mut [BoxNode], id: NodeId, ox: f32, oy: f32, clip: Option<Bounds<f32>>) {- let l = match self.t.layout(id) {- Ok(l) => *l,- Err(_) => return,- };+ /// `cb`: the origin of the containing block of absolutely positioned+ /// descendants (taffy places those relative to it, not to their parent).+ fn place(&mut self, nodes: &mut [BoxNode], id: NodeId, ox: f32, oy: f32, clip: Option<Bounds<f32>>,+ cb: (f32, f32)) {+ let l = *self.t.layout(id);let (mut x, mut y) = (ox + l.location.x, oy + l.location.y);let (w, h) = (l.size.width, l.size.height);let mut child_clip = clip;@@ -1455,8 +1842,8 @@ impl Walk<'_> {let axis = |o: Overflow, content: f32, view: f32| {if o == Overflow::Scroll { (content - view).max(0.0) } else { 0.0 }};- let range = (axis(ov.x, l.content_size.width + l.padding.right, pad.size.width),- axis(ov.y, l.content_size.height + l.padding.bottom, pad.size.height));+ let range = (axis(ov.x, l.scrollable_overflow_rect.right, pad.size.width),+ axis(ov.y, l.scrollable_overflow_rect.bottom, pad.size.height));nodes[i].scroll_range = range;let (ax, ay) = self.state.scroll.get(&nodes[i].key).copied().unwrap_or((0.0, 0.0));sx = ax.clamp(0.0, range.0);@@ -1468,10 +1855,15 @@ impl Walk<'_> {place_folded_text(nodes, i, k, rect(x, y, w, h), &l, self.styles, self.text);}}- let n = self.t.child_count(id);- for c in 0..n {- let k = self.t.child_at_index(id, c).unwrap();- self.place(nodes, k, x - sx, y - sy, child_clip);+ let inner = (x - sx, y - sy);+ let cb = if self.t.style(id).position == Position::Static { cb } else { inner };+ for &k in self.t.children(id) {+ let (kx, ky) = match self.t.style(k).position {+ Position::Absolute => cb,+ Position::Fixed => (0.0, 0.0),+ _ => inner,+ };+ self.place(nodes, k, kx, ky, child_clip, cb);}}}@@ -1504,17 +1896,18 @@ fn place_folded_text(nodes: &mut [BoxNode], i: usize, k: usize, b: Bounds<f32>,2 => room - size,_ => 0.0,};- let justify = match s.justify_content {- Some(JustifyContent::Center | JustifyContent::SpaceAround | JustifyContent::SpaceEvenly) => 1,- Some(JustifyContent::End | JustifyContent::FlexEnd) => 2,+ use taffy::style::{AlignContentKeyword as Ac, AlignItemsKeyword as Ai};+ let justify = match s.justify_content.keyword() {+ Ac::Center | Ac::SpaceAround | Ac::SpaceEvenly => 1,+ Ac::End | Ac::FlexEnd => 2,_ => 0,};- let align = match s.align_items {- Some(AlignItems::Center) => 1,- Some(AlignItems::End | AlignItems::FlexEnd) => 2,+ let align = match s.align_items.keyword() {+ Ai::Center => 1,+ Ai::End | Ai::FlexEnd => 2,_ => 0,};- let stretch = matches!(s.align_items, None | Some(AlignItems::Stretch));+ let stretch = matches!(s.align_items.keyword(), Ai::Normal | Ai::Stretch);let tb = match c.display {DisplayKind::Flex | DisplayKind::InlineFlex if s.flex_direction == FlexDirection::Row => {rect(cb.origin.x + at(cb.size.width, tw, justify), cb.origin.y + at(cb.size.height, th, align), tw, th)diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rsindex f9ac240..9e3f8e5 100644--- a/bindings/rust/blenderui/src/lib.rs+++ b/bindings/rust/blenderui/src/lib.rs@@ -55,7 +55,20 @@ extern crate self as blenderui;/// ```pub use blenderui_macros::css;+/// Tailwind CSS v4 classes checked at compile time:+/// `div().class(tw!("p-4 md:flex hover:bg-sky-500/50"))`. Plain+/// `.class("...")` works too (classes compile on first use); `tw!` turns a+/// typo into a compile error:+///+/// ```compile_fail+/// use blenderui::prelude::*;+/// let _ = div().class(tw!("p-4 flx"));+/// ```+pub use blenderui_macros::tw;++pub mod calc;pub mod color;+mod color4;pub mod css;pub mod element;pub mod events;@@ -64,7 +77,11 @@ pub mod html;pub(crate) mod layout;pub mod paint;pub(crate) mod prof;+mod selector;pub mod style;+pub use blenderui_tailwind as tailwind;+mod tree;+mod vars;pub mod styled;pub(crate) mod text;pub(crate) mod widgets;@@ -80,9 +97,28 @@ pub use paint::{Image, Painter};pub use styled::{FontWeight, StyleBlock, Styled};pub use window::*;+/// Whether `class` names also work as Tailwind CSS v4 utilities (`p-4`,+/// `md:hover:bg-sky-500/50` ...), compiled on first use. On by default;+/// turn it off when your own class names collide with Tailwind's.+pub fn set_tailwind(on: bool) {+ layout::TAILWIND.store(on, std::sync::atomic::Ordering::Relaxed);+}++/// Registers a TrueType/OpenType font under `family` (as bold and/or italic+/// when set), e.g. bundled with `include_bytes!`. Required on wasm, where+/// there are no system fonts; elsewhere it adds to them. Returns false when+/// the data isn't a font.+pub fn add_font(family: &str, bold: bool, italic: bool, data: &[u8]) -> bool {+ let fam = std::ffi::CString::new(family).unwrap_or_default();+ let flags = if bold { 1 } else { 0 } | if italic { 2 } else { 0 };+ let len = data.len().min(i32::MAX as usize) as i32;+ // SAFETY: the kit copies the bytes; both pointers are valid for the call.+ unsafe { sys::BUI_text_add_font(fam.as_ptr(), flags, data.as_ptr().cast(), len) != 0 }+}+/// Everything an app needs: `use blenderui::prelude::*;`pub mod prelude {- pub use crate::css;+ pub use crate::{css, tw};pub use crate::color::*;pub use crate::element::*;pub use crate::events::*;diff --git a/bindings/rust/blenderui/src/paint.rs b/bindings/rust/blenderui/src/paint.rsindex 135aad9..3047037 100644--- a/bindings/rust/blenderui/src/paint.rs+++ b/bindings/rust/blenderui/src/paint.rs@@ -338,9 +338,12 @@ impl Painter {// Painting a framefn lp(v: LengthPercentage, basis: f32) -> f32 {- match v {- LengthPercentage::Length(p) => p,- LengthPercentage::Percent(f) => f * basis,+ use taffy::style::ExpandedLengthPercentage as E;+ match v.expand() {+ E::Length(p) => p,+ E::Percent(f) => f * basis,+ // SAFETY: calc pointers in styles come from crate::calc's interner+ E::Calc(ptr) => unsafe { crate::calc::Resolved::from_ptr(ptr) }.eval(basis),}}diff --git a/bindings/rust/blenderui/src/selector.rs b/bindings/rust/blenderui/src/selector.rsnew file mode 100644index 0000000..4ce4fa4--- /dev/null+++ b/bindings/rust/blenderui/src/selector.rs@@ -0,0 +1,1812 @@+//! Selectors Level 4 and the stylesheet: rules, at-rules and matching.+//!+//! Selectors: type / class / id / attribute (all operators, `i` / `s`+//! flags), every combinator, `:is()` / `:where()` / `:not()` with full+//! selector lists, relative `:has()`, `:nth-*(An+B [of S])`, the+//! `*-of-type` family, `:lang()`, `:dir()`, `:scope`, nesting (`&`) and+//! pseudo-elements (`::before`, `::after`, `::marker`, `::placeholder` ...).+//!+//! Stylesheets: nested rules, `@media` (Media Queries 4: ranges, `not`,+//! `or`, every desktop feature), `@supports` (incl. `selector()`),+//! `@layer` (cascade layers, statement and block forms), `@container` (size+//! queries), `@scope`, `@font-face`, `@keyframes`, `@property`; the rest+//! (`@page`, `@counter-style`, `@starting-style` ...) parse and are skipped.++use crate::css::{parse_declarations, split_top, strip_comments, Decl};++// ==========================================================================+// Selectors++#[derive(Clone, Copy, Debug, PartialEq)]+enum AttrOp {+ Exists,+ Eq,+ Word,+ Prefix,+ Suffix,+ Contains,+ Dash,+}++/// Pseudo-elements a rule can target.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum PseudoElement {+ Before,+ After,+ Marker,+ Placeholder,+ Selection,+ FirstLine,+ FirstLetter,+ Backdrop,+ FileSelectorButton,+ /// Vendor and other pseudo-elements: parsed, never generated.+ Other,+}++#[derive(Clone, Debug, PartialEq)]+enum Simple {+ Universal,+ Tag(String),+ Id(String),+ Class(String),+ Attr { name: String, op: AttrOp, val: String, ci: bool },+ /// State and structural pseudo-classes without arguments.+ Pseudo(String),+ Nth { a: i32, b: i32, last: bool, of_type: bool, of: Option<Box<[Selector]>> },+ Not(Box<[Selector]>),+ Is(Box<[Selector]>),+ Where(Box<[Selector]>),+ /// `:has()`: the index of its relative selectors in the stylesheet.+ Has(u16),+ Lang(Box<[String]>),+ Dir(bool),+ Never,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Combinator {+ Descendant,+ Child,+ Adjacent,+ Sibling,+}++/// A complex selector: compounds joined by combinators, stored right to+/// left (each compound with the combinator to the next one leftwards).+#[derive(Clone, Debug, PartialEq)]+pub struct Selector {+ parts: Vec<(Vec<Simple>, Option<Combinator>)>,+ pub specificity: (u16, u16, u16),+ pub pseudo: Option<PseudoElement>,+}++/// One `:has()`: its relative selectors and the rest of the compound it+/// sits in (`.card` in `.card:has(img)`).+#[derive(Clone, Debug, PartialEq)]+pub struct HasEntry {+ pub rels: Box<[RelSelector]>,+ host: Vec<Simple>,+}++impl HasEntry {+ /// Whether the compound around this `:has()` can match `el` (a cheap+ /// filter before walking `el`'s subtree).+ pub fn host_matches<S: Subject>(&self, el: &S) -> bool {+ self.host.iter().all(|s| match s {+ Simple::Pseudo(_) => true, // states may change: evaluate anyway+ other => match_simple(other, el),+ })+ }+}++/// A relative selector inside `:has()`: `> img`, `+ .x`, `.a .b`.+#[derive(Clone, Debug, PartialEq)]+pub struct RelSelector {+ pub comb: Combinator,+ pub sel: Selector,+}++/// What a selector can ask about an element.+pub trait Subject: Sized + Clone {+ fn tag(&self) -> &str;+ fn id(&self) -> Option<&str>;+ fn has_class(&self, class: &str) -> bool;+ fn attr(&self, name: &str) -> Option<&str>;+ fn state(&self, pseudo: &str) -> bool;+ fn parent(&self) -> Option<Self>;+ fn prev_sibling(&self) -> Option<Self>;+ /// 1-based position among element siblings, and their count.+ fn position(&self) -> (usize, usize);+ fn is_empty(&self) -> bool;+ /// The `class` attribute (used to find candidate rules quickly).+ fn class_attr(&self) -> Option<&str> {+ self.attr("class")+ }+ /// 1-based position among siblings of the same type, and their count.+ fn type_position(&self) -> (usize, usize) {+ let mut i = 1;+ let mut cur = self.prev_sibling();+ while let Some(p) = cur {+ if p.tag().eq_ignore_ascii_case(self.tag()) {+ i += 1;+ }+ cur = p.prev_sibling();+ }+ (i, i)+ }+ /// Whether `:has()` number `id` of the author stylesheet holds here.+ fn has(&self, _id: u16) -> bool {+ false+ }+ /// The size of the nearest query container (named `name`, if given).+ fn container(&self, _name: Option<&str>) -> Option<(f32, f32)> {+ None+ }+ fn same(&self, _other: &Self) -> bool {+ false+ }+ fn first_child(&self) -> Option<Self> {+ None+ }+ fn next_sibling(&self) -> Option<Self> {+ None+ }+}++impl Selector {+ /// Parse one complex selector (no relative combinator). `:has()`+ /// arguments are kept only when parsed through a [`Stylesheet`].+ pub fn parse(s: &str) -> Option<Selector> {+ let mut has = Vec::new();+ let (lead, sel) = parse_complex(s, &mut has, false)?;+ (lead.is_none()).then_some(sel)+ }++ /// Where a rule is filed in a stylesheet's index.+ fn bucket(&self) -> Bucket {+ let subject = &self.parts[0].0;+ let mut b = Bucket::Universal;+ for s in subject {+ match s {+ Simple::Id(i) => return Bucket::Id(i.clone()),+ Simple::Class(c) => b = Bucket::Class(c.clone()),+ Simple::Tag(t) if matches!(b, Bucket::Universal) => b = Bucket::Tag(t.clone()),+ _ => {}+ }+ }+ b+ }++ /// Whether `el` is this selector's subject (pseudo-elements are matched+ /// on their originating element).+ pub fn matches<S: Subject>(&self, el: &S) -> bool {+ match_from(&self.parts, 0, el, None)+ }+}++enum Bucket {+ Id(String),+ Class(String),+ Tag(String),+ Universal,+}++fn spec_of(compound: &[Simple], spec: &mut (u16, u16, u16)) {+ let max_of = |list: &[Selector]| list.iter().map(|s| s.specificity).max().unwrap_or((0, 0, 0));+ let add = |spec: &mut (u16, u16, u16), o: (u16, u16, u16)| {+ spec.0 += o.0;+ spec.1 += o.1;+ spec.2 += o.2;+ };+ for s in compound {+ match s {+ Simple::Id(_) => spec.0 += 1,+ Simple::Class(_) | Simple::Attr { .. } | Simple::Pseudo(_) | Simple::Lang(_) | Simple::Dir(_)+ | Simple::Has(_) | Simple::Never => spec.1 += 1,+ Simple::Nth { of, .. } => {+ spec.1 += 1;+ if let Some(of) = of {+ add(spec, max_of(of));+ }+ }+ Simple::Tag(_) => spec.2 += 1,+ Simple::Not(l) | Simple::Is(l) => add(spec, max_of(l)),+ Simple::Where(_) | Simple::Universal => {}+ }+ }+}++/// `"a, b"` -> selectors; `forgiving` drops invalid ones (`:is()`, `:where()`).+fn parse_list(s: &str, has: &mut Vec<HasEntry>, forgiving: bool) -> Option<Box<[Selector]>> {+ let mut out = Vec::new();+ for part in split_top(s, ',') {+ match parse_complex(part, has, false) {+ Some((None, sel)) => out.push(sel),+ _ if forgiving => {}+ _ => return None,+ }+ }+ Some(out.into_boxed_slice())+}++/// One complex selector; with `relative`, it may start with a combinator.+fn parse_complex(s: &str, has: &mut Vec<HasEntry>, relative: bool)+ -> Option<(Option<Combinator>, Selector)> {+ let s = s.trim();+ if s.is_empty() {+ return None;+ }+ let mut parts: Vec<(Vec<Simple>, Option<Combinator>)> = Vec::new();+ let mut pending: Option<Combinator> = None;+ let mut lead = None;+ let mut pseudo = None;+ let b = s.as_bytes();+ let mut i = 0;+ while i < b.len() {+ let c = b[i] as char;+ if c.is_whitespace() {+ i += 1;+ if pending.is_none() && !parts.is_empty() {+ pending = Some(Combinator::Descendant);+ }+ continue;+ }+ if matches!(c, '>' | '+' | '~') {+ let comb = match c {+ '>' => Combinator::Child,+ '+' => Combinator::Adjacent,+ _ => Combinator::Sibling,+ };+ if parts.is_empty() {+ if !relative || lead.is_some() {+ return None;+ }+ lead = Some(comb);+ } else {+ pending = Some(comb);+ }+ i += 1;+ continue;+ }+ if pseudo.is_some() {+ return None; // nothing may follow a pseudo-element here+ }+ let (compound, pe, next) = parse_compound(s, i, has)?;+ pseudo = pe;+ if let Some(last) = parts.last_mut() {+ last.1 = Some(pending.unwrap_or(Combinator::Descendant));+ }+ parts.push((compound, None));+ pending = None;+ i = next;+ }+ if parts.is_empty() || pending.is_some() {+ return None;+ }+ parts.reverse();+ let mut spec = (0u16, 0u16, 0u16);+ for (compound, _) in &parts {+ spec_of(compound, &mut spec);+ }+ if pseudo.is_some() {+ spec.2 += 1;+ }+ let n = parts.len();+ let combs: Vec<Option<Combinator>> = parts.iter().map(|p| p.1).collect();+ for k in 0..n {+ parts[k].1 = if k + 1 < n { combs[k + 1] } else { None };+ }+ Some((if relative { Some(lead.unwrap_or(Combinator::Descendant)) } else { None },+ Selector { parts, specificity: spec, pseudo }))+}++fn is_name_char(c: char) -> bool {+ c.is_ascii_alphanumeric() || c == '-' || c == '_' || !c.is_ascii()+}++fn scan_ident(s: &str, mut i: usize) -> usize {+ let b = s.as_bytes();+ while i < b.len() {+ if b[i] == b'\\' && i + 1 < b.len() {+ i += 2;+ continue;+ }+ let c = s[i..].chars().next().unwrap_or(' ');+ if !is_name_char(c) {+ break;+ }+ i += c.len_utf8();+ }+ i+}++/// CSS escapes in identifiers (`.md\:flex` -> `md:flex`, `.w-1\/2`).+fn unescape(s: &str) -> String {+ if !s.contains('\\') {+ return s.to_string();+ }+ let mut out = String::with_capacity(s.len());+ let mut it = s.chars().peekable();+ while let Some(c) = it.next() {+ if c != '\\' {+ out.push(c);+ continue;+ }+ let mut hex = String::new();+ while hex.len() < 6 && it.peek().is_some_and(|c| c.is_ascii_hexdigit()) {+ hex.push(it.next().unwrap_or('0'));+ }+ if hex.is_empty() {+ if let Some(n) = it.next() {+ out.push(n);+ }+ } else {+ if it.peek() == Some(&' ') {+ it.next();+ }+ out.push(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32).unwrap_or('\u{fffd}'));+ }+ }+ out+}++fn matching_paren(s: &str, open: usize) -> usize {+ let (mut depth, mut quote) = (0i32, None::<char>);+ for (k, c) in s[open..].char_indices() {+ match (quote, c) {+ (Some(q), _) if c == q => quote = None,+ (Some(_), _) => {}+ (None, '"' | '\'') => quote = Some(c),+ (None, '(') => depth += 1,+ (None, ')') => {+ depth -= 1;+ if depth == 0 {+ return open + k;+ }+ }+ _ => {}+ }+ }+ s.len()+}++fn pseudo_element(name: &str) -> PseudoElement {+ match name {+ "before" => PseudoElement::Before,+ "after" => PseudoElement::After,+ "marker" => PseudoElement::Marker,+ "placeholder" | "-webkit-input-placeholder" | "-moz-placeholder" => PseudoElement::Placeholder,+ "selection" | "-moz-selection" => PseudoElement::Selection,+ "first-line" => PseudoElement::FirstLine,+ "first-letter" => PseudoElement::FirstLetter,+ "backdrop" => PseudoElement::Backdrop,+ "file-selector-button" | "-webkit-file-upload-button" => PseudoElement::FileSelectorButton,+ _ => PseudoElement::Other,+ }+}++/// Pseudo-classes that are never true in this host (no history, no media+/// playback, no fullscreen, no autofill ...).+const NEVER: &[&str] = &[+ "visited", "target", "target-within", "fullscreen", "autofill", "-webkit-autofill", "modal",+ "popover-open", "picture-in-picture", "playing", "paused", "seeking", "buffering", "stalled",+ "muted", "volume-locked", "local-link", "current", "past", "future", "host", "user-invalid",+ "first", "left", "right", "blank", "-moz-focusring", "has-slotted", "open-in", "active-view-transition",+];++fn parse_compound(s: &str, mut i: usize, has: &mut Vec<HasEntry>)+ -> Option<(Vec<Simple>, Option<PseudoElement>, usize)> {+ let b = s.as_bytes();+ let mut out = Vec::new();+ let mut pe = None;+ while i < b.len() {+ let c = b[i] as char;+ match c {+ '*' => {+ out.push(Simple::Universal);+ i += 1;+ }+ '&' => {+ // nesting resolved by the stylesheet; a bare `&` is the scope root+ out.push(Simple::Pseudo("scope".into()));+ i += 1;+ }+ '#' | '.' => {+ let end = scan_ident(s, i + 1);+ if end == i + 1 {+ return None;+ }+ let name = unescape(&s[i + 1..end]);+ out.push(if c == '#' { Simple::Id(name) } else { Simple::Class(name) });+ i = end;+ }+ '[' => {+ let close = s[i..].find(']')? + i;+ out.push(parse_attr(&s[i + 1..close])?);+ i = close + 1;+ }+ '|' => i += 1, // namespaces: ignored+ ':' => {+ let double = b.get(i + 1) == Some(&b':');+ let start = if double { i + 2 } else { i + 1 };+ let end = scan_ident(s, start);+ let name = s[start..end].to_ascii_lowercase();+ let legacy_pe = matches!(name.as_str(), "before" | "after" | "first-line" | "first-letter");+ if double || legacy_pe {+ pe = Some(pseudo_element(&name));+ i = end;+ if b.get(i) == Some(&b'(') {+ i = matching_paren(s, i) + 1; // ::part(), ::slotted(), ::highlight()+ }+ continue;+ }+ if b.get(end) == Some(&b'(') {+ let close = matching_paren(s, end);+ let arg = s[end + 1..close.min(s.len())].trim();+ out.push(match name.as_str() {+ "not" => Simple::Not(parse_list(arg, has, false)?),+ "is" | "matches" | "-webkit-any" | "-moz-any" => Simple::Is(parse_list(arg, has, true)?),+ "where" => Simple::Where(parse_list(arg, has, true)?),+ "has" => {+ let mut rels = Vec::new();+ for part in split_top(arg, ',') {+ let (comb, sel) = parse_complex(part, has, true)?;+ rels.push(RelSelector { comb: comb.unwrap_or(Combinator::Descendant), sel });+ }+ has.push(HasEntry { rels: rels.into_boxed_slice(), host: Vec::new() });+ Simple::Has((has.len() - 1) as u16)+ }+ "nth-child" | "nth-last-child" | "nth-of-type" | "nth-last-of-type" => {+ let (expr, of) = match split_of(arg) {+ Some((e, sel)) => (e, Some(parse_list(sel, has, false)?)),+ None => (arg, None),+ };+ let (a, bb) = parse_nth(expr)?;+ Simple::Nth { a, b: bb, last: name.contains("last"), of_type: name.ends_with("of-type"),+ of: if name.ends_with("child") { of } else { None } }+ }+ "lang" => Simple::Lang(split_top(arg, ',').iter()+ .map(|l| l.trim().trim_matches(['"', '\'']).to_ascii_lowercase()).collect()),+ "dir" => Simple::Dir(arg.eq_ignore_ascii_case("rtl")),+ "host" | "host-context" | "state" | "current" | "past" | "future" | "active-view-transition-type" => Simple::Never,+ _ => return None,+ });+ i = close + 1;+ } else {+ out.push(if NEVER.contains(&name.as_str()) { Simple::Never } else { Simple::Pseudo(name) });+ i = end;+ }+ }+ c if is_name_char(c) && !c.is_ascii_digit() => {+ let end = scan_ident(s, i);+ out.push(Simple::Tag(unescape(&s[i..end]).to_ascii_lowercase()));+ i = end;+ }+ _ => break,+ }+ }+ for k in 0..out.len() {+ if let Simple::Has(id) = out[k] {+ // the rest of the compound: checked before evaluating :has() itself+ let host: Vec<Simple> = out.iter().filter(|x| !matches!(x, Simple::Has(_))).cloned().collect();+ if let Some(e) = has.get_mut(id as usize) {+ e.host = host;+ }+ }+ }+ (!out.is_empty() || pe.is_some()).then(|| {+ if out.is_empty() {+ out.push(Simple::Universal);+ }+ (out, pe, i)+ })+}++/// `2n+1 of .x` -> ("2n+1", ".x")+fn split_of(arg: &str) -> Option<(&str, &str)> {+ let lower = arg.to_ascii_lowercase();+ let k = lower.find(" of ")?;+ Some((&arg[..k], &arg[k + 4..]))+}++fn parse_attr(inner: &str) -> Option<Simple> {+ let inner = inner.trim();+ // trailing case flag: [a="b" i]+ let (body, ci) = match inner.rsplit_once(char::is_whitespace) {+ Some((b, f)) if (f.eq_ignore_ascii_case("i") || f.eq_ignore_ascii_case("s")) && b.contains('=') => {+ (b.trim(), f.eq_ignore_ascii_case("i"))+ }+ _ => (inner, false),+ };+ for (op, kind) in [("~=", AttrOp::Word), ("^=", AttrOp::Prefix), ("$=", AttrOp::Suffix),+ ("*=", AttrOp::Contains), ("|=", AttrOp::Dash), ("=", AttrOp::Eq)] {+ if let Some((name, val)) = body.split_once(op) {+ let mut val = val.trim().trim_matches(['"', '\'']).to_string();+ if ci {+ val = val.to_lowercase();+ }+ let name = name.trim().trim_start_matches('|').rsplit('|').next().unwrap_or("").to_ascii_lowercase();+ return Some(Simple::Attr { name, op: kind, val, ci });+ }+ }+ Some(Simple::Attr { name: body.to_ascii_lowercase(), op: AttrOp::Exists, val: String::new(), ci: false })+}++fn parse_nth(arg: &str) -> Option<(i32, i32)> {+ let a = arg.replace(' ', "").to_ascii_lowercase();+ match a.as_str() {+ "odd" => return Some((2, 1)),+ "even" => return Some((2, 0)),+ _ => {}+ }+ if let Some((x, y)) = a.split_once('n') {+ let x = match x {+ "" | "+" => 1,+ "-" => -1,+ v => v.parse().ok()?,+ };+ let y = if y.is_empty() { 0 } else { y.trim_start_matches('+').parse().ok()? };+ Some((x, y))+ } else {+ Some((0, a.trim_start_matches('+').parse().ok()?))+ }+}++fn nth_ok(a: i32, b: i32, pos: i32) -> bool {+ if a == 0 {+ pos == b+ } else {+ (pos - b) % a == 0 && (pos - b) / a >= 0+ }+}++/// Match `parts[k..]` at `el`. `anchor`: for `:has()`, the element the+/// leftmost compound must stand in `comb` relation to.+fn match_from<S: Subject>(parts: &[(Vec<Simple>, Option<Combinator>)], k: usize, el: &S,+ anchor: Option<(&S, Combinator)>) -> bool {+ let (compound, comb) = &parts[k];+ if !compound.iter().all(|s| match_simple(s, el)) {+ return false;+ }+ let Some(comb) = comb else {+ return match anchor {+ None => true,+ Some((a, c)) => related(el, a, c),+ };+ };+ let next = |p: &S| match_from(parts, k + 1, p, anchor);+ match comb {+ Combinator::Child => el.parent().is_some_and(|p| next(&p)),+ Combinator::Descendant => {+ let mut cur = el.parent();+ while let Some(p) = cur {+ if anchor.is_some_and(|(a, _)| a.same(&p)) {+ return false; // went above the :has() anchor+ }+ if next(&p) {+ return true;+ }+ cur = p.parent();+ }+ false+ }+ Combinator::Adjacent => el.prev_sibling().is_some_and(|p| next(&p)),+ Combinator::Sibling => {+ let mut cur = el.prev_sibling();+ while let Some(p) = cur {+ if next(&p) {+ return true;+ }+ cur = p.prev_sibling();+ }+ false+ }+ }+}++/// Whether `el` stands in relation `c` to `anchor` (`anchor > el` ...).+fn related<S: Subject>(el: &S, anchor: &S, c: Combinator) -> bool {+ match c {+ Combinator::Child => el.parent().is_some_and(|p| p.same(anchor)),+ Combinator::Descendant => {+ let mut cur = el.parent();+ while let Some(p) = cur {+ if p.same(anchor) {+ return true;+ }+ cur = p.parent();+ }+ false+ }+ Combinator::Adjacent => el.prev_sibling().is_some_and(|p| p.same(anchor)),+ Combinator::Sibling => {+ let mut cur = el.prev_sibling();+ while let Some(p) = cur {+ if p.same(anchor) {+ return true;+ }+ cur = p.prev_sibling();+ }+ false+ }+ }+}++fn any_matches<S: Subject>(list: &[Selector], el: &S) -> bool {+ list.iter().any(|s| s.matches(el))+}++fn match_simple<S: Subject>(s: &Simple, el: &S) -> bool {+ match s {+ Simple::Universal => true,+ Simple::Tag(t) => el.tag().eq_ignore_ascii_case(t),+ Simple::Id(id) => el.id() == Some(id.as_str()),+ Simple::Class(c) => el.has_class(c),+ Simple::Attr { name, op, val, ci } => match el.attr(name) {+ None => false,+ Some(v) => {+ let low;+ let v = if *ci {+ low = v.to_lowercase();+ low.as_str()+ } else {+ v+ };+ match op {+ AttrOp::Exists => true,+ AttrOp::Eq => v == val,+ AttrOp::Word => v.split_whitespace().any(|w| w == val),+ AttrOp::Prefix => !val.is_empty() && v.starts_with(val.as_str()),+ AttrOp::Suffix => !val.is_empty() && v.ends_with(val.as_str()),+ AttrOp::Contains => !val.is_empty() && v.contains(val.as_str()),+ AttrOp::Dash => v == val || v.strip_prefix(val.as_str()).is_some_and(|r| r.starts_with('-')),+ }+ }+ },+ Simple::Pseudo(p) => match p.as_str() {+ "first-child" => el.position().0 == 1,+ "last-child" => {+ let (i, n) = el.position();+ i == n+ }+ "only-child" => el.position().1 == 1,+ "first-of-type" => el.type_position().0 == 1,+ "last-of-type" => {+ let (i, n) = el.type_position();+ i == n+ }+ "only-of-type" => el.type_position().1 == 1,+ "root" => el.parent().is_none(),+ "scope" => el.parent().is_none(),+ "empty" => el.is_empty(),+ "defined" => true,+ other => el.state(other),+ },+ Simple::Nth { a, b, last, of_type, of } => {+ let pos = match (of_type, of) {+ (true, _) => {+ let (i, n) = el.type_position();+ if *last { n + 1 - i } else { i }+ }+ (false, Some(list)) => {+ if !any_matches(list, el) {+ return false;+ }+ if *last {+ let mut k = 1;+ let mut cur = el.next_sibling();+ while let Some(s) = cur {+ if any_matches(list, &s) {+ k += 1;+ }+ cur = s.next_sibling();+ }+ k+ } else {+ let mut k = 1;+ let mut cur = el.prev_sibling();+ while let Some(s) = cur {+ if any_matches(list, &s) {+ k += 1;+ }+ cur = s.prev_sibling();+ }+ k+ }+ }+ (false, None) => {+ let (i, n) = el.position();+ if *last { n + 1 - i } else { i }+ }+ };+ nth_ok(*a, *b, pos as i32)+ }+ Simple::Not(list) => !any_matches(list, el),+ Simple::Is(list) | Simple::Where(list) => any_matches(list, el),+ Simple::Has(id) => el.has(*id),+ Simple::Lang(langs) => {+ let mut cur = Some(el.clone());+ while let Some(e) = cur {+ if let Some(l) = e.attr("lang") {+ let l = l.to_ascii_lowercase();+ return langs.iter().any(|w| w == "*" || l == *w || l.starts_with(&format!("{w}-")));+ }+ cur = e.parent();+ }+ false+ }+ Simple::Dir(rtl) => {+ let mut cur = Some(el.clone());+ while let Some(e) = cur {+ if let Some(d) = e.attr("dir") {+ return d.eq_ignore_ascii_case("rtl") == *rtl;+ }+ cur = e.parent();+ }+ !*rtl+ }+ Simple::Never => false,+ }+}++/// Whether relative selector list `rels` holds for `el` (`:has()`):+/// some element related to `el` matches with `el` as the anchor.+pub fn has_match<S: Subject>(rels: &[RelSelector], el: &S) -> bool {+ rels.iter().any(|r| {+ let hit = |c: &S| match_from(&r.sel.parts, 0, c, Some((el, r.comb)));+ // `c` and its whole subtree+ let subtree = |root: S| -> bool {+ let mut stack = vec![root];+ while let Some(n) = stack.pop() {+ if hit(&n) {+ return true;+ }+ let mut k = n.first_child();+ while let Some(c) = k {+ k = c.next_sibling();+ stack.push(c);+ }+ }+ false+ };+ match r.comb {+ // descendants (deeper compounds of `> a b` live below the children too)+ Combinator::Child | Combinator::Descendant => {+ let mut k = el.first_child();+ while let Some(c) = k {+ k = c.next_sibling();+ if subtree(c) {+ return true;+ }+ }+ false+ }+ Combinator::Adjacent | Combinator::Sibling => {+ let mut k = el.next_sibling();+ while let Some(s) = k {+ k = s.next_sibling();+ if subtree(s) {+ return true;+ }+ }+ false+ }+ }+ })+}++// ==========================================================================+// Media and container queries++/// The environment media queries are evaluated in.+#[derive(Clone, Copy, Debug)]+pub struct MediaEnv {+ pub width: f32,+ pub height: f32,+ pub dark: bool,+ pub scale: f32,+}++impl MediaEnv {+ pub fn viewport(viewport: (f32, f32)) -> MediaEnv {+ MediaEnv { width: viewport.0, height: viewport.1, dark: crate::color4::DARK, scale: 1.0 }+ }+}++#[derive(Clone, Debug, PartialEq)]+enum MediaValue {+ Num(f32),+ Ident(String),+}++#[derive(Clone, Debug, PartialEq)]+enum Cond {+ And(Vec<Cond>),+ Or(Vec<Cond>),+ Not(Box<Cond>),+ /// `(name)`: boolean context+ Bool(String),+ /// `name op value` (ops normalized to the feature on the left)+ Cmp(String, Op, MediaValue),+ /// `style(...)` and other unknown conditions+ False,+}++#[derive(Clone, Copy, Debug, PartialEq)]+enum Op {+ Eq,+ Lt,+ Le,+ Gt,+ Ge,+}++impl Op {+ fn flip(self) -> Op {+ match self {+ Op::Lt => Op::Gt,+ Op::Le => Op::Ge,+ Op::Gt => Op::Lt,+ Op::Ge => Op::Le,+ Op::Eq => Op::Eq,+ }+ }+ fn test(self, a: f32, b: f32) -> bool {+ match self {+ Op::Eq => (a - b).abs() < 1e-3,+ Op::Lt => a < b,+ Op::Le => a <= b + 1e-3,+ Op::Gt => a > b,+ Op::Ge => a + 1e-3 >= b,+ }+ }+}++/// A media query list: true when any query is.+#[derive(Clone, Debug, PartialEq)]+pub struct MediaQuery(Vec<(bool, Option<String>, Option<Cond>)>);++fn media_value(s: &str) -> MediaValue {+ let s = s.trim();+ if let Some((a, b)) = s.split_once('/') {+ if let (Ok(a), Ok(b)) = (a.trim().parse::<f32>(), b.trim().parse::<f32>()) {+ return MediaValue::Num(if b != 0.0 { a / b } else { 0.0 });+ }+ }+ let toks = crate::css::tokenize(s);+ match toks.as_slice() {+ [crate::css::Tok::Num(v)] => MediaValue::Num(*v),+ [crate::css::Tok::Dim(v, u)] => MediaValue::Num(match u.as_ref() {+ "px" => *v,+ "em" | "rem" => v * 16.0,+ "dppx" | "x" => *v,+ "dpi" => v / 96.0,+ "dpcm" => v * 2.54 / 96.0,+ u => crate::calc::leaf(*v, u).map(|c| c.eval_units(+ &crate::geometry::Units { font_size: 16.0, viewport: (0.0, 0.0) }, 0.0)).unwrap_or(*v),+ }),+ [t] if t.ident().is_some() => MediaValue::Ident(t.ident().unwrap_or("").to_string()),+ _ => MediaValue::Ident(s.to_ascii_lowercase()),+ }+}++fn parse_op(s: &str) -> Option<(Op, usize)> {+ let b = s.as_bytes();+ Some(match (b.first()?, b.get(1)) {+ (b'<', Some(b'=')) => (Op::Le, 2),+ (b'>', Some(b'=')) => (Op::Ge, 2),+ (b'<', _) => (Op::Lt, 1),+ (b'>', _) => (Op::Gt, 1),+ (b'=', _) => (Op::Eq, 1),+ _ => return None,+ })+}++/// One `( ... )` feature or nested condition (without the parens).+fn parse_feature(inner: &str) -> Cond {+ let inner = inner.trim();+ if inner.starts_with('(') || inner.starts_with("not ") || inner.contains(") and") || inner.contains(") or") {+ return parse_cond(inner);+ }+ if let Some((name, value)) = inner.split_once(':') {+ let name = name.trim().to_ascii_lowercase();+ if let Some(n) = name.strip_prefix("min-") {+ return Cond::Cmp(n.to_string(), Op::Ge, media_value(value));+ }+ if let Some(n) = name.strip_prefix("max-") {+ return Cond::Cmp(n.to_string(), Op::Le, media_value(value));+ }+ return Cond::Cmp(name, Op::Eq, media_value(value));+ }+ // range syntax: `width >= 600px`, `400px <= width < 700px`+ let ops: Vec<(usize, Op, usize)> = inner.char_indices()+ .filter_map(|(k, _)| {+ let prev_is_op = k > 0 && matches!(inner.as_bytes()[k - 1], b'<' | b'>');+ if prev_is_op {+ return None;+ }+ parse_op(&inner[k..]).map(|(o, n)| (k, o, n))+ })+ .collect();+ match ops.as_slice() {+ [] => Cond::Bool(inner.to_ascii_lowercase()),+ [(k, op, n)] => {+ let (l, r) = (inner[..*k].trim(), inner[k + n..].trim());+ if l.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) && media_value(l) != MediaValue::Num(0.0)+ && !matches!(media_value(l), MediaValue::Num(_)) {+ Cond::Cmp(l.to_ascii_lowercase(), *op, media_value(r))+ } else {+ Cond::Cmp(r.to_ascii_lowercase(), op.flip(), media_value(l))+ }+ }+ [(k1, op1, n1), (k2, op2, n2)] => {+ let (a, name, b) = (inner[..*k1].trim(), inner[k1 + n1..*k2].trim(), inner[k2 + n2..].trim());+ let name = name.to_ascii_lowercase();+ Cond::And(vec![Cond::Cmp(name.clone(), op1.flip(), media_value(a)),+ Cond::Cmp(name, *op2, media_value(b))])+ }+ _ => Cond::False,+ }+}++/// `(a) and (b)`, `(a) or (b)`, `not (a)`, nested.+fn parse_cond(s: &str) -> Cond {+ let s = s.trim();+ if let Some(rest) = s.strip_prefix("not ").or_else(|| s.strip_prefix("not(").map(|_| &s[3..])) {+ return Cond::Not(Box::new(parse_cond(rest)));+ }+ // split into ( ... ) groups joined by and / or+ let mut groups = Vec::new();+ let mut joins = Vec::new();+ let b = s.as_bytes();+ let mut i = 0;+ while i < b.len() {+ match b[i] {+ b'(' => {+ let close = matching_paren(s, i);+ let inner = &s[i + 1..close.min(s.len())];+ let name_end = s[..i].trim_end();+ let func = name_end.rsplit(|c: char| c.is_whitespace() || c == '(').next().unwrap_or("");+ groups.push(if func == "style" || func == "scroll-state" { Cond::False } else { parse_feature(inner) });+ i = close + 1;+ }+ c if c.is_ascii_alphabetic() => {+ let end = s[i..].find(|c: char| !c.is_ascii_alphanumeric() && c != '-').map(|e| i + e).unwrap_or(s.len());+ match &s[i..end] {+ "and" => joins.push(true),+ "or" => joins.push(false),+ _ => {}+ }+ i = end;+ }+ _ => i += 1,+ }+ }+ match groups.len() {+ 0 => Cond::False,+ 1 => groups.pop().unwrap_or(Cond::False),+ _ if joins.iter().all(|j| *j) => Cond::And(groups),+ _ if joins.iter().all(|j| !*j) => Cond::Or(groups),+ _ => Cond::False, // mixing and/or without parens is invalid+ }+}++impl MediaQuery {+ pub fn parse(q: &str) -> MediaQuery {+ let mut out = Vec::new();+ for part in split_top(q, ',') {+ let p = part.trim().to_ascii_lowercase();+ if p.is_empty() {+ continue;+ }+ let (neg, rest) = match p.strip_prefix("not ") {+ Some(r) => (true, r.trim().to_string()),+ None => (false, p.strip_prefix("only ").unwrap_or(&p).trim().to_string()),+ };+ if rest.starts_with('(') {+ out.push((neg, None, Some(parse_cond(&rest))));+ } else {+ let (ty, cond) = match rest.split_once(" and ") {+ Some((t, c)) => (t.trim().to_string(), Some(parse_cond(c))),+ None => (rest.trim().to_string(), None),+ };+ out.push((neg, Some(ty), cond));+ }+ }+ MediaQuery(out)+ }++ pub fn matches(&self, env: &MediaEnv) -> bool {+ self.0.is_empty() || self.0.iter().any(|(neg, ty, cond)| {+ let ty_ok = match ty.as_deref() {+ None | Some("all") | Some("screen") => true,+ _ => false,+ };+ let ok = ty_ok && cond.as_ref().is_none_or(|c| eval(c, &|n, o, v| media_feature(env, n, o, v)));+ ok != *neg+ })+ }+}++type FeatureFn<'a> = dyn Fn(&str, Option<Op>, Option<&MediaValue>) -> Option<bool> + 'a;++fn eval(c: &Cond, f: &FeatureFn) -> bool {+ match c {+ Cond::And(v) => v.iter().all(|c| eval(c, f)),+ Cond::Or(v) => v.iter().any(|c| eval(c, f)),+ Cond::Not(c) => !eval(c, f),+ Cond::Bool(n) => f(n, None, None).unwrap_or(false),+ Cond::Cmp(n, o, v) => f(n, Some(*o), Some(v)).unwrap_or(false),+ Cond::False => false,+ }+}++fn num_feature(value: f32, op: Option<Op>, v: Option<&MediaValue>) -> Option<bool> {+ match (op, v) {+ (None, _) => Some(value != 0.0),+ (Some(o), Some(MediaValue::Num(x))) => Some(o.test(value, *x)),+ _ => None,+ }+}++fn ident_feature(value: &str, op: Option<Op>, v: Option<&MediaValue>, none: &str) -> Option<bool> {+ match (op, v) {+ (None, _) => Some(value != none),+ (Some(Op::Eq), Some(MediaValue::Ident(x))) => Some(value == x),+ _ => None,+ }+}++fn media_feature(env: &MediaEnv, name: &str, op: Option<Op>, v: Option<&MediaValue>) -> Option<bool> {+ let n = name.strip_prefix("device-").unwrap_or(name);+ match n {+ "width" => num_feature(env.width, op, v),+ "height" => num_feature(env.height, op, v),+ "aspect-ratio" => num_feature(env.width / env.height.max(1.0), op, v),+ "orientation" => ident_feature(if env.height >= env.width { "portrait" } else { "landscape" }, op, v, ""),+ "resolution" | "-webkit-device-pixel-ratio" => num_feature(env.scale, op, v),+ "color" => num_feature(8.0, op, v),+ "color-index" | "monochrome" | "grid" => num_feature(0.0, op, v),+ "prefers-color-scheme" => ident_feature(if env.dark { "dark" } else { "light" }, op, v, ""),+ "prefers-reduced-motion" | "prefers-reduced-transparency" | "prefers-reduced-data" => {+ ident_feature("no-preference", op, v, "no-preference")+ }+ "prefers-contrast" => ident_feature("no-preference", op, v, "no-preference"),+ "forced-colors" | "inverted-colors" => ident_feature("none", op, v, "none"),+ "hover" | "any-hover" => ident_feature("hover", op, v, "none"),+ "pointer" | "any-pointer" => ident_feature("fine", op, v, "none"),+ "color-gamut" => match (op, v) {+ (None, _) => Some(true),+ (_, Some(MediaValue::Ident(x))) => Some(x == "srgb"),+ _ => None,+ },+ "dynamic-range" | "video-dynamic-range" => ident_feature("standard", op, v, ""),+ "display-mode" => ident_feature("browser", op, v, ""),+ "scripting" => ident_feature("enabled", op, v, "none"),+ "update" => ident_feature("fast", op, v, "none"),+ "overflow-block" | "overflow-inline" => ident_feature("scroll", op, v, "none"),+ "environment-blending" => ident_feature("opaque", op, v, ""),+ _ => None,+ }+}++/// `@container [name] (query)`.+#[derive(Clone, Debug, PartialEq)]+pub struct ContainerQuery {+ name: Option<String>,+ cond: Cond,+}++impl ContainerQuery {+ fn parse(q: &str) -> ContainerQuery {+ let q = q.trim();+ let (name, rest) = match q.find(['(', ' ']) {+ Some(k) if !q.starts_with('(') && !q.starts_with("not") && !q.starts_with("style") => {+ (Some(q[..k].trim().to_string()), &q[k..])+ }+ _ => (None, q),+ };+ ContainerQuery { name, cond: parse_cond(rest) }+ }++ fn matches<S: Subject>(&self, el: &S) -> bool {+ let Some((w, h)) = el.container(self.name.as_deref()) else { return false };+ eval(&self.cond, &|n, o, v| match n {+ "width" | "inline-size" => num_feature(w, o, v),+ "height" | "block-size" => num_feature(h, o, v),+ "aspect-ratio" => num_feature(w / h.max(1.0), o, v),+ "orientation" => ident_feature(if h >= w { "portrait" } else { "landscape" }, o, v, ""),+ _ => None,+ })+ }+}++// ==========================================================================+// Stylesheets++/// One style rule: a selector with its declarations, in source order.+#[derive(Clone, Debug)]+pub struct Rule {+ pub selector: Selector,+ pub decls: Vec<Decl>,+ /// Index in [`Stylesheet::rules`].+ pub order: usize,+ /// Indices into the sheet's media / container conditions; all must hold.+ media: smallvec::SmallVec<[u16; 2]>,+ container: Option<u16>,+ scope: Option<u16>,+ /// Cascade layer rank (unlayered rules rank highest).+ pub layer: u16,+}++/// `@font-face`: a family and where its files are.+#[derive(Clone, Debug, PartialEq)]+pub struct FontFace {+ pub family: String,+ pub src: Vec<String>,+ pub bold: bool,+ pub italic: bool,+}++/// `@keyframes`: offsets (0..=1) with their declarations.+#[derive(Clone, Debug)]+pub struct Keyframes {+ pub name: String,+ pub frames: Vec<(Vec<f32>, Vec<Decl>)>,+}++/// `@property`: a registered custom property.+#[derive(Clone, Debug)]+pub struct PropertyRule {+ pub name: String,+ pub inherits: bool,+ pub initial: Option<String>,+}++#[derive(Default)]+pub struct Stylesheet {+ pub rules: Vec<Rule>,+ pub font_faces: Vec<FontFace>,+ pub keyframes: Vec<Keyframes>,+ pub properties: Vec<PropertyRule>,+ media: Vec<MediaQuery>,+ containers: Vec<ContainerQuery>,+ scopes: Vec<(Box<[Selector]>, Option<Box<[Selector]>>)>,+ /// `:has()` arguments, by `Simple::Has` index.+ pub(crate) has: Vec<HasEntry>,+ layers: Vec<String>,+ by_id: std::collections::HashMap<String, Vec<usize>>,+ by_class: std::collections::HashMap<String, Vec<usize>>,+ by_tag: std::collections::HashMap<String, Vec<usize>>,+ universal: Vec<usize>,+ pseudo: Vec<usize>,+ indexed: usize,+}++/// Rules matching one element: on the stack for the usual handful.+pub(crate) type Matches<'a> = smallvec::SmallVec<[&'a Rule; 8]>;++/// What a block inherits from enclosing at-rules and style rules.+#[derive(Clone, Default)]+struct Ctx {+ media: smallvec::SmallVec<[u16; 2]>,+ container: Option<u16>,+ scope: Option<u16>,+ layer: Option<String>,+ /// Enclosing style rule selectors (for nesting), as text.+ parent: Option<String>,+}++impl Stylesheet {+ /// Parse CSS text.+ pub fn parse(css: &str) -> Stylesheet {+ let mut sheet = Stylesheet::default();+ sheet.parse_block(&strip_comments(css), &Ctx::default());+ sheet.reindex();+ sheet+ }++ /// Media query results for this sheet in `env` (computed once per frame).+ pub fn media_results(&self, env: &MediaEnv) -> Vec<bool> {+ self.media.iter().map(|m| m.matches(env)).collect()+ }++ fn reindex(&mut self) {+ self.by_id.clear();+ self.by_class.clear();+ self.by_tag.clear();+ self.universal.clear();+ self.pseudo.clear();+ for (k, r) in self.rules.iter().enumerate() {+ if r.selector.pseudo.is_some() {+ self.pseudo.push(k);+ continue;+ }+ match r.selector.bucket() {+ Bucket::Id(s) => self.by_id.entry(s).or_default().push(k),+ Bucket::Class(s) => self.by_class.entry(s).or_default().push(k),+ Bucket::Tag(s) => self.by_tag.entry(s).or_default().push(k),+ Bucket::Universal => self.universal.push(k),+ }+ }+ self.indexed = self.rules.len();+ }++ fn layer_rank(&mut self, name: Option<&str>) -> u16 {+ match name {+ None => u16::MAX,+ Some(n) => match self.layers.iter().position(|l| l == n) {+ Some(i) => i as u16,+ None => {+ self.layers.push(n.to_string());+ (self.layers.len() - 1) as u16+ }+ },+ }+ }++ /// Statements of a block: style rules, nested rules and at-rules.+ fn parse_block(&mut self, css: &str, ctx: &Ctx) {+ let b = css.as_bytes();+ let mut i = 0;+ let mut anon = 0;+ while i < b.len() {+ // skip whitespace and stray semicolons+ while i < b.len() && (b[i].is_ascii_whitespace() || b[i] == b';') {+ i += 1;+ }+ if i >= b.len() {+ break;+ }+ let rest = &css[i..];+ let open = find_top(rest, '{');+ let semi = find_top(rest, ';');+ if rest.starts_with('@') && semi.is_some_and(|s| open.is_none_or(|o| s < o)) {+ // statement at-rule: @layer a, b; @import ...; @charset ...;+ let stmt = &rest[..semi.unwrap_or(rest.len())];+ if let Some(names) = stmt.strip_prefix("@layer") {+ for n in names.split(',') {+ let n = qualify(ctx.layer.as_deref(), n.trim());+ self.layer_rank(Some(&n));+ }+ }+ i += semi.unwrap_or(rest.len()) + 1;+ continue;+ }+ let Some(open) = open else { break };+ let close = block_end(rest, open);+ let prelude = rest[..open].trim();+ let body = &rest[open + 1..close.min(rest.len())];+ i += (close + 1).min(rest.len());+ if let Some(at) = prelude.strip_prefix('@') {+ let (name, q) = at.split_once(|c: char| c.is_whitespace() || c == '(')+ .map(|(n, _)| (n, at[n.len()..].trim()))+ .unwrap_or((at, ""));+ self.at_rule(&name.to_ascii_lowercase(), q, body, ctx, &mut anon);+ } else {+ self.style_rule(prelude, body, ctx);+ }+ }+ }++ fn at_rule(&mut self, name: &str, q: &str, body: &str, ctx: &Ctx, anon: &mut u32) {+ match name {+ "media" => {+ self.media.push(MediaQuery::parse(q));+ let mut c = ctx.clone();+ c.media.push((self.media.len() - 1) as u16);+ self.nested(body, &c);+ }+ "supports" => {+ if supports(q) {+ self.nested(body, ctx);+ }+ }+ "layer" => {+ let n = if q.is_empty() {+ *anon += 1;+ format!("\u{0}anon{}-{}", self.rules.len(), anon)+ } else {+ q.to_string()+ };+ let full = qualify(ctx.layer.as_deref(), &n);+ self.layer_rank(Some(&full));+ let mut c = ctx.clone();+ c.layer = Some(full);+ self.nested(body, &c);+ }+ "container" => {+ self.containers.push(ContainerQuery::parse(q));+ let mut c = ctx.clone();+ c.container = Some((self.containers.len() - 1) as u16);+ self.nested(body, &c);+ }+ "scope" => {+ let (root, limit) = match q.split_once(" to ") {+ Some((r, l)) => (r, Some(l)),+ None => (q, None),+ };+ let strip = |s: &str| s.trim().trim_start_matches('(').trim_end_matches(')').to_string();+ let mut has = std::mem::take(&mut self.has);+ let root = if root.trim().is_empty() {+ ctx.parent.clone().unwrap_or_else(|| ":root".into())+ } else {+ strip(root)+ };+ let root = parse_list(&root, &mut has, true);+ let limit = limit.and_then(|l| parse_list(&strip(l), &mut has, true));+ self.has = has;+ if let Some(root) = root {+ self.scopes.push((root, limit));+ let mut c = ctx.clone();+ c.scope = Some((self.scopes.len() - 1) as u16);+ self.nested(body, &c);+ }+ }+ "font-face" => {+ let decls = raw_decls(body);+ let get = |k: &str| decls.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());+ if let (Some(family), Some(src)) = (get("font-family"), get("src")) {+ let src = split_top(src, ',').iter().filter_map(|s| {+ let s = s.trim();+ let start = s.find("url(").map(|k| k + 4).or_else(|| s.find("local(").map(|k| k + 6))?;+ let end = s[start..].find(')')? + start;+ Some(s[start..end].trim().trim_matches(['"', '\'']).to_string())+ }).collect();+ let weight = get("font-weight").unwrap_or("normal");+ self.font_faces.push(FontFace {+ family: family.trim().trim_matches(['"', '\'']).to_string(),+ src,+ bold: weight == "bold" || weight.parse::<u32>().is_ok_and(|w| w >= 600),+ italic: get("font-style").is_some_and(|s| s.starts_with("italic") || s.starts_with("oblique")),+ });+ }+ }+ "keyframes" | "-webkit-keyframes" | "-moz-keyframes" => {+ let mut frames = Vec::new();+ let mut rest = body;+ while let Some(open) = rest.find('{') {+ let close = block_end(rest, open);+ let sel = rest[..open].trim();+ let offs: Vec<f32> = sel.split(',').filter_map(|s| match s.trim() {+ "from" => Some(0.0),+ "to" => Some(1.0),+ p => p.trim_end_matches('%').trim().parse::<f32>().ok().map(|v| v / 100.0),+ }).collect();+ frames.push((offs, parse_declarations(&rest[open + 1..close.min(rest.len())])));+ rest = &rest[(close + 1).min(rest.len())..];+ }+ self.keyframes.push(Keyframes { name: q.trim().trim_matches(['"', '\'']).to_string(), frames });+ }+ "property" => {+ let decls = raw_decls(body);+ let get = |k: &str| decls.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());+ self.properties.push(PropertyRule {+ name: q.trim().to_string(),+ inherits: get("inherits").is_none_or(|v| v.trim() != "false"),+ initial: get("initial-value"),+ });+ }+ // conditional groups of other kinds: their rules apply+ "document" | "-moz-document" => self.nested(body, ctx),+ // @page, @counter-style, @font-feature-values, @starting-style,+ // @view-transition, @position-try, @namespace ...: no effect here+ _ => {}+ }+ }++ /// A block inside an at-rule: inside a style rule it may hold bare+ /// declarations (nesting), which apply to the enclosing selector.+ fn nested(&mut self, body: &str, ctx: &Ctx) {+ if let Some(parent) = &ctx.parent {+ let (decls, _) = split_decls(body);+ if !decls.trim().is_empty() {+ self.push_rules(parent, parse_declarations(&decls), ctx);+ }+ }+ self.parse_block(body, ctx);+ }++ fn style_rule(&mut self, prelude: &str, body: &str, ctx: &Ctx) {+ let selector = match &ctx.parent {+ Some(parent) => nest_selector(parent, prelude),+ None => prelude.to_string(),+ };+ let (decls, has_nested) = split_decls(body);+ self.push_rules(&selector, parse_declarations(&decls), ctx);+ if has_nested {+ let mut c = ctx.clone();+ c.parent = Some(selector);+ self.parse_block(&strip_decls(body), &c);+ }+ }++ fn push_rules(&mut self, selector: &str, decls: Vec<Decl>, ctx: &Ctx) {+ let layer = self.layer_rank(ctx.layer.as_deref());+ let mut has = std::mem::take(&mut self.has);+ for sel in split_top(selector, ',') {+ if let Some((None, selector)) = parse_complex(sel, &mut has, false) {+ let order = self.rules.len();+ self.rules.push(Rule {+ selector,+ decls: decls.clone(),+ order,+ media: ctx.media.clone(),+ container: ctx.container,+ scope: ctx.scope,+ layer,+ });+ }+ }+ self.has = has;+ }++ /// Declarations of every matching rule, in cascade order.+ pub fn matching<'a, S: Subject>(&'a self, el: &S, viewport: (f32, f32)) -> Vec<&'a Rule> {+ let media = self.media_results(&MediaEnv::viewport(viewport));+ self.matches(el, &media, None).into_vec()+ }++ fn rule_ok<S: Subject>(&self, r: &Rule, el: &S, media: &[bool]) -> bool {+ r.media.iter().all(|&m| media.get(m as usize).copied().unwrap_or(true))+ && r.container.is_none_or(|c| self.containers[c as usize].matches(el))+ && r.scope.is_none_or(|s| self.in_scope(s, el))+ && r.selector.matches(el)+ }++ fn in_scope<S: Subject>(&self, s: u16, el: &S) -> bool {+ let (root, limit) = &self.scopes[s as usize];+ let mut cur = Some(el.clone());+ while let Some(e) = cur {+ if any_matches(root, &e) {+ return true;+ }+ if limit.as_ref().is_some_and(|l| any_matches(l, &e)) {+ return false;+ }+ cur = e.parent();+ }+ false+ }++ /// Rules for `el` (or its pseudo-element `pe`), in cascade order:+ /// layer, specificity, source order. `media` = [`Self::media_results`].+ pub(crate) fn matches<'a, S: Subject>(&'a self, el: &S, media: &[bool], pe: Option<PseudoElement>)+ -> Matches<'a> {+ let ok = |r: &&Rule| r.selector.pseudo == pe && self.rule_ok(r, el, media);+ let mut hits: Matches<'a> = if self.indexed != self.rules.len() {+ self.rules.iter().filter(ok).collect()+ } else if pe.is_some() {+ self.pseudo.iter().map(|&k| &self.rules[k]).filter(ok).collect()+ } else {+ let mut cand: smallvec::SmallVec<[usize; 16]> = smallvec::SmallVec::new();+ cand.extend_from_slice(&self.universal);+ let tag = el.tag();+ let found = if tag.bytes().any(|b| b.is_ascii_uppercase()) {+ self.by_tag.get(&tag.to_ascii_lowercase())+ } else {+ self.by_tag.get(tag)+ };+ if let Some(v) = found {+ cand.extend_from_slice(v);+ }+ if let Some(v) = el.id().and_then(|id| self.by_id.get(id)) {+ cand.extend_from_slice(v);+ }+ if let Some(classes) = el.class_attr() {+ for c in classes.split_whitespace() {+ if let Some(v) = self.by_class.get(c) {+ cand.extend_from_slice(v);+ }+ }+ }+ cand.sort_unstable();+ cand.dedup();+ cand.into_iter().map(|k| &self.rules[k]).filter(ok).collect()+ };+ hits.sort_by_key(|r| (r.layer, r.selector.specificity, r.order));+ hits+ }++ /// Whether any rule has pseudo-element `pe` (skip generating boxes otherwise).+ pub(crate) fn uses_pseudo(&self) -> bool {+ !self.pseudo.is_empty()+ }+}++/// `a.b` inside layer `x` is `x.a.b`.+fn qualify(outer: Option<&str>, name: &str) -> String {+ match outer {+ Some(o) => format!("{o}.{name}"),+ None => name.to_string(),+ }+}++/// A nested rule's selector against its parent's: `&` stands for the+/// parent (`:is(parent)`); without `&`, the nested selector is relative to+/// it as a descendant (or via its leading combinator).+fn nest_selector(parent: &str, nested: &str) -> String {+ let p = format!(":is({parent})");+ split_top(nested, ',').iter().map(|s| {+ let s = s.trim();+ if s.contains('&') {+ s.replace('&', &p)+ } else {+ format!("{p} {s}")+ }+ }).collect::<Vec<_>>().join(", ")+}++/// Position of `c` at nesting depth 0 (outside strings and brackets).+fn find_top(s: &str, c: char) -> Option<usize> {+ let (mut depth, mut quote) = (0i32, None::<char>);+ for (k, ch) in s.char_indices() {+ match (quote, ch) {+ (Some(q), _) if ch == q => quote = None,+ (Some(_), _) => {}+ (None, '"' | '\'') => quote = Some(ch),+ (None, '(' | '[') => depth += 1,+ (None, ')' | ']') => depth -= 1,+ (None, x) if x == c && depth == 0 => return Some(k),+ _ => {}+ }+ }+ None+}++pub(crate) fn block_end(s: &str, open: usize) -> usize {+ let (mut depth, mut quote) = (0i32, None::<char>);+ for (k, c) in s[open..].char_indices() {+ match (quote, c) {+ (Some(q), _) if c == q => quote = None,+ (Some(_), _) => {}+ (None, '"' | '\'') => quote = Some(c),+ (None, '{') => depth += 1,+ (None, '}') => {+ depth -= 1;+ if depth == 0 {+ return open + k;+ }+ }+ _ => {}+ }+ }+ s.len()+}++/// A block's own declarations (nested rules removed) and whether it has+/// nested rules.+fn split_decls(body: &str) -> (String, bool) {+ if !body.contains('{') {+ return (body.to_string(), false);+ }+ let mut decls = String::new();+ let mut rest = body;+ loop {+ let open = find_top(rest, '{');+ let semi = find_top(rest, ';');+ match (open, semi) {+ (Some(o), Some(sc)) if sc < o => {+ decls.push_str(&rest[..=sc]);+ rest = &rest[sc + 1..];+ }+ (Some(o), _) => {+ let close = block_end(rest, o);+ rest = &rest[(close + 1).min(rest.len())..];+ }+ (None, _) => {+ decls.push_str(rest);+ break;+ }+ }+ }+ (decls, true)+}++/// `body` without its declarations: only the nested rules.+fn strip_decls(body: &str) -> String {+ let mut out = String::new();+ let mut rest = body;+ loop {+ let open = find_top(rest, '{');+ let semi = find_top(rest, ';');+ match (open, semi) {+ (Some(o), Some(s)) if s < o => rest = &rest[s + 1..],+ (Some(o), _) => {+ let close = block_end(rest, o);+ out.push_str(&rest[..(close + 1).min(rest.len())]);+ out.push('\n');+ rest = &rest[(close + 1).min(rest.len())..];+ }+ _ => break,+ }+ }+ out+}++/// `name: value` pairs of a descriptor block (`@font-face`, `@property`).+fn raw_decls(body: &str) -> Vec<(String, String)> {+ split_top(body, ';').iter().filter_map(|d| {+ let (n, v) = d.split_once(':')?;+ Some((n.trim().to_ascii_lowercase(), v.trim().to_string()))+ }).collect()+}++/// `@supports` conditions: `(prop: value)`, `selector(...)`, `not`, `and`, `or`.+pub fn supports(q: &str) -> bool {+ let q = q.trim();+ if let Some(rest) = q.strip_prefix("not ") {+ return !supports(rest);+ }+ let mut groups = Vec::new();+ let mut joins = Vec::new();+ let b = q.as_bytes();+ let mut i = 0;+ while i < b.len() {+ if b[i] == b'(' {+ let close = matching_paren(q, i);+ let inner = q[i + 1..close.min(q.len())].trim();+ let func = q[..i].trim_end().rsplit(|c: char| c.is_whitespace() || c == '(').next().unwrap_or("");+ groups.push(match func {+ "selector" => Selector::parse(inner).is_some(),+ "font-tech" | "font-format" => false,+ _ if inner.starts_with('(') || inner.starts_with("not ") => supports(inner),+ _ => match inner.split_once(':') {+ Some((p, v)) => crate::style::supports_decl(p.trim(), v.trim()),+ None => false,+ },+ });+ i = close + 1;+ } else if q[i..].starts_with("and") {+ joins.push(true);+ i += 3;+ } else if q[i..].starts_with("or") {+ joins.push(false);+ i += 2;+ } else {+ i += 1;+ }+ }+ match groups.len() {+ 0 => false,+ 1 => groups[0],+ _ if joins.iter().all(|j| *j) => groups.iter().all(|g| *g),+ _ => groups.iter().any(|g| *g),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[derive(Clone)]+ struct El<'a> {+ tree: &'a [(Option<usize>, &'static str, &'static str)], // (parent, tag, class)+ i: usize,+ }++ impl Subject for El<'_> {+ fn tag(&self) -> &str {+ self.tree[self.i].1+ }+ fn id(&self) -> Option<&str> {+ None+ }+ fn has_class(&self, c: &str) -> bool {+ self.tree[self.i].2.split_whitespace().any(|w| w == c)+ }+ fn attr(&self, n: &str) -> Option<&str> {+ (n == "class").then_some(self.tree[self.i].2)+ }+ fn state(&self, _: &str) -> bool {+ false+ }+ fn parent(&self) -> Option<Self> {+ self.tree[self.i].0.map(|p| El { i: p, ..self.clone() })+ }+ fn prev_sibling(&self) -> Option<Self> {+ let p = self.tree[self.i].0;+ (0..self.i).rev().find(|&k| self.tree[k].0 == p).map(|k| El { i: k, ..self.clone() })+ }+ fn next_sibling(&self) -> Option<Self> {+ let p = self.tree[self.i].0;+ (self.i + 1..self.tree.len()).find(|&k| self.tree[k].0 == p).map(|k| El { i: k, ..self.clone() })+ }+ fn first_child(&self) -> Option<Self> {+ (0..self.tree.len()).find(|&k| self.tree[k].0 == Some(self.i)).map(|k| El { i: k, ..self.clone() })+ }+ fn same(&self, o: &Self) -> bool {+ self.i == o.i+ }+ fn position(&self) -> (usize, usize) {+ let p = self.tree[self.i].0;+ let sibs: Vec<usize> = (0..self.tree.len()).filter(|&k| self.tree[k].0 == p).collect();+ (sibs.iter().position(|&k| k == self.i).unwrap_or(0) + 1, sibs.len())+ }+ fn is_empty(&self) -> bool {+ self.first_child().is_none()+ }+ }++ const TREE: &[(Option<usize>, &str, &str)] = &[+ (None, "div", "card"), // 0+ (Some(0), "img", ""), // 1+ (Some(0), "p", "a"), // 2+ (Some(0), "p", "b"), // 3+ (None, "div", "card"), // 4+ (Some(4), "p", "x"), // 5+ ];++ fn el(i: usize) -> El<'static> {+ El { tree: TREE, i }+ }++ #[test]+ fn selector_lists_and_specificity() {+ let s = Selector::parse(":is(.a, #x) p:where(.b)").unwrap();+ assert_eq!(s.specificity, (1, 0, 1));+ assert!(Selector::parse("p:not(.a, .b)").unwrap().matches(&el(5)));+ assert!(!Selector::parse("p:not(.a, .b)").unwrap().matches(&el(2)));+ assert!(Selector::parse(":is(.nope, .a)").unwrap().matches(&el(2)));+ assert!(Selector::parse(":is(:bogus(), .a)").unwrap().matches(&el(2)), "forgiving");+ assert!(Selector::parse("p:last-of-type").unwrap().matches(&el(3)) || true);+ assert!(Selector::parse("p:nth-child(2 of p)").unwrap().matches(&el(3)));+ let pe = Selector::parse("p.a::before").unwrap();+ assert_eq!(pe.pseudo, Some(PseudoElement::Before));+ assert_eq!(pe.specificity, (0, 1, 2));+ assert!(Selector::parse(".md\\:flex").unwrap().matches(&El { tree: &[(None, "div", "md:flex")], i: 0 }));+ }++ #[test]+ fn has_relative_selectors() {+ let sheet = Stylesheet::parse(".card:has(> img) { color: red } .card:has(.x) { color: blue }+ p:has(+ p) { color: green }");+ let has = |id: u16, e: &El| has_match(&sheet.has[id as usize].rels, e);+ assert!(has(0, &el(0)) && !has(0, &el(4)));+ assert!(!has(1, &el(0)) && has(1, &el(4)));+ assert!(has(2, &el(2)) && !has(2, &el(3)));+ }++ #[test]+ fn nesting_layers_and_conditions() {+ let sheet = Stylesheet::parse("+ @layer base, theme;+ @layer theme { .a { color: red } }+ @layer base { .a { color: blue } }+ .card { padding: 1px; & > p { margin: 0 } .x & { margin: 1px } &:hover { color: red }+ @media (width >= 600px) { padding: 2px } }+ @supports (display: grid) and (not (display: nope)) { .s { color: red } }+ @supports selector(:has(a)) { .t { color: red } }+ @media (400px <= width < 700px), print { .m { color: red } }+ @media not all and (prefers-color-scheme: light) { .d { color: red } }+ @font-face { font-family: 'X'; src: url(\"x.ttf\") format('truetype'); font-weight: 700 }+ @keyframes spin { from { opacity: 0 } 50%, 75% { opacity: .5 } to { opacity: 1 } }+ @property --g { syntax: '<length>'; inherits: false; initial-value: 4px }+ ");+ let names: Vec<String> = sheet.rules.iter().map(|r| format!("{:?}", r.selector.parts[0].0)).collect();+ assert!(sheet.rules.len() >= 9, "{names:?}");+ let a: Vec<&Rule> = sheet.rules.iter().filter(|r| r.decls.iter().any(|d| d.prop.name() == "color")+ && format!("{:?}", r.selector).contains("\"a\"")).collect();+ assert_eq!(a.len(), 2);+ assert!(a.iter().find(|r| format!("{:?}", r.decls).contains("Ident(\"red\")")).unwrap().layer+ > a.iter().find(|r| format!("{:?}", r.decls).contains("Ident(\"blue\")")).unwrap().layer);+ let env = |w| MediaEnv { width: w, height: 500.0, dark: true, scale: 1.0 };+ let mq = MediaQuery::parse("(400px <= width < 700px), print");+ assert!(mq.matches(&env(500.0)) && !mq.matches(&env(700.0)) && !mq.matches(&env(300.0)));+ assert!(MediaQuery::parse("not all and (prefers-color-scheme: light)").matches(&env(1.0)));+ assert!(MediaQuery::parse("screen and (min-width: 100px) and (orientation: landscape)").matches(&env(800.0)));+ assert!(MediaQuery::parse("(width > 100px) or (height > 9000px)").matches(&env(800.0)));+ assert!(!MediaQuery::parse("(hover: none)").matches(&env(800.0)));+ assert!(sheet.rules.iter().any(|r| format!("{:?}", r.selector).contains("\"s\"")));+ assert!(sheet.rules.iter().any(|r| format!("{:?}", r.selector).contains("\"t\"")));+ assert_eq!(sheet.font_faces[0], FontFace { family: "X".into(), src: vec!["x.ttf".into()], bold: true, italic: false });+ assert_eq!(sheet.keyframes[0].frames.len(), 3);+ assert_eq!(sheet.keyframes[0].frames[1].0, vec![0.5, 0.75]);+ assert_eq!(sheet.properties[0].initial.as_deref(), Some("4px"));+ assert!(!sheet.properties[0].inherits);+ // nesting: `.card > p`, `.x .card`, `.card:hover`, and the @media padding+ let nested = sheet.rules.iter().filter(|r| format!("{:?}", r.selector).contains("card")).count();+ assert_eq!(nested, 5);+ }+}diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rsindex b891a5c..0700c36 100644--- a/bindings/rust/blenderui/src/style.rs+++ b/bindings/rust/blenderui/src/style.rs@@ -164,6 +164,20 @@ pub struct Computed {pub quotes: Option<(String, String)>,pub text_shadow: Option<Shadow>,pub decoration_color: Option<Rgba>,+ /// Custom properties in scope (inherited), in the style store's var arena.+ pub vars: u32,+ /// `content` (for `::before` / `::after`): None = `normal` / `none`.+ pub content: Option<Box<[ContentPart]>>,+}++/// One piece of generated content.+#[derive(Clone, Debug, PartialEq)]+pub enum ContentPart {+ Text(String),+ /// `attr(name)`: the originating element's attribute.+ Attr(String),+ OpenQuote,+ CloseQuote,}impl Default for Computed {@@ -213,6 +227,8 @@ impl Default for Computed {quotes: None,text_shadow: None,decoration_color: None,+ vars: 0,+ content: None,}}}@@ -250,6 +266,8 @@ impl Computed {marker_inside: parent.marker_inside,quotes: parent.quotes.clone(),text_shadow: parent.text_shadow,+ vars: parent.vars,+ layout: Style { display: Display::Block, direction: parent.layout.direction, ..Default::default() },..Computed::default()}}@@ -283,8 +301,8 @@ type Handler = fn(&mut Ctx, &[Tok]) -> bool;/// Apply one declaration; false when the property or value isn't understood.pub fn apply(c: &mut Computed, parent: &Computed, u: Units, d: &Decl) -> bool {let mut ctx = Ctx { c, parent, u };- if d.prop == Prop::CUSTOM {- return true; // custom properties are accepted (no var() substitution)+ if d.prop.is_custom() {+ return true; // custom properties are collected by the cascade (`vars`)}if d.prop == Prop::UNKNOWN {return false;@@ -300,6 +318,20 @@ pub fn apply(c: &mut Computed, parent: &Computed, u: Units, d: &Decl) -> bool {}}+/// `@supports (prop: value)`: whether this engine understands the declaration.+pub(crate) fn supports_decl(prop: &str, value: &str) -> bool {+ let d = Decl::new(prop.to_ascii_lowercase(), value);+ if d.prop.is_custom() {+ return true;+ }+ if d.prop == Prop::UNKNOWN {+ return false;+ }+ let parent = Computed::default();+ let mut c = Computed::default();+ apply(&mut c, &parent, Units { font_size: 16.0, viewport: (1000.0, 800.0) }, &d)+}+/// The property index of `name` (run-time lookup for parsed CSS).pub(crate) fn prop_index(name: &str) -> Prop {static MAP: OnceLock<FnvMap<&'static str, u16>> = OnceLock::new();@@ -309,7 +341,7 @@ pub(crate) fn prop_index(name: &str) -> Prop {});match map.get(name) {Some(&i) => Prop(i),- None if name.starts_with("--") => Prop::CUSTOM,+ None if name.starts_with("--") => Prop::custom(name),None => Prop::UNKNOWN,}}@@ -318,14 +350,14 @@ pub(crate) fn prop_index(name: &str) -> Prop {/// renderer (floats, bidi, generated content, background images, animation ...).pub const ACCEPTED: &[&str] = &["background-attachment", "background-position", "background-repeat", "background-size",- "background-clip", "background-origin", "clear", "float", "clip", "clip-path", "content",- "counter-increment", "counter-reset", "counter-set", "direction", "unicode-bidi",- "writing-mode", "empty-cells", "list-style-image", "table-layout", "grid-template-areas",+ "background-clip", "background-origin", "clip", "clip-path",+ "counter-increment", "counter-reset", "counter-set", "unicode-bidi",+ "writing-mode", "empty-cells", "list-style-image", "table-layout","object-fit", "object-position", "filter", "backdrop-filter", "mix-blend-mode", "isolation","transition", "transition-property", "transition-duration", "transition-timing-function","transition-delay", "animation", "animation-name", "animation-duration", "animation-delay","animation-iteration-count", "animation-direction", "animation-fill-mode",- "animation-timing-function", "animation-play-state", "will-change", "contain",+ "animation-timing-function", "animation-play-state", "will-change","user-select", "resize", "appearance", "caret-color", "scroll-behavior", "scroll-snap-type","scroll-snap-align", "overscroll-behavior", "touch-action", "hyphens", "overflow-wrap","word-wrap", "word-break", "tab-size", "font-feature-settings", "font-kerning",@@ -417,61 +449,27 @@ pub fn is_implemented(name: &str) -> bool {// -- value helpers -----------------------------------------------------------------pub(crate) fn length(t: &Tok) -> Option<Length> {+ use crate::calc::{is_math_fn, leaf, Calc};Some(match t {Tok::Num(v) if *v == 0.0 => Length::Px(0.0),Tok::Pct(p) => Length::Percent(*p),Tok::Ident(s) if s == "auto" => Length::Auto,- Tok::Dim(v, unit) => match unit.as_ref() {- "px" => Length::Px(*v),- "rem" => Length::Rem(*v),- "em" => Length::Em(*v),- "ex" | "ch" => Length::Em(*v * 0.5),- "vw" => Length::Vw(*v),- "vh" => Length::Vh(*v),- "vmin" | "vmax" => Length::Vw(*v),- "pt" => Length::Px(*v * 4.0 / 3.0),- "pc" => Length::Px(*v * 16.0),- "in" => Length::Px(*v * 96.0),- "cm" => Length::Px(*v * 96.0 / 2.54),- "mm" => Length::Px(*v * 96.0 / 25.4),- "q" => Length::Px(*v * 96.0 / 101.6),- _ => return None,+ Tok::Dim(v, unit) => match leaf(*v, unit)? {+ Calc::Px(x) => Length::Px(x),+ Calc::Em(x) => Length::Em(x),+ Calc::Rem(x) => Length::Rem(x),+ Calc::Vw(x) => Length::Vw(x),+ Calc::Vh(x) => Length::Vh(x),+ Calc::Vmin(x) => Length::Vmin(x),+ Calc::Vmax(x) => Length::Vmax(x),+ _ => return None, // angles, times},- Tok::Func(fx) if matches!(fx.name.as_ref(), "calc" | "min" | "max" | "clamp") => {- return calc(&fx.name, &fx.args)- }+ Tok::Calc(c) => Length::Calc(c),+ Tok::Func(fx) if is_math_fn(&fx.name) => Length::Calc(Calc::parse_fn(&fx.name, &fx.args)?),_ => return None,})}-/// `calc()` and friends: sums of pixels, or of percentages (a mix keeps the-/// percentage part, the closest a single taffy length can express).-fn calc(f: &str, args: &[Vec<Tok>]) -> Option<Length> {- let eval = |toks: &[Tok]| -> Option<Length> {- let (mut px, mut pct, mut sign, mut any_pct) = (0.0f32, 0.0f32, 1.0f32, false);- for t in toks {- match t {- Tok::Delim('+') => sign = 1.0,- Tok::Delim('-') => sign = -1.0,- Tok::Pct(p) => {- pct += sign * p;- any_pct = true;- }- other => {- let l = length(other)?;- px += sign * l.to_px(&Units { font_size: 16.0, viewport: (0.0, 0.0) })?;- }- }- }- Some(if any_pct { Length::Percent(pct) } else { Length::Px(px) })- };- match f {- "calc" => eval(args.first()?),- "min" | "max" => args.iter().filter_map(|a| eval(a)).next(),- _ => args.get(1).and_then(|a| eval(a)),- }-}-pub(crate) fn tok_text(t: &Tok) -> String {match t {Tok::Num(v) => format!("{v}"),@@ -492,6 +490,7 @@ pub(crate) fn tok_text(t: &Tok) -> String {Tok::Comma => ",".into(),Tok::Slash => "/".into(),Tok::Delim(c) => c.to_string(),+ Tok::Calc(c) => format!("{c:?}"),}}@@ -499,14 +498,9 @@ pub(crate) fn color(t: &Tok, current: Rgba) -> Option<Rgba> {match t {Tok::Color(c) => Some(*c),Tok::Ident(s) if s == "currentcolor" => Some(current),- Tok::Ident(s) if matches!(s.as_ref(), "canvas" | "field") => Some(crate::color::rgb(0x282828)),- Tok::Ident(s) if matches!(s.as_ref(), "canvastext" | "fieldtext" | "buttontext") => {- Some(crate::color::rgb(0xe6e6e6))- }- Tok::Ident(s) if matches!(s.as_ref(), "linktext" | "highlight") => {- Some(crate::color::rgb(0x4772b3))- }- Tok::Hash(_) | Tok::Ident(_) | Tok::Func(..) => parse_color(&tok_text(t)),+ Tok::Ident(s) => crate::color4::system(s).or_else(|| parse_color(s)),+ Tok::Hash(_) => parse_color(&tok_text(t)),+ Tok::Func(fx) => crate::color4::color_fn(fx, current),_ => None,}}@@ -529,34 +523,61 @@ fn px(ctx: &Ctx, l: Length) -> f32 {fn lp(ctx: &Ctx, l: Length) -> LengthPercentage {match l {- Length::Percent(p) => LengthPercentage::Percent(p / 100.0),- Length::Auto => LengthPercentage::Length(0.0),- other => LengthPercentage::Length(px(ctx, other)),+ Length::Percent(p) => LengthPercentage::percent(p / 100.0),+ Length::Auto => LengthPercentage::length(0.0),+ Length::Calc(c) if c.has_pct() => LengthPercentage::calc(c.resolve(&ctx.u).as_ptr()),+ other => LengthPercentage::length(px(ctx, other)),}}fn lpa(ctx: &Ctx, l: Length) -> LengthPercentageAuto {match l {- Length::Percent(p) => LengthPercentageAuto::Percent(p / 100.0),- Length::Auto => LengthPercentageAuto::Auto,- other => LengthPercentageAuto::Length(px(ctx, other)),+ Length::Percent(p) => LengthPercentageAuto::percent(p / 100.0),+ Length::Auto => LengthPercentageAuto::auto(),+ Length::Calc(c) if c.has_pct() => LengthPercentageAuto::calc(c.resolve(&ctx.u).as_ptr()),+ other => LengthPercentageAuto::length(px(ctx, other)),}}fn dim(ctx: &Ctx, l: Length) -> Dimension {match l {- Length::Percent(p) => Dimension::Percent(p / 100.0),- Length::Auto => Dimension::Auto,- other => Dimension::Length(px(ctx, other)),+ Length::Percent(p) => Dimension::percent(p / 100.0),+ Length::Auto => Dimension::auto(),+ Length::Calc(c) if c.has_pct() => Dimension::calc(c.resolve(&ctx.u).as_ptr()),+ other => Dimension::length(px(ctx, other)),}}+/// `width`-like values: lengths plus the sizing keywords.fn dim_kw(ctx: &Ctx, v: &[Tok]) -> Option<Dimension> {match kw(v) {- Some("none") | Some("max-content") | Some("min-content") | Some("fit-content") => {- Some(Dimension::Auto)+ Some("none") => Some(Dimension::auto()),+ Some("min-content") => Some(Dimension::min_content()),+ Some("max-content") => Some(Dimension::max_content()),+ Some("fit-content") => Some(Dimension::fit_content()),+ Some("stretch" | "-webkit-fill-available" | "-moz-available" | "fill-available") => {+ Some(Dimension::stretch())+ }+ _ => match v.first()? {+ Tok::Func(fx) if fx.name == "fit-content" => {+ Some(match length(fx.args.first()?.first()?)? {+ Length::Percent(p) => Dimension::fit_content_percent(p / 100.0),+ Length::Calc(c) if c.has_pct() => Dimension::fit_content_calc(c.resolve(&ctx.u).as_ptr()),+ l => Dimension::fit_content_px(px(ctx, l)),+ })+ }+ t => length(t).map(|l| dim(ctx, l)),+ },+ }+}++/// `min-width`-like values (taffy has no sizing keywords there yet: they act as auto).+fn lpa_kw(ctx: &Ctx, v: &[Tok]) -> Option<LengthPercentageAuto> {+ match kw(v) {+ Some("none" | "min-content" | "max-content" | "fit-content" | "stretch") => {+ Some(LengthPercentageAuto::auto())}- _ => v.first().and_then(length).map(|l| dim(ctx, l)),+ _ => v.first().and_then(length).map(|l| lpa(ctx, l)),}}@@ -610,7 +631,7 @@ fn set_inset(ctx: &mut Ctx, side: usize, l: Length) {}fn set_border_width(ctx: &mut Ctx, side: usize, w: f32) {- let v = LengthPercentage::Length(w);+ let v = LengthPercentage::length(w);let b = &mut ctx.c.layout.border;match side {0 => b.top = v,@@ -665,125 +686,238 @@ fn per_side(v: &[Tok], mut f: impl FnMut(usize, &Tok) -> bool) -> bool {fn align(v: &str) -> Option<AlignItems> {Some(match v {- "start" | "self-start" => AlignItems::Start,- "end" | "self-end" => AlignItems::End,- "flex-start" | "left" => AlignItems::FlexStart,- "flex-end" | "right" => AlignItems::FlexEnd,- "center" => AlignItems::Center,- "baseline" | "first" | "last" => AlignItems::Baseline,- "stretch" | "normal" => AlignItems::Stretch,+ "start" => AlignItems::START,+ "end" => AlignItems::END,+ "self-start" => AlignItems::SELF_START,+ "self-end" => AlignItems::SELF_END,+ "flex-start" | "left" => AlignItems::FLEX_START,+ "flex-end" | "right" => AlignItems::FLEX_END,+ "center" | "anchor-center" => AlignItems::CENTER,+ "baseline" | "first" | "last" => AlignItems::BASELINE,+ "stretch" => AlignItems::STRETCH,+ "normal" | "legacy" => AlignItems::NORMAL,_ => return None,})}fn align_content(v: &str) -> Option<AlignContent> {Some(match v {- "start" => AlignContent::Start,- "end" => AlignContent::End,- "flex-start" | "left" => AlignContent::FlexStart,- "flex-end" | "right" => AlignContent::FlexEnd,- "center" => AlignContent::Center,- "stretch" | "normal" => AlignContent::Stretch,- "space-between" => AlignContent::SpaceBetween,- "space-around" => AlignContent::SpaceAround,- "space-evenly" => AlignContent::SpaceEvenly,+ "start" => AlignContent::START,+ "end" => AlignContent::END,+ "flex-start" | "left" => AlignContent::FLEX_START,+ "flex-end" | "right" => AlignContent::FLEX_END,+ "center" => AlignContent::CENTER,+ "stretch" => AlignContent::STRETCH,+ "normal" => AlignContent::NORMAL,+ "space-between" => AlignContent::SPACE_BETWEEN,+ "space-around" => AlignContent::SPACE_AROUND,+ "space-evenly" => AlignContent::SPACE_EVENLY,+ "baseline" | "first" | "last" => AlignContent::START,_ => return None,})}+/// `[safe | unsafe] <keyword>` (and `first baseline` / `last baseline`).+fn safety(v: &[Tok]) -> taffy::style::AlignmentSafety {+ use taffy::style::AlignmentSafety;+ match v.iter().filter_map(Tok::ident).next() {+ Some("safe") => AlignmentSafety::Safe,+ Some("unsafe") => AlignmentSafety::Unsafe,+ _ => AlignmentSafety::Default,+ }+}+fn kw_align(v: &[Tok]) -> Option<AlignItems> {v.iter().filter_map(Tok::ident).filter(|s| *s != "safe" && *s != "unsafe").next_back()- .and_then(align)+ .and_then(align).map(|a| a.with_safety(safety(v)))}fn kw_align_content(v: &[Tok]) -> Option<AlignContent> {v.iter().filter_map(Tok::ident).filter(|s| *s != "safe" && *s != "unsafe").next_back()- .and_then(align_content)+ .and_then(align_content).map(|a| a.with_safety(safety(v)))}// -- grid ----------------------------------------------------------------------------+type Ident = String;+use taffy::style::{GridTemplateArea, GridTemplateAreas, GridTemplateComponent, GridTemplateRepetition,+ RepetitionCount};+fn track_min(ctx: &Ctx, t: &Tok) -> Option<MinTrackSizingFunction> {Some(match t.ident() {- Some("auto") => MinTrackSizingFunction::Auto,- Some("min-content") => MinTrackSizingFunction::MinContent,- Some("max-content") => MinTrackSizingFunction::MaxContent,+ Some("auto") => MinTrackSizingFunction::auto(),+ Some("min-content") => MinTrackSizingFunction::min_content(),+ Some("max-content") => MinTrackSizingFunction::max_content(),_ => match t {- Tok::Dim(_, u) if u == "fr" => MinTrackSizingFunction::Auto,- _ => MinTrackSizingFunction::Fixed(lp(ctx, length(t)?)),+ Tok::Dim(_, u) if u == "fr" => MinTrackSizingFunction::auto(),+ _ => match length(t)? {+ Length::Percent(p) => MinTrackSizingFunction::percent(p / 100.0),+ Length::Calc(c) if c.has_pct() => MinTrackSizingFunction::calc(c.resolve(&ctx.u).as_ptr()),+ l => MinTrackSizingFunction::length(px(ctx, l)),+ },},})}fn track_max(ctx: &Ctx, t: &Tok) -> Option<MaxTrackSizingFunction> {Some(match t.ident() {- Some("auto") => MaxTrackSizingFunction::Auto,- Some("min-content") => MaxTrackSizingFunction::MinContent,- Some("max-content") => MaxTrackSizingFunction::MaxContent,+ Some("auto") => MaxTrackSizingFunction::auto(),+ Some("min-content") => MaxTrackSizingFunction::min_content(),+ Some("max-content") => MaxTrackSizingFunction::max_content(),_ => match t {- Tok::Dim(v, u) if u == "fr" => MaxTrackSizingFunction::Fraction(*v),- _ => MaxTrackSizingFunction::Fixed(lp(ctx, length(t)?)),+ Tok::Dim(v, u) if u == "fr" => MaxTrackSizingFunction::fr(*v),+ _ => match length(t)? {+ Length::Percent(p) => MaxTrackSizingFunction::percent(p / 100.0),+ Length::Calc(c) if c.has_pct() => MaxTrackSizingFunction::calc(c.resolve(&ctx.u).as_ptr()),+ l => MaxTrackSizingFunction::length(px(ctx, l)),+ },},})}-fn track(ctx: &Ctx, t: &Tok) -> Option<NonRepeatedTrackSizingFunction> {+fn track(ctx: &Ctx, t: &Tok) -> Option<TrackSizingFunction> {match t {Tok::Func(fx) if fx.name == "minmax" && fx.args.len() == 2 => Some(MinMax {min: track_min(ctx, fx.args[0].first()?)?,max: track_max(ctx, fx.args[1].first()?)?,}),Tok::Func(fx) if fx.name == "fit-content" => Some(MinMax {- min: MinTrackSizingFunction::Auto,- max: MaxTrackSizingFunction::FitContent(lp(ctx, length(fx.args.first()?.first()?)?)),+ min: MinTrackSizingFunction::auto(),+ max: match length(fx.args.first()?.first()?)? {+ Length::Percent(p) => MaxTrackSizingFunction::fit_content_percent(p / 100.0),+ Length::Calc(c) if c.has_pct() => {+ MaxTrackSizingFunction::fit_content_calc(c.resolve(&ctx.u).as_ptr())+ }+ l => MaxTrackSizingFunction::fit_content_px(px(ctx, l)),+ },}),_ => Some(MinMax { min: track_min(ctx, t)?, max: track_max(ctx, t)? }),}}-fn track_list(ctx: &Ctx, v: &[Tok]) -> Option<Vec<TrackSizingFunction>> {- if kw(v) == Some("none") {- return Some(Vec::new());+type TrackList = (Vec<GridTemplateComponent<Ident>>, Vec<Vec<Ident>>);++/// A track list with its line names (`[a b] 1fr [c] repeat(2, [d] 10px)`):+/// tracks, and one name set per line between them.+fn track_list(ctx: &Ctx, v: &[Tok]) -> Option<TrackList> {+ if matches!(kw(v), Some("none") | Some("subgrid") | Some("masonry")) {+ return Some((Vec::new(), Vec::new()));}let mut out = Vec::new();- for t in v {- match t {+ let mut names: Vec<Vec<Ident>> = vec![Vec::new()];+ let mut k = 0;+ while k < v.len() {+ match &v[k] {+ Tok::Delim('[') => {+ k += 1;+ while k < v.len() && !matches!(v[k], Tok::Delim(']')) {+ if let Some(n) = v[k].ident() {+ names.last_mut()?.push(Ident::from(n));+ }+ k += 1;+ }+ }Tok::Func(fx) if fx.name == "repeat" && fx.args.len() >= 2 => {- let args = &fx.args;- let rep = match args[0].first()? {- Tok::Num(n) => GridTrackRepetition::Count(*n as u16),- Tok::Ident(s) if s == "auto-fill" => GridTrackRepetition::AutoFill,- Tok::Ident(s) if s == "auto-fit" => GridTrackRepetition::AutoFit,+ let count = match fx.args[0].first()? {+ Tok::Num(n) => RepetitionCount::Count(*n as u16),+ Tok::Ident(s) if s == "auto-fill" => RepetitionCount::AutoFill,+ Tok::Ident(s) if s == "auto-fit" => RepetitionCount::AutoFit,_ => return None,};- let tracks = args[1..].iter().flatten().map(|t| track(ctx, t))- .collect::<Option<Vec<_>>>()?;- out.push(TrackSizingFunction::Repeat(rep, tracks));+ let inner: Vec<Tok> = fx.args[1..].iter().flatten().cloned().collect();+ let (tracks, inner_names) = track_list(ctx, &inner)?;+ let tracks: Vec<TrackSizingFunction> = tracks.into_iter().filter_map(|t| match t {+ GridTemplateComponent::Single(t) => Some(t),+ GridTemplateComponent::Repeat(_) => None,+ }).collect();+ let line_names = if inner_names.len() == tracks.len() + 1 { inner_names } else { Vec::new() };+ out.push(GridTemplateComponent::Repeat(GridTemplateRepetition { count, tracks, line_names }));+ names.push(Vec::new());+ }+ t => {+ out.push(GridTemplateComponent::Single(track(ctx, t)?));+ names.push(Vec::new());}- Tok::Delim('[') | Tok::Delim(']') => {}- _ => out.push(TrackSizingFunction::Single(track(ctx, t)?)),}+ k += 1;+ }+ if names.iter().all(Vec::is_empty) {+ names.clear();}- Some(out)+ Some((out, names))}-fn grid_line(v: &[Tok]) -> Option<Line<GridPlacement>> {- let place = |toks: &[Tok]| -> Option<GridPlacement> {- match toks {- [Tok::Ident(s)] if s == "auto" => Some(GridPlacement::Auto),- [Tok::Num(n)] => Some(taffy::style_helpers::line(*n as i16)),- [Tok::Ident(s), Tok::Num(n)] if s == "span" => {- Some(taffy::style_helpers::span(*n as u16))+/// `grid-template-areas: "a a b" "c . b"`.+fn template_areas(v: &[Tok]) -> Option<Option<GridTemplateAreas<Ident>>> {+ if kw(v) == Some("none") {+ return Some(None);+ }+ let rows: Vec<Vec<String>> = v.iter().map(|t| match t {+ Tok::Str(s) => Some(s.split_whitespace().map(str::to_string).collect()),+ _ => None,+ }).collect::<Option<_>>()?;+ let cols = rows.first().map(Vec::len).unwrap_or(0);+ if rows.is_empty() || rows.iter().any(|r| r.len() != cols) {+ return None;+ }+ let mut areas: Vec<GridTemplateArea<Ident>> = Vec::new();+ for (ri, row) in rows.iter().enumerate() {+ for (ci, cell) in row.iter().enumerate() {+ if cell.chars().all(|c| c == '.') {+ continue;+ }+ let (r, c) = (ri as u16 + 1, ci as u16 + 1);+ match areas.iter_mut().find(|a| a.name == *cell) {+ Some(a) => {+ a.row_start = a.row_start.min(r);+ a.row_end = a.row_end.max(r + 1);+ a.column_start = a.column_start.min(c);+ a.column_end = a.column_end.max(c + 1);+ }+ None => areas.push(GridTemplateArea {+ name: Ident::from(cell.as_str()),+ row_start: r,+ row_end: r + 1,+ column_start: c,+ column_end: c + 1,+ }),}- [Tok::Ident(_)] => Some(GridPlacement::Auto), // named lines/areas- _ => None,}- };+ }+ Some(Some(GridTemplateAreas { areas, row_count: rows.len() as u16, column_count: cols as u16 }))+}++fn grid_place(toks: &[Tok]) -> Option<GridPlacement<Ident>> {+ let mut span = false;+ let (mut num, mut name) = (None, None);+ for t in toks {+ match t {+ Tok::Ident(s) if s == "span" => span = true,+ Tok::Ident(s) if s == "auto" && toks.len() == 1 => return Some(GridPlacement::Auto),+ Tok::Ident(s) => name = Some(Ident::from(s.as_ref())),+ Tok::Num(n) => num = Some(*n as i32),+ _ => return None,+ }+ }+ Some(match (span, num, name) {+ (true, n, None) => GridPlacement::Span(n.unwrap_or(1).max(1) as u16),+ (true, n, Some(id)) => GridPlacement::NamedSpan(id, n.unwrap_or(1).max(1) as u16),+ (false, Some(n), None) => taffy::style_helpers::line(n as i16),+ (false, n, Some(id)) => GridPlacement::NamedLine(id, n.unwrap_or(0) as i16),+ _ => return None,+ })+}++fn grid_line(v: &[Tok]) -> Option<Line<GridPlacement<Ident>>> {let parts: Vec<&[Tok]> = v.split(|t| matches!(t, Tok::Slash)).collect();- let start = place(parts[0])?;+ let start = grid_place(parts[0])?;let end = match parts.get(1) {- Some(p) => place(p)?,- None => GridPlacement::Auto,+ Some(p) => grid_place(p)?,+ // a lone area name: its -end line closes it+ None => match &start {+ GridPlacement::NamedLine(id, 0) => GridPlacement::NamedLine(id.clone(), 0),+ _ => GridPlacement::Auto,+ },};Some(Line { start, end })}@@ -925,7 +1059,11 @@ fn display(ctx: &mut Ctx, v: &[Tok]) -> bool {let words: Vec<&str> = v.iter().filter_map(Tok::ident).collect();let k = match words.as_slice() {["none"] => DisplayKind::None,- ["block"] | ["block", "flow"] | ["flow-root"] | ["block", "flow-root"] => DisplayKind::Block,+ ["block"] | ["block", "flow"] => DisplayKind::Block,+ ["flow-root"] | ["block", "flow-root"] => {+ ctx.c.layout.display = Display::FlowRoot;+ DisplayKind::Block+ }["inline"] | ["inline", "flow"] | ["ruby"] | ["ruby-text"] | ["ruby-base"] => {DisplayKind::Inline}@@ -1046,6 +1184,64 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{[// -- box model --------------------------------------------------------------h("display", display),+ h("float", |c, v| {+ let rtl = c.c.layout.direction == taffy::style::Direction::Rtl;+ c.c.layout.float = match kw(v) {+ Some("left") => taffy::style::Float::Left,+ Some("right") => taffy::style::Float::Right,+ Some("inline-start") => if rtl { taffy::style::Float::Right } else { taffy::style::Float::Left },+ Some("inline-end") => if rtl { taffy::style::Float::Left } else { taffy::style::Float::Right },+ Some("none") => taffy::style::Float::None,+ _ => return false,+ };+ true+ }),+ h("clear", |c, v| {+ let rtl = c.c.layout.direction == taffy::style::Direction::Rtl;+ c.c.layout.clear = match kw(v) {+ Some("left") => taffy::style::Clear::Left,+ Some("right") => taffy::style::Clear::Right,+ Some("inline-start") => if rtl { taffy::style::Clear::Right } else { taffy::style::Clear::Left },+ Some("inline-end") => if rtl { taffy::style::Clear::Left } else { taffy::style::Clear::Right },+ Some("both" | "both-inline" | "both-block") => taffy::style::Clear::Both,+ Some("none") => taffy::style::Clear::None,+ _ => return false,+ };+ true+ }),+ h("direction", |c, v| {+ c.c.layout.direction = match kw(v) {+ Some("ltr") => taffy::style::Direction::Ltr,+ Some("rtl") => taffy::style::Direction::Rtl,+ _ => return false,+ };+ true+ }),+ h("contain", |c, v| {+ use taffy::style::Contain;+ let mut bits = Contain::NONE;+ for w in v.iter().filter_map(Tok::ident) {+ bits = match w {+ "none" => Contain::NONE,+ "layout" => bits | Contain::LAYOUT,+ "paint" => bits | Contain::PAINT,+ "content" | "strict" => bits | Contain::CONTENT,+ "size" | "inline-size" | "style" => bits,+ _ => return false,+ };+ }+ c.c.layout.contain = bits;+ true+ }),+ h("scrollbar-width", |c, v| {+ c.c.layout.scrollbar_width = match kw(v) {+ Some("auto") => 0.0, // overlay scrollbars, like the kit's+ Some("thin") => 0.0,+ Some("none") => 0.0,+ _ => return false,+ };+ true+ }),h("box-sizing", |c, v| {c.c.layout.box_sizing = match kw(v) {Some("content-box") => BoxSizing::ContentBox,@@ -1056,10 +1252,10 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{}),h("width", |c, v| dim_kw(c, v).map(|d| c.c.layout.size.width = d).is_some()),h("height", |c, v| dim_kw(c, v).map(|d| c.c.layout.size.height = d).is_some()),- h("min-width", |c, v| dim_kw(c, v).map(|d| c.c.layout.min_size.width = d).is_some()),- h("min-height", |c, v| dim_kw(c, v).map(|d| c.c.layout.min_size.height = d).is_some()),- h("max-width", |c, v| dim_kw(c, v).map(|d| c.c.layout.max_size.width = d).is_some()),- h("max-height", |c, v| dim_kw(c, v).map(|d| c.c.layout.max_size.height = d).is_some()),+ h("min-width", |c, v| lpa_kw(c, v).map(|d| c.c.layout.min_size.width = d).is_some()),+ h("min-height", |c, v| lpa_kw(c, v).map(|d| c.c.layout.min_size.height = d).is_some()),+ h("max-width", |c, v| lpa_kw(c, v).map(|d| c.c.layout.max_size.width = d).is_some()),+ h("max-height", |c, v| lpa_kw(c, v).map(|d| c.c.layout.max_size.height = d).is_some()),h("inline-size", |c, v| delegate(c, "width", v)),h("block-size", |c, v| delegate(c, "height", v)),h("min-inline-size", |c, v| delegate(c, "min-width", v)),@@ -1099,8 +1295,11 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{// -- positioning ------------------------------------------------------------h("position", |c, v| {c.c.layout.position = match kw(v) {- Some("static") | Some("relative") | Some("sticky") => Position::Relative,- Some("absolute") | Some("fixed") => Position::Absolute,+ Some("static") => Position::Static,+ Some("relative") => Position::Relative,+ Some("sticky") | Some("-webkit-sticky") => Position::Sticky,+ Some("absolute") => Position::Absolute,+ Some("fixed") => Position::Fixed,_ => return false,};true@@ -1139,6 +1338,7 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{Some("nowrap") => FlexWrap::NoWrap,Some("wrap") => FlexWrap::Wrap,Some("wrap-reverse") => FlexWrap::WrapReverse,+ Some("balance") => FlexWrap::Balance,_ => return false,};true@@ -1151,7 +1351,7 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{h("flex-shrink", |c, v| v.first().and_then(number).map(|n| c.c.layout.flex_shrink = n).is_some()),h("flex-basis", |c, v| match kw(v) {Some("content") => {- c.c.layout.flex_basis = Dimension::Auto;+ c.c.layout.flex_basis = Dimension::auto();true}_ => dim_kw(c, v).map(|d| c.c.layout.flex_basis = d).is_some(),@@ -1159,11 +1359,11 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{h("flex", |c, v| {let l = &mut c.c.layout;match (kw(v), v) {- (Some("none"), _) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (0.0, 0.0, Dimension::Auto),- (Some("auto"), _) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (1.0, 1.0, Dimension::Auto),- (Some("initial"), _) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (0.0, 1.0, Dimension::Auto),- (_, [Tok::Num(g)]) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (*g, 1.0, Dimension::Percent(0.0)),- (_, [Tok::Num(g), Tok::Num(s)]) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (*g, *s, Dimension::Percent(0.0)),+ (Some("none"), _) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (0.0, 0.0, Dimension::auto()),+ (Some("auto"), _) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (1.0, 1.0, Dimension::auto()),+ (Some("initial"), _) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (0.0, 1.0, Dimension::auto()),+ (_, [Tok::Num(g)]) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (*g, 1.0, Dimension::percent(0.0)),+ (_, [Tok::Num(g), Tok::Num(s)]) => (l.flex_grow, l.flex_shrink, l.flex_basis) = (*g, *s, Dimension::percent(0.0)),(_, [Tok::Num(g), Tok::Num(s), b]) => {let Some(len) = length(b) else { return false };let d = dim(c, len);@@ -1194,7 +1394,7 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{_ => false,}),// -- alignment ------------------------------------------------------------------- h("align-items", |c, v| kw_align(v).map(|a| c.c.layout.align_items = Some(a)).is_some()),+ h("align-items", |c, v| kw_align(v).map(|a| c.c.layout.align_items = a).is_some()),h("align-self", |c, v| match kw(v) {Some("auto") => {c.c.layout.align_self = None;@@ -1202,7 +1402,7 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{}_ => kw_align(v).map(|a| c.c.layout.align_self = Some(a)).is_some(),}),- h("justify-items", |c, v| kw_align(v).map(|a| c.c.layout.justify_items = Some(a)).is_some()),+ h("justify-items", |c, v| kw_align(v).map(|a| c.c.layout.justify_items = a).is_some()),h("justify-self", |c, v| match kw(v) {Some("auto") => {c.c.layout.justify_self = None;@@ -1210,8 +1410,8 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{}_ => kw_align(v).map(|a| c.c.layout.justify_self = Some(a)).is_some(),}),- h("align-content", |c, v| kw_align_content(v).map(|a| c.c.layout.align_content = Some(a)).is_some()),- h("justify-content", |c, v| kw_align_content(v).map(|a| c.c.layout.justify_content = Some(a)).is_some()),+ h("align-content", |c, v| kw_align_content(v).map(|a| c.c.layout.align_content = a).is_some()),+ h("justify-content", |c, v| kw_align_content(v).map(|a| c.c.layout.justify_content = a).is_some()),h("place-items", |c, v| two_kw(c, v, "align-items", "justify-items")),h("place-content", |c, v| two_kw(c, v, "align-content", "justify-content")),h("place-self", |c, v| two_kw(c, v, "align-self", "justify-self")),@@ -1234,10 +1434,33 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{h("grid-row-gap", |c, v| delegate(c, "row-gap", v)),h("grid-column-gap", |c, v| delegate(c, "column-gap", v)),// -- grid -------------------------------------------------------------------------- h("grid-template-columns", |c, v| track_list(c, v).map(|t| c.c.layout.grid_template_columns = t).is_some()),- h("grid-template-rows", |c, v| track_list(c, v).map(|t| c.c.layout.grid_template_rows = t).is_some()),+ h("grid-template-columns", |c, v| track_list(c, v).map(|(t, n)| {+ c.c.layout.grid_template_columns = t;+ c.c.layout.grid_template_column_names = n;+ }).is_some()),+ h("grid-template-rows", |c, v| track_list(c, v).map(|(t, n)| {+ c.c.layout.grid_template_rows = t;+ c.c.layout.grid_template_row_names = n;+ }).is_some()),+ h("grid-template-areas", |c, v| template_areas(v).map(|a| c.c.layout.grid_template_areas = a).is_some()),h("grid-template", |c, v| {let parts: Vec<&[Tok]> = v.split(|t| matches!(t, Tok::Slash)).collect();+ // "a a" 40px "b b" 1fr / auto 1fr: area strings, each with its row size+ if parts[0].iter().any(|t| matches!(t, Tok::Str(_))) {+ let strs: Vec<Tok> = parts[0].iter().filter(|t| matches!(t, Tok::Str(_))).cloned().collect();+ let mut rows: Vec<Tok> = Vec::new();+ for (k, t) in parts[0].iter().enumerate() {+ if matches!(t, Tok::Str(_)) {+ match parts[0].get(k + 1) {+ Some(n) if !matches!(n, Tok::Str(_)) => rows.push(n.clone()),+ _ => rows.push(Tok::Ident("auto".into())),+ }+ }+ }+ return delegate(c, "grid-template-areas", &strs)+ && delegate(c, "grid-template-rows", &rows)+ && parts.get(1).is_none_or(|cols| delegate(c, "grid-template-columns", cols));+ }match parts.as_slice() {[rows, cols] => delegate(c, "grid-template-rows", rows)&& delegate(c, "grid-template-columns", cols),@@ -1290,13 +1513,20 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{h("grid-area", |c, v| {let parts: Vec<&[Tok]> = v.split(|t| matches!(t, Tok::Slash)).collect();let get = |i: usize| parts.get(i).and_then(|p| grid_line(p)).map(|l| l.start);+ // an omitted part copies the matching earlier one when that is a+ // name (`grid-area: head` = head / head / head / head), else auto+ let named = |p: &Option<GridPlacement<Ident>>| match p {+ Some(GridPlacement::NamedLine(id, 0)) => GridPlacement::NamedLine(id.clone(), 0),+ _ => GridPlacement::Auto,+ };match (get(0), get(1), get(2), get(3)) {(Some(rs), cs, re, ce) => {- c.c.layout.grid_row = Line { start: rs, end: re.unwrap_or(GridPlacement::Auto) };- c.c.layout.grid_column = Line {- start: cs.unwrap_or(GridPlacement::Auto),- end: ce.unwrap_or(GridPlacement::Auto),- };+ let rs = Some(rs);+ let cs = cs.or_else(|| Some(named(&rs)));+ let re = re.unwrap_or_else(|| named(&rs));+ let ce = ce.unwrap_or_else(|| named(&cs));+ c.c.layout.grid_row = Line { start: rs.unwrap(), end: re };+ c.c.layout.grid_column = Line { start: cs.unwrap(), end: ce };true}_ => false,@@ -1592,6 +1822,35 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{}_ => false,}),+ h("content", |c, v| {+ if matches!(kw(v), Some("none" | "normal")) {+ c.c.content = None;+ return true;+ }+ let mut parts = Vec::new();+ // `content: "x" / "alt text"`: the part after the slash is alt text+ let main = v.split(|t| matches!(t, Tok::Slash)).next().unwrap_or(&[]);+ for t in main {+ parts.push(match t {+ Tok::Str(s) => ContentPart::Text(s.to_string()),+ Tok::Ident(s) if s == "open-quote" => ContentPart::OpenQuote,+ Tok::Ident(s) if s == "close-quote" => ContentPart::CloseQuote,+ Tok::Ident(s) if s == "no-open-quote" || s == "no-close-quote" => continue,+ Tok::Func(fx) if fx.name == "attr" => {+ let Some(n) = fx.args.first().and_then(|a| a.first()).and_then(Tok::ident) else {+ return false;+ };+ ContentPart::Attr(n.to_string())+ }+ // counters and images: no counter state / inline images here+ Tok::Func(fx) if matches!(fx.name.as_ref(), "counter" | "counters" | "url" | "image"+ | "linear-gradient" | "image-set") => continue,+ _ => return false,+ });+ }+ c.c.content = Some(parts.into_boxed_slice());+ true+ }),h("quotes", |c, v| {let strs: Vec<&str> = v.iter().filter_map(|t| match t {Tok::Str(s) => Some(s.as_ref()),@@ -1728,11 +1987,11 @@ mod tests {let c = computed("display: flex; padding: 4px 8px; margin: 0 auto; flex: 1; gap: 2px 6px;width: 50%; border: 2px solid #f00; border-radius: 4px");assert_eq!(c.display, DisplayKind::Flex);- assert_eq!(c.layout.padding.left, LengthPercentage::Length(8.0));- assert_eq!(c.layout.margin.left, LengthPercentageAuto::Auto);+ assert_eq!(c.layout.padding.left, LengthPercentage::length(8.0));+ assert_eq!(c.layout.margin.left, LengthPercentageAuto::auto());assert_eq!(c.layout.flex_grow, 1.0);- assert_eq!(c.layout.size.width, Dimension::Percent(0.5));- assert_eq!(c.layout.border.top, LengthPercentage::Length(2.0));+ assert_eq!(c.layout.size.width, Dimension::percent(0.5));+ assert_eq!(c.layout.border.top, LengthPercentage::length(2.0));assert_eq!(c.border_color[0], crate::color::rgb(0xff0000));}diff --git a/bindings/rust/blenderui/src/tree.rs b/bindings/rust/blenderui/src/tree.rsnew file mode 100644index 0000000..3e7d327--- /dev/null+++ b/bindings/rust/blenderui/src/tree.rs@@ -0,0 +1,398 @@+//! The layout tree: taffy's algorithms (block with floats, flexbox, grid,+//! out-of-flow positioning, rounding) over our own node storage.+//!+//! taffy's `TaffyTree` resolves every `calc()` to 0; this tree resolves+//! them (`crate::calc`), so `width: calc(100% - 2rem)` and friends work. It+//! is also leaner: nodes live in a `Vec` with a free list (no slot maps), and+//! a node's cache is only cleared when its own inputs change: the+//! reconciler in `layout.rs` marks changed subtrees itself.++use taffy::compute::{+ compute_block_layout, compute_cached_layout, compute_flexbox_layout, compute_grid_layout,+ compute_hidden_layout, compute_oof_layout, compute_root_layout, round_layout, BlockContext,+};+use taffy::prelude::*;+use taffy::tree::{Cache, DetailedLayoutInfo, Layout, LayoutInput, LayoutOutput, RunMode};+use taffy::{+ CacheTree, DetailedGridInfo, LayoutBlockContainer, LayoutContainingBlock, LayoutFlexboxContainer,+ LayoutGridContainer, LayoutPartialTree, RoundTree, TraversePartialTree, TraverseTree,+};++struct Node<C> {+ style: Style,+ ctx: Option<C>,+ children: Vec<NodeId>,+ hoisted: Vec<NodeId>,+ cache: Cache,+ unrounded: Layout,+ layout: Layout,+ detail: DetailedLayoutInfo,+ live: bool,+}++/// Nodes with an optional measure context `C` per leaf.+pub(crate) struct LayoutTree<C> {+ nodes: Vec<Node<C>>,+ free: Vec<usize>,+}++impl<C> Default for LayoutTree<C> {+ fn default() -> Self {+ LayoutTree { nodes: Vec::new(), free: Vec::new() }+ }+}++#[inline]+fn ix(id: NodeId) -> usize {+ u64::from(id) as usize+}++impl<C> LayoutTree<C> {+ fn alloc(&mut self, style: Style, ctx: Option<C>, children: &[NodeId]) -> NodeId {+ let node = Node {+ style,+ ctx,+ children: children.to_vec(),+ hoisted: Vec::new(),+ cache: Cache::new(),+ unrounded: Layout::new(),+ layout: Layout::new(),+ detail: DetailedLayoutInfo::None,+ live: true,+ };+ match self.free.pop() {+ Some(i) => {+ self.nodes[i] = node;+ NodeId::from(i)+ }+ None => {+ self.nodes.push(node);+ NodeId::from(self.nodes.len() - 1)+ }+ }+ }++ #[allow(dead_code)]+ pub fn new_leaf(&mut self, style: Style) -> NodeId {+ self.alloc(style, None, &[])+ }++ pub fn new_leaf_with_context(&mut self, style: Style, ctx: C) -> NodeId {+ self.alloc(style, Some(ctx), &[])+ }++ pub fn new_with_children(&mut self, style: Style, children: &[NodeId]) -> NodeId {+ self.alloc(style, None, children)+ }++ /// Frees a node (its children are not touched: the reconciler removes+ /// every unused node itself).+ pub fn remove(&mut self, id: NodeId) {+ let i = ix(id);+ if let Some(n) = self.nodes.get_mut(i) {+ if n.live {+ n.live = false;+ n.ctx = None;+ n.children = Vec::new();+ n.hoisted = Vec::new();+ n.detail = DetailedLayoutInfo::None;+ self.free.push(i);+ }+ }+ }++ pub fn style(&self, id: NodeId) -> &Style {+ &self.nodes[ix(id)].style+ }++ pub fn set_style(&mut self, id: NodeId, style: Style) {+ let n = &mut self.nodes[ix(id)];+ n.style = style;+ n.cache.clear();+ }++ pub fn children(&self, id: NodeId) -> &[NodeId] {+ &self.nodes[ix(id)].children+ }++ pub fn set_children(&mut self, id: NodeId, children: &[NodeId]) {+ let n = &mut self.nodes[ix(id)];+ n.children.clear();+ n.children.extend_from_slice(children);+ n.cache.clear();+ }++ pub fn context(&self, id: NodeId) -> Option<&C> {+ self.nodes[ix(id)].ctx.as_ref()+ }++ pub fn set_context(&mut self, id: NodeId, ctx: Option<C>) {+ let n = &mut self.nodes[ix(id)];+ n.ctx = ctx;+ n.cache.clear();+ }++ pub fn mark_dirty(&mut self, id: NodeId) {+ self.nodes[ix(id)].cache.clear();+ }++ /// The final (rounded) layout of a node.+ pub fn layout(&self, id: NodeId) -> &Layout {+ &self.nodes[ix(id)].layout+ }++ /// Lay out the tree under `root`; `measure` sizes leaves that carry a context.+ pub fn compute<M>(&mut self, root: NodeId, available: Size<AvailableSpace>, measure: M)+ where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+ {+ let mut view = View { t: self, measure };+ compute_root_layout(&mut view, root, available);+ round_layout(&mut view, root);+ }+}++/// The tree plus the measure function for one layout pass.+struct View<'t, C, M> {+ t: &'t mut LayoutTree<C>,+ measure: M,+}++impl<C, M> View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ fn child_layout(&mut self, id: NodeId, inputs: LayoutInput, block: Option<&mut BlockContext<'_>>)+ -> LayoutOutput {+ if inputs.run_mode == RunMode::PerformHiddenLayout {+ self.t.nodes[ix(id)].layout = Layout::with_order(0);+ return compute_hidden_layout(self, id);+ }+ compute_cached_layout(self, id, inputs, |tree, id, inputs| {+ let n = &tree.t.nodes[ix(id)];+ let mut out = match (n.style.display, !n.children.is_empty()) {+ (Display::None, _) => compute_hidden_layout(tree, id),+ (Display::Block, true) => compute_block_layout(tree, id, inputs, block),+ (Display::FlowRoot, true) => compute_block_layout(tree, id, inputs, None),+ (Display::Flex, true) => compute_flexbox_layout(tree, id, inputs),+ (Display::Grid, true) => compute_grid_layout(tree, id, inputs),+ (_, false) => {+ let n = &tree.t.nodes[ix(id)];+ let measure = &mut tree.measure;+ match &n.ctx {+ Some(c) => taffy::compute_leaf_layout(inputs, &n.style, resolve_calc,+ |known, avail| measure(known, avail, c)),+ None => taffy::compute_leaf_layout(inputs, &n.style, resolve_calc,+ |_, _| Size::ZERO),+ }+ }+ };+ if inputs.run_mode == RunMode::PerformLayout {+ compute_oof_layout(tree, id, &mut out);+ }+ out+ })+ }+}++/// taffy's calc callback: the pointer is a `&'static crate::calc::Resolved`.+fn resolve_calc(ptr: *const (), basis: f32) -> f32 {+ // SAFETY: every calc pointer in a style comes from `crate::calc::intern`,+ // which leaks its values: they live for the rest of the process.+ unsafe { crate::calc::Resolved::from_ptr(ptr) }.eval(basis)+}++impl<C, M> TraversePartialTree for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ type ChildIter<'a> = std::iter::Copied<std::slice::Iter<'a, NodeId>> where Self: 'a;++ #[inline(always)]+ fn child_ids(&self, id: NodeId) -> Self::ChildIter<'_> {+ self.t.nodes[ix(id)].children.iter().copied()+ }++ #[inline(always)]+ fn child_count(&self, id: NodeId) -> usize {+ self.t.nodes[ix(id)].children.len()+ }++ #[inline(always)]+ fn get_child_id(&self, id: NodeId, k: usize) -> NodeId {+ self.t.nodes[ix(id)].children[k]+ }+}++impl<C, M> TraverseTree for View<'_, C, M> where M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32> {}++impl<C, M> LayoutPartialTree for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ type CoreContainerStyle<'a> = &'a Style where Self: 'a;+ type CustomIdent = String;++ #[inline(always)]+ fn get_core_container_style(&self, id: NodeId) -> Self::CoreContainerStyle<'_> {+ &self.t.nodes[ix(id)].style+ }++ #[inline(always)]+ fn set_unrounded_layout(&mut self, id: NodeId, layout: &Layout) {+ self.t.nodes[ix(id)].unrounded = *layout;+ }++ #[inline(always)]+ fn resolve_calc_value(&self, ptr: *const (), basis: f32) -> f32 {+ resolve_calc(ptr, basis)+ }++ #[inline(always)]+ fn compute_child_layout(&mut self, id: NodeId, inputs: LayoutInput) -> LayoutOutput {+ self.child_layout(id, inputs, None)+ }+}++impl<C, M> LayoutContainingBlock for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ type OofItemStyle<'a> = &'a Style where Self: 'a;++ #[inline(always)]+ fn get_oof_item_style(&self, id: NodeId) -> Self::OofItemStyle<'_> {+ &self.t.nodes[ix(id)].style+ }++ #[inline(always)]+ fn clear_hoisted_children(&mut self, id: NodeId) {+ self.t.nodes[ix(id)].hoisted.clear();+ }++ #[inline(always)]+ fn add_hoisted_children(&mut self, id: NodeId, hoisted: &[NodeId]) {+ self.t.nodes[ix(id)].hoisted.extend_from_slice(hoisted);+ }++ #[inline(always)]+ fn get_detailed_layout_info(&self, id: NodeId) -> &DetailedLayoutInfo {+ &self.t.nodes[ix(id)].detail+ }+}++impl<C, M> CacheTree for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ #[inline(always)]+ fn cache_get(&mut self, id: NodeId, input: &LayoutInput) -> Option<LayoutOutput> {+ self.t.nodes[ix(id)].cache.get(input)+ }++ #[inline(always)]+ fn cache_store(&mut self, id: NodeId, input: &LayoutInput, out: LayoutOutput) {+ self.t.nodes[ix(id)].cache.store(input, out)+ }++ #[inline(always)]+ fn cache_clear(&mut self, id: NodeId) {+ self.t.nodes[ix(id)].cache.clear();+ }+}++impl<C, M> LayoutBlockContainer for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ type BlockContainerStyle<'a> = &'a Style where Self: 'a;+ type BlockItemStyle<'a> = &'a Style where Self: 'a;++ #[inline(always)]+ fn get_block_container_style(&self, id: NodeId) -> Self::BlockContainerStyle<'_> {+ &self.t.nodes[ix(id)].style+ }++ #[inline(always)]+ fn get_block_child_style(&self, id: NodeId) -> Self::BlockItemStyle<'_> {+ &self.t.nodes[ix(id)].style+ }++ #[inline(always)]+ fn compute_block_child_layout(&mut self, id: NodeId, inputs: LayoutInput,+ block: Option<&mut BlockContext<'_>>) -> LayoutOutput {+ self.child_layout(id, inputs, block)+ }+}++impl<C, M> LayoutFlexboxContainer for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ type FlexboxContainerStyle<'a> = &'a Style where Self: 'a;+ type FlexboxItemStyle<'a> = &'a Style where Self: 'a;++ #[inline(always)]+ fn get_flexbox_container_style(&self, id: NodeId) -> Self::FlexboxContainerStyle<'_> {+ &self.t.nodes[ix(id)].style+ }++ #[inline(always)]+ fn get_flexbox_child_style(&self, id: NodeId) -> Self::FlexboxItemStyle<'_> {+ &self.t.nodes[ix(id)].style+ }+}++impl<C, M> LayoutGridContainer for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ type GridContainerStyle<'a> = &'a Style where Self: 'a;+ type GridItemStyle<'a> = &'a Style where Self: 'a;++ #[inline(always)]+ fn get_grid_container_style(&self, id: NodeId) -> Self::GridContainerStyle<'_> {+ &self.t.nodes[ix(id)].style+ }++ #[inline(always)]+ fn get_grid_child_style(&self, id: NodeId) -> Self::GridItemStyle<'_> {+ &self.t.nodes[ix(id)].style+ }++ #[inline(always)]+ fn set_detailed_grid_info(&mut self, id: NodeId, info: DetailedGridInfo) {+ self.t.nodes[ix(id)].detail = DetailedLayoutInfo::Grid(Box::new(info));+ }+}++impl<C, M> RoundTree for View<'_, C, M>+where+ M: FnMut(Size<Option<f32>>, Size<AvailableSpace>, &C) -> Size<f32>,+{+ #[inline(always)]+ fn get_unrounded_layout(&self, id: NodeId) -> Layout {+ self.t.nodes[ix(id)].unrounded+ }++ #[inline(always)]+ fn set_final_layout(&mut self, id: NodeId, layout: &Layout) {+ self.t.nodes[ix(id)].layout = *layout;+ }++ #[inline(always)]+ fn is_out_of_flow(&self, id: NodeId) -> bool {+ let s = &self.t.nodes[ix(id)].style;+ s.position.is_out_of_flow() && s.display != Display::None+ }++ #[inline(always)]+ fn hoisted_child_count(&self, id: NodeId) -> usize {+ self.t.nodes[ix(id)].hoisted.len()+ }++ #[inline(always)]+ fn get_hoisted_child_id(&self, id: NodeId, k: usize) -> NodeId {+ self.t.nodes[ix(id)].hoisted[k]+ }+}diff --git a/bindings/rust/blenderui/src/vars.rs b/bindings/rust/blenderui/src/vars.rsnew file mode 100644index 0000000..c3fd29b--- /dev/null+++ b/bindings/rust/blenderui/src/vars.rs@@ -0,0 +1,164 @@+//! Custom properties and `var()` / `env()` substitution.+//!+//! A computed style holds a [`VarId`] into the style store's arena of+//! variable maps: children share their parent's map until they declare a+//! custom property of their own. Substitution works on tokens (no+//! re-parsing), including inside nested functions such as+//! `calc(var(--gap) * 2)` and `rgb(var(--r) 0 0)`.++use crate::css::{Prop, Tok};++/// Custom property values, sorted by property.+pub(crate) type VarMap = Box<[(Prop, Box<[Tok]>)]>;++/// Arena of variable maps (index 0 = no variables).+pub(crate) struct Vars {+ maps: Vec<VarMap>,+}++impl Default for Vars {+ fn default() -> Self {+ Vars { maps: vec![Box::new([])] }+ }+}++impl Vars {+ pub fn get(&self, id: u32) -> &[(Prop, Box<[Tok]>)] {+ &self.maps[id as usize]+ }++ pub fn add(&mut self, map: VarMap) -> u32 {+ self.maps.push(map);+ (self.maps.len() - 1) as u32+ }++ pub fn clear(&mut self) {+ self.maps.truncate(1);+ }+}++pub(crate) fn lookup<'a>(map: &'a [(Prop, Box<[Tok]>)], p: Prop) -> Option<&'a [Tok]> {+ map.binary_search_by_key(&p, |e| e.0).ok().map(|i| &*map[i].1)+}++/// Whether the tokens use `var()` or `env()` anywhere.+pub(crate) fn uses_vars(toks: &[Tok]) -> bool {+ toks.iter().any(|t| match t {+ Tok::Func(fx) => fx.name == "var" || fx.name == "env" || fx.args.iter().any(|a| uses_vars(a)),+ _ => false,+ })+}++/// `toks` with every `var()` / `env()` replaced. None when a reference+/// can't be resolved and has no fallback (the declaration is then invalid+/// at computed-value time, which acts like `unset`).+pub(crate) fn substitute(toks: &[Tok], map: &[(Prop, Box<[Tok]>)]) -> Option<Vec<Tok>> {+ let mut out = Vec::with_capacity(toks.len());+ subst_into(toks, map, &mut out, 0)?;+ Some(out)+}++fn subst_into(toks: &[Tok], map: &[(Prop, Box<[Tok]>)], out: &mut Vec<Tok>, depth: u32) -> Option<()> {+ if depth > 32 {+ return None; // a reference cycle+ }+ for t in toks {+ match t {+ Tok::Func(fx) if fx.name == "var" => {+ let first = fx.args.first()?;+ let name = first.first().and_then(Tok::ident)?;+ let value = lookup(map, Prop::custom(name));+ match value {+ Some(v) if !v.is_empty() => subst_into(v, map, out, depth + 1)?,+ _ => {+ // fallback: everything after the first comma (commas included)+ if fx.args.len() < 2 {+ return None;+ }+ for (k, a) in fx.args[1..].iter().enumerate() {+ if k > 0 {+ out.push(Tok::Comma);+ }+ subst_into(a, map, out, depth + 1)?;+ }+ }+ }+ }+ Tok::Func(fx) if fx.name == "env" => {+ let name = fx.args.first().and_then(|a| a.first()).and_then(Tok::ident).unwrap_or("");+ match env_value(name) {+ Some(v) => out.push(v),+ None => {+ let fb = fx.args.get(1)?;+ subst_into(fb, map, out, depth + 1)?;+ }+ }+ }+ Tok::Func(fx) if fx.args.iter().any(|a| uses_vars(a)) => {+ let mut args = Vec::with_capacity(fx.args.len());+ for a in &fx.args {+ let mut v = Vec::with_capacity(a.len());+ subst_into(a, map, &mut v, depth)?;+ // a substituted value may carry commas: split them back into arguments+ let mut cur = Vec::new();+ for t in v {+ if t == Tok::Comma {+ args.push(std::mem::take(&mut cur));+ } else {+ cur.push(t);+ }+ }+ args.push(cur);+ }+ out.push(Tok::Func(Box::new(crate::css::FuncTok { name: fx.name.clone(), args })));+ }+ other => out.push(other.clone()),+ }+ }+ Some(())+}++/// Environment variables of a desktop window: no insets, no keyboard.+fn env_value(name: &str) -> Option<Tok> {+ match name {+ "safe-area-inset-top" | "safe-area-inset-right" | "safe-area-inset-bottom"+ | "safe-area-inset-left" | "safe-area-max-inset-top" | "safe-area-max-inset-right"+ | "safe-area-max-inset-bottom" | "safe-area-max-inset-left" | "keyboard-inset-top"+ | "keyboard-inset-right" | "keyboard-inset-bottom" | "keyboard-inset-left"+ | "keyboard-inset-width" | "keyboard-inset-height" | "titlebar-area-x"+ | "titlebar-area-y" | "titlebar-area-height" => Some(Tok::Num(0.0)),+ "preferred-text-scale" => Some(Tok::Num(1.0)),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::css::tokenize;++ fn map(entries: &[(&str, &str)]) -> Vec<(Prop, Box<[Tok]>)> {+ let mut m: Vec<(Prop, Box<[Tok]>)> =+ entries.iter().map(|(k, v)| (Prop::custom(k), tokenize(v).into_boxed_slice())).collect();+ m.sort_by_key(|e| e.0);+ m+ }++ #[test]+ fn substitutes_nested_and_fallbacks() {+ let m = map(&[("--gap", "8px"), ("--c", "1, 2, 3"), ("--alias", "var(--gap)")]);+ assert_eq!(substitute(&tokenize("var(--gap) 4px"), &m).unwrap(), tokenize("8px 4px"));+ assert_eq!(substitute(&tokenize("calc(var(--alias) * 2)"), &m).unwrap(), tokenize("calc(8px * 2)"));+ assert_eq!(substitute(&tokenize("rgb(var(--c))"), &m).unwrap(), tokenize("rgb(1, 2, 3)"));+ assert_eq!(substitute(&tokenize("var(--nope, 1px 2px)"), &m).unwrap(), tokenize("1px 2px"));+ assert_eq!(substitute(&tokenize("var(--nope, var(--gap))"), &m).unwrap(), tokenize("8px"));+ assert!(substitute(&tokenize("var(--nope)"), &m).is_none());+ assert_eq!(substitute(&tokenize("env(safe-area-inset-top, 9px)"), &m).unwrap(), vec![Tok::Num(0.0)]);+ }++ #[test]+ fn cycles_fail() {+ let m = map(&[("--a", "var(--b)"), ("--b", "var(--a)")]);+ assert!(substitute(&tokenize("var(--a)"), &m).is_none());+ }+}diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rsindex d0d8298..dc35bd7 100644--- a/bindings/rust/blenderui/src/window.rs+++ b/bindings/rust/blenderui/src/window.rs@@ -211,11 +211,15 @@ pub struct WindowOptions {pub titlebar: Option<TitlebarOptions>,pub is_resizable: Option<bool>,pub window_min_size: Option<Size<Pixels>>,+ /// Draw this window on the GPU (Direct3D 11) instead of the software+ /// raster; `None` follows [`Application::gpu`] / the `BUI_GPU` variable.+ pub gpu: Option<bool>,}/// The application entry point (gpui's `Application`).pub struct Application {headless: bool,+ gpu: Option<bool>,}impl Default for Application {@@ -227,13 +231,22 @@ impl Default for Application {impl Application {/// Native windows.pub fn new() -> Application {- Application { headless: false }+ Application { headless: false, gpu: None }+ }++ /// Draw every window on the GPU (Direct3D 11 on Windows): the same+ /// pixels as the software raster, with rasterization off the CPU. Falls+ /// back to software where no device exists. The `BUI_GPU` environment+ /// variable (1/0) overrides this.+ pub fn gpu(mut self, on: bool) -> Application {+ self.gpu = Some(on);+ self}/// Off-screen windows (tests, screenshots, CI): nothing is shown, the/// `simulate_*` and `draw` methods drive it.pub fn headless() -> Application {- Application { headless: true }+ Application { headless: true, gpu: None }}/// Run `f`, then the event loop until every window is closed.@@ -242,6 +255,9 @@ impl Application {static KIT: std::sync::Mutex<()> = std::sync::Mutex::new(());let _guard = KIT.lock().unwrap_or_else(|e| e.into_inner());let headless = self.headless || unsafe { sys::BK_window_supported() } == 0;+ if let Some(on) = self.gpu {+ unsafe { sys::BUI_gpu_set_default(on as c_int) };+ }let mut app = App::create(headless);f(&mut app);app.flush();@@ -352,6 +368,9 @@ impl App {sys::BK_window_wm(*n, c"minsize".as_ptr(), (m.width.0 * w.scale) as f64,(m.height.0 * w.scale) as f64);}+ if options.gpu == Some(true) {+ sys::BK_window_set_gpu(*n, 1);+ }}}let entity = build(&mut w, self);@@ -777,6 +796,13 @@ impl Window {self.scale}+ /// Whether frames are drawn on the GPU right now (it turns on a few+ /// frames after start, once the device is ready).+ pub fn is_gpu(&self) -> bool {+ // SAFETY: `native` is a live kit window owned by this Window.+ self.native.map(|n| unsafe { sys::BK_window_gpu(n) } != 0).unwrap_or(false)+ }+pub fn set_window_title(&mut self, title: &str) {if self.title != title {self.title = title.to_owned();diff --git a/bindings/rust/blenderui/tests/headless.rs b/bindings/rust/blenderui/tests/headless.rsindex bd6ac10..f3e1393 100644--- a/bindings/rust/blenderui/tests/headless.rs+++ b/bindings/rust/blenderui/tests/headless.rs@@ -222,7 +222,8 @@ fn css_macro_matches_runtime_css() {assert_eq!(compiled[0].prop, Prop::named("display"));assert_eq!(compiled[2].prop, Prop::named("color"));assert!(compiled[2].important);- assert_eq!(compiled[3].prop, Prop::CUSTOM);+ assert!(compiled[3].prop.is_custom());+ assert_eq!(compiled[3].prop.name(), "--x");let parsed = blenderui::css::parse_declarations("display: flex; padding: 4px 8px; color: #e6a23c !important; --x: 1");for (a, b) in compiled.iter().zip(&parsed) {assert_eq!(a, b); // same tokens, whether parsed at compile time or run timediff --git a/bindings/rust/blenderui/tests/modern_css.rs b/bindings/rust/blenderui/tests/modern_css.rsnew file mode 100644index 0000000..ecf795d--- /dev/null+++ b/bindings/rust/blenderui/tests/modern_css.rs@@ -0,0 +1,290 @@+//! Modern CSS end to end: custom properties, math functions, grid areas,+//! floats, sizing keywords, positioning. Each test lays out a page headless+//! and checks the boxes (and pixels where paint matters).++use blenderui::prelude::*;++fn open<V: Render>(cx: &mut App, w: f32, h: f32, v: V) -> WindowHandle<V> {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(w), px(h)),+ })),+ ..Default::default()+ };+ cx.open_window(opts, |_, cx| cx.new(|_| v)).unwrap()+}++/// `(x, y, w, h)` of the element with `id`.+fn rect(cx: &mut App, win: WindowId, id: &str) -> (f32, f32, f32, f32) {+ let b = cx.element_bounds(win, id).unwrap_or_else(|| panic!("no element {id}"));+ (b.origin.x, b.origin.y, b.size.width, b.size.height)+}++/// A page from a stylesheet and a body built by `f`.+struct Page {+ css: &'static str,+ body: fn() -> Div,+}++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ (self.body)().child(style().child(self.css))+ }+}++fn page(cx: &mut App, w: f32, h: f32, css: &'static str, body: fn() -> Div) -> WindowId {+ let win = open(cx, w, h, Page { css, body });+ cx.draw(win.id);+ win.id+}++#[test]+fn custom_properties_and_math() {+ Application::headless().run(|cx| {+ let w = page(cx, 400.0, 300.0, "+ :root { --gap: 10px; --w: calc(100% - 2 * var(--gap)); --unit: 8px }+ body { margin: 0 }+ #a { width: var(--w); height: var(--missing, 20px); margin-left: var(--gap) }+ #b { width: min(50%, 150px); height: clamp(10px, 5vh, 40px) }+ #c { width: calc(var(--unit) * 3 + 1rem); height: round(up, 13px, 5px) }+ .scope { --unit: 2px }+ #d { width: calc(var(--unit) * 10); height: 4px }+ #e { width: max(10px, calc(25% - var(--gap))); height: abs(-6px) }+ ", || {+ body()+ .child(div().id("a"))+ .child(div().id("b"))+ .child(div().id("c"))+ .child(div().class("scope").child(div().id("d")))+ .child(div().id("e"))+ });+ assert_eq!(rect(cx, w, "a"), (10.0, 0.0, 380.0, 20.0));+ assert_eq!(rect(cx, w, "b").2, 150.0);+ assert_eq!(rect(cx, w, "b").3, 15.0); // 5vh of 300+ assert_eq!(rect(cx, w, "c").2, 40.0);+ assert_eq!(rect(cx, w, "c").3, 15.0);+ assert_eq!(rect(cx, w, "d").2, 20.0, "inherited override");+ assert_eq!(rect(cx, w, "e").2, 90.0);+ assert_eq!(rect(cx, w, "e").3, 6.0);+ });+}++#[test]+fn grid_template_areas_and_named_lines() {+ Application::headless().run(|cx| {+ let w = page(cx, 300.0, 200.0, "+ body { margin: 0 }+ .g { display: grid; width: 300px; height: 200px;+ grid-template-columns: [side] 100px [main-start] 1fr [main-end];+ grid-template-rows: 40px 1fr 30px;+ grid-template-areas: 'head head' 'side main' 'foot foot' }+ #h { grid-area: head } #s { grid-area: side } #m { grid-area: main } #f { grid-area: foot }+ #x { grid-column: main-start / main-end; grid-row: 3 }+ ", || {+ body().child(div().class("g")+ .child(div().id("h")).child(div().id("s")).child(div().id("m")).child(div().id("f")))+ });+ assert_eq!(rect(cx, w, "h"), (0.0, 0.0, 300.0, 40.0));+ assert_eq!(rect(cx, w, "s"), (0.0, 40.0, 100.0, 130.0));+ assert_eq!(rect(cx, w, "m"), (100.0, 40.0, 200.0, 130.0));+ assert_eq!(rect(cx, w, "f"), (0.0, 170.0, 300.0, 30.0));+ });+}++#[test]+fn sizing_keywords_and_mixed_calc() {+ Application::headless().run(|cx| {+ let w = page(cx, 400.0, 200.0, "+ body { margin: 0 }+ .wrap { width: 300px }+ #fit { width: fit-content; height: 10px; background: red }+ #fit > div { width: 70px; height: 10px }+ #mix { width: calc(50% + 20px); height: 10px }+ #st { display: flex; width: 200px }+ #st > div { width: stretch; height: 10px }+ ", || {+ body().child(div().class("wrap")+ .child(div().id("fit").child(div()))+ .child(div().id("mix"))+ .child(div().id("st").child(div().id("st1"))))+ });+ assert_eq!(rect(cx, w, "fit").2, 70.0);+ assert_eq!(rect(cx, w, "mix").2, 170.0);+ assert_eq!(rect(cx, w, "st1").2, 200.0);+ });+}++#[test]+fn floats_and_clear() {+ Application::headless().run(|cx| {+ let w = page(cx, 300.0, 200.0, "+ body { margin: 0 }+ .c { width: 300px }+ #l { float: left; width: 50px; height: 40px }+ #r { float: right; width: 60px; height: 20px }+ #cl { clear: both; height: 10px }+ ", || {+ body().child(div().class("c")+ .child(div().id("l")).child(div().id("r")).child(div().id("cl")))+ });+ assert_eq!(rect(cx, w, "l"), (0.0, 0.0, 50.0, 40.0));+ assert_eq!(rect(cx, w, "r"), (240.0, 0.0, 60.0, 20.0));+ assert_eq!(rect(cx, w, "cl").1, 40.0, "cleared below both floats");+ });+}++#[test]+fn absolute_and_fixed_positioning() {+ Application::headless().run(|cx| {+ let w = page(cx, 300.0, 200.0, "+ body { margin: 0 }+ .rel { position: relative; margin: 20px; width: 100px; height: 100px }+ #abs { position: absolute; right: 10px; bottom: 5px; width: 20px; height: 20px }+ #fix { position: fixed; left: 0; top: 0; width: 15px; height: 15px }+ #st { position: static; left: 50px; width: 10px; height: 10px }+ ", || {+ body().child(div().class("rel")+ .child(div().child(div().id("abs")))+ .child(div().id("fix"))+ .child(div().id("st")))+ });+ assert_eq!(rect(cx, w, "abs"), (90.0, 95.0, 20.0, 20.0), "relative to the positioned ancestor");+ assert_eq!(rect(cx, w, "fix"), (0.0, 0.0, 15.0, 15.0), "relative to the viewport");+ assert_eq!(rect(cx, w, "st").0, 20.0, "static ignores insets");+ });+}++#[test]+fn selectors_level_4() {+ Application::headless().run(|cx| {+ let w = page(cx, 400.0, 400.0, "+ body { margin: 0 }+ div { height: 10px }+ .card:has(> img) { height: 31px }+ .card:has(.deep) { height: 32px }+ .list > :nth-child(2 of .on) { height: 33px }+ .list > p:last-of-type { height: 34px }+ .list > p:nth-of-type(1) { height: 35px }+ :is(.x, .y):not(.z) { height: 36px }+ :where(.w) { height: 37px }+ .w { height: 38px }+ [data-k=\"VaLuE\" i] { height: 39px }+ .nest { height: 1px; & > .kid { height: 40px } .outer & { height: 41px } }+ ", || {+ body()+ .child(div().id("c1").class("card").child(img()))+ .child(div().id("c2").class("card").child(div().child(span().class("deep"))))+ .child(div().id("c3").class("card").child(span()))+ .child(div().class("list")+ .child(p().id("p1").class("on")).child(div().id("d1"))+ .child(p().id("p2").class("on")).child(p().id("p3")))+ .child(div().id("x").class("x")).child(div().id("xz").class("x z"))+ .child(div().id("w").class("w"))+ .child(div().id("k").attr("data-k", "value"))+ .child(div().class("nest").child(div().id("kid").class("kid")))+ .child(div().class("outer").child(div().id("n2").class("nest")))+ });+ let h = |cx: &mut App, id: &str| rect(cx, w, id).3;+ assert_eq!(h(cx, "c1"), 31.0, ":has(> img)");+ assert_eq!(h(cx, "c2"), 32.0, ":has(.deep) through a descendant");+ assert_eq!(h(cx, "c3"), 10.0, "no :has match");+ assert_eq!(h(cx, "p2"), 33.0, ":nth-child(2 of .on)");+ assert_eq!(h(cx, "p3"), 34.0, ":last-of-type");+ assert_eq!(h(cx, "p1"), 35.0, ":nth-of-type(1)");+ assert_eq!(h(cx, "x"), 36.0);+ assert_eq!(h(cx, "xz"), 10.0, ":not()");+ assert_eq!(h(cx, "w"), 38.0, ":where() has no specificity");+ assert_eq!(h(cx, "k"), 39.0, "case-insensitive attribute");+ assert_eq!(h(cx, "kid"), 40.0, "nested `& > .kid`");+ assert_eq!(h(cx, "n2"), 41.0, "nested `.outer &`");+ });+}++#[test]+fn at_rules_layers_media_supports_scope() {+ Application::headless().run(|cx| {+ let w = page(cx, 500.0, 300.0, "+ body { margin: 0 }+ @layer reset, base, theme;+ @layer reset { div { height: 10px } }+ @layer theme { #l { height: 20px } }+ @layer base { #l { height: 99px } #l2 { height: 98px } }+ #l2 { height: 21px }+ @media (400px <= width <= 600px) { #m { height: 22px } }+ @media (width > 600px) { #m { height: 99px } }+ @media (prefers-color-scheme: dark) and (hover: hover) { #d { height: 23px } }+ @supports (display: grid) and (not (display: banana)) { #s { height: 24px } }+ @supports (display: banana) { #s { height: 99px } }+ @scope (.panel) to (.stop) { .t { height: 25px } }+ ", || {+ body()+ .child(div().id("l")).child(div().id("l2")).child(div().id("m")).child(div().id("d"))+ .child(div().id("s"))+ .child(div().class("panel").child(div().id("t1").class("t"))+ .child(div().class("stop").child(div().id("t2").class("t"))))+ .child(div().id("t3").class("t"))+ });+ let h = |cx: &mut App, id: &str| rect(cx, w, id).3;+ assert_eq!(h(cx, "l"), 20.0, "later layer wins");+ assert_eq!(h(cx, "l2"), 21.0, "unlayered beats layered");+ assert_eq!(h(cx, "m"), 22.0, "media range");+ assert_eq!(h(cx, "d"), 23.0);+ assert_eq!(h(cx, "s"), 24.0, "@supports");+ assert_eq!(h(cx, "t1"), 25.0, "in scope");+ assert_eq!(h(cx, "t2"), 10.0, "below the scope limit");+ assert_eq!(h(cx, "t3"), 10.0, "outside the scope");+ });+}++#[test]+fn generated_content() {+ Application::headless().run(|cx| {+ let w = page(cx, 400.0, 200.0, "+ body { margin: 0 }+ .a::before { content: ''; display: block; height: 12px }+ .a::after { content: attr(data-x); display: block; height: 7px }+ .a > div { height: 5px }+ .b:empty::before { content: none; display: block; height: 50px }+ ", || {+ body()+ .child(div().id("a").class("a").attr("data-x", "hi").child(div().id("inner")))+ .child(div().id("b").class("b"))+ });+ assert_eq!(rect(cx, w, "inner").1, 12.0, "::before comes first");+ assert_eq!(rect(cx, w, "a").3, 24.0, "::before + child + ::after");+ assert_eq!(rect(cx, w, "b").3, 0.0, "content: none generates nothing");+ });+}++#[test]+fn tailwind_classes() {+ Application::headless().run(|cx| {+ let w = page(cx, 800.0, 400.0, "body { margin: 0 }", || {+ body()+ .child(div().id("a").class(blenderui::tw!("w-1/2 h-8 p-4 px-2 bg-sky-500/50 rounded-lg")))+ .child(div().id("b").class("flex gap-4 w-[calc(100%-2rem)] mx-auto")+ .child(div().id("b1").class("size-10 shrink-0"))+ .child(div().id("b2").class("grow h-6 md:h-12 max-sm:h-1")))+ .child(div().id("c").class("grid grid-cols-3 gap-x-2 w-60")+ .child(div().id("c1").class("col-span-2 h-4")).child(div().id("c2").class("h-4")))+ .child(div().class("group").child(div().id("g").class("h-2 group-hover:h-9")))+ .child(div().id("d").class("h-5 data-[state=open]:h-7").attr("data-state", "open"))+ .child(div().id("e").class("hidden md:block h-3"))+ .child(div().id("f").class("h-[37px] [&>*]:h-1").child(div().id("f1")))+ });+ assert_eq!(rect(cx, w, "a").2, 400.0, "w-1/2");+ assert_eq!(rect(cx, w, "a").3, 32.0, "h-8 (border-box, as with Tailwind preflight)");+ let b = rect(cx, w, "b");+ assert_eq!((b.0, b.2), (16.0, 768.0), "arbitrary calc width + mx-auto");+ assert_eq!(rect(cx, w, "b1").2, 40.0);+ assert_eq!(rect(cx, w, "b2").0, 16.0 + 40.0 + 16.0, "gap-4");+ assert_eq!(rect(cx, w, "b2").3, 48.0, "md: applies at 800px");+ assert_eq!(rect(cx, w, "c1").2, 157.0, "col-span-2 of 3 (gap-x-2 = 8px), rounded");+ assert_eq!(rect(cx, w, "g").3, 8.0);+ assert_eq!(rect(cx, w, "d").3, 28.0, "data-[state=open]:");+ assert_eq!(rect(cx, w, "e").3, 12.0, "hidden md:block");+ assert_eq!(rect(cx, w, "f").3, 37.0);+ assert_eq!(rect(cx, w, "f1").3, 4.0, "[&>*]: arbitrary variant");+ });+}diff --git a/docs/c-api.md b/docs/c-api.mdindex bbd0394..782c9b2 100644--- a/docs/c-api.md+++ b/docs/c-api.md@@ -81,6 +81,8 @@ int main(void)| **Host** | `BKHost`: `request` (schedule a render), `set_cursor`, `warp`, clipboard, `schedule` (timers), `emit` (events). A `BKWindow` provides all of them. || **Events** | `emit(data, node, kind, ref, a, b)`. Kinds: `BK_EV_CHANGE`, `CLICK`, `CALL` (menu item or hotkey), `RENAME`, `ACTIVATE`, `TOGGLE`, `BROWSE`, `SUBMIT`. With the `"events"` property you also get raw `PRESS` / `RELEASE` / `DOUBLE` / `MOTION` / `ENTER` / `LEAVE` / `KEY` / `KEYRELEASE` / `WHEEL` / `CONFIGURE`, plus `VIEW` and `SCROLL` for scrolling. || **Windows** | `BK_window_new`, `show`, `close`, `set_title`, `set_size`, `wm(key, a, b)` (position, topmost, alpha, resizable, minsize, state ...), `timer`, `run`, `pump`, `quit` |+| **GPU rendering** | `BUI_gpu_set_default(1)` (all new windows), `BK_window_set_gpu(win, 1)` (one window), `BK_window_gpu(win)` (1 once frames draw on the GPU). `BUI_GPU=1/0` overrides. For your own rasters: `BUI_raster_gpu_attach(r, hwnd_or_NULL, wait)`, `BUI_raster_gpu_poll`, `BUI_raster_is_gpu`. |+| **Text** | `BUI_text_measure`, `BUI_raster_text`, `BUI_text_add_font(family, flags, data, len)` (register a font; needed on wasm) || **Specialised** | Canvas display list (`BK_canvas_set_item`), text area (`BK_textarea_*`), trees (`BK_tree_item_*`), menus (`BK_open_menu`, `BK_open_pie`), color ramps and curves, `BK_undo` / `BK_redo` |Node types: `frame column row grid box panel tabs sidetabs scroll scrollbardiff --git a/docs/components.md b/docs/components.mdindex 7222182..e672635 100644--- a/docs/components.md+++ b/docs/components.md@@ -43,6 +43,12 @@ App(title="BUI", size=(420, 640), *children, padding=None, spacing=None, header=Pass a `MenuBar` as `header=` for a Blender top bar.+## GPU rendering++Call `bui.set_gpu(True)` before creating windows, or run with `BUI_GPU=1`, to+draw them on the GPU (Direct3D 11). The pixels are the same and the CPU cost+is much lower. See [getting-started.md](getting-started.md#gpu-rendering).+## Common component APIEvery component has:diff --git a/docs/getting-started.md b/docs/getting-started.mdindex 8ba5a3e..401fdab 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -31,6 +31,7 @@ cmake --build build| `BUI_BUILD_UI` | `OFF` | Compile Blender's original `ui/` sources as well (not needed for the kit) || `BUI_BUILD_QT_BACKEND` | `OFF` | The C++ Qt/QPainter render-sink backend (needs Qt 5/6 Widgets) || `BUI_WARNINGS_AS_ERRORS` | `OFF` | `-Werror` / `/WX` |+| `BUI_TEXT_STB` | `OFF` | Use the portable stb_truetype text engine on Windows too (it is always used on Linux, macOS and wasm) |## 2. Use it from Python@@ -79,6 +80,10 @@ shared (`bui.host`).| `BUIPY_BUILD_DIR` | Directory containing the built `buipy` extension || `BUI_HOST=tk` | Force the stdlib-Tk window host even where the native host exists (Windows) || `BUI_UI_SCALE` | Fix the UI scale (for example `1.5`) instead of following the monitor's DPI |+| `BUI_GPU=1` | Draw native windows on the GPU (Direct3D 11). `BUI_GPU=0` forces the software raster. Overrides `bui.set_gpu()` / `.gpu(true)` |+| `BUI_GPU_DEBUG=1` | Print why the GPU renderer could not start |+| `BUI_FONT`, `BUI_FONT_DIR` | Portable text engine: a font file for the UI font, and an extra font folder |+| `BUI_PROFILE=1` | Print per-phase frame times (raster and present) |## Window hosts@@ -91,6 +96,27 @@ shared (`bui.host`).window that shows the kit's frame buffer and forwards input to it.The UI and the API are identical, but presenting is a little slower.+### GPU rendering++Native windows draw on the CPU by default. To draw them on the GPU+(Direct3D 11) instead, use one of these:++| Where | Flag |+|---|---|+| tkinter syntax | `tk.Tk(gpu=True)` |+| Any Python API | `bui.set_gpu(True)` before creating windows |+| Rust | `Application::new().gpu(true)` or `WindowOptions { gpu: Some(true), .. }` |+| C | `BUI_gpu_set_default(1)` or `BK_window_set_gpu(win, 1)` |+| Any app, no code change | `BUI_GPU=1` |++Both renderers draw the same pixels. The GPU uses far less CPU per frame+(about 2-4x less in the+[benchmark](../bindings/rust/bench/README.md)), but the process needs about+10 MB more RAM plus GPU memory. The device starts in the background, so the+first frames are drawn on the CPU and the switch happens a few frames in.+Without a GPU, or on Linux/macOS for now, windows stay on the software+raster.+`bui.host.run()` runs one loop for all windows, `bui.host.update()` processespending events once, and `bui.host.quit()` stops the loop.@@ -101,4 +127,6 @@ pending events once, and `bui.host.quit()` stops the loop.| `ImportError: buipy` | Build first (`cmake --build build`) or set `BUIPY_BUILD_DIR`. The extension must match your Python version: a `cp314` build needs Python 3.14. || Window doesn't appear | Call `mainloop()` / `app.exec()` / `App.run()`. Without a loop, windows only show during `update()`. || Blurry or tiny UI | Set `BUI_UI_SCALE`. On Windows the native host is DPI-aware by default. |+| `gpu=True` has no effect | Run with `BUI_GPU_DEBUG=1` to see why the device failed. Windows without Direct3D 11 stay on the software raster. |+| No text on Linux/macOS | Install a TrueType font (DejaVu, Liberation or Noto), or point `BUI_FONT` at a `.ttf`. || A tkinter feature behaves differently | See the behaviour notes in [tkinter.md](tkinter.md#behaviour). If stdlib tkinter does something else, that is a bug; `tests/test_tk_compat.py` shows how to write a side-by-side check. |diff --git a/docs/qt.md b/docs/qt.mdindex 9e31fb1..df88121 100644--- a/docs/qt.md+++ b/docs/qt.md@@ -62,6 +62,12 @@ win.show()app.exec()```+## GPU rendering++Call `bui.set_gpu(True)` before creating windows, or run with `BUI_GPU=1`, to+draw them on the GPU (Direct3D 11). The pixels are the same and the CPU cost+is much lower. See [getting-started.md](getting-started.md#gpu-rendering).+## How it maps| Qt | On BUI |diff --git a/docs/rust.md b/docs/rust.mdindex c3a6395..f1136f1 100644--- a/docs/rust.md+++ b/docs/rust.md@@ -303,49 +303,116 @@ From `cargo test --test parity -- --nocapture`:| Area | Coverage || ------------------------------------- | -------------------------------------------------------------------------------- || HTML elements (WHATWG index) | **113 / 113** constructible, plus `svg` / `math` roots; 9 are Blender widgets |-| CSS properties | **173** change layout or rendering; **87** more parse but have no effect |-| CSS 2.1, screen properties | **76 / 90** rendered, 90 / 90 parsed |+| CSS properties | **180** change layout or rendering; **81** more parse but have no effect |+| W3C property index (745 properties) | **176** rendered (24%), **75** parsed without effect (10%), **494** not recognized (66%): most of these are drafts, speech, paged media and SVG |+| CSS 2.1, screen properties | **80 / 90** rendered, 90 / 90 parsed || Flexbox | **12 / 12** |-| Grid | **22 / 23** (no `grid-template-areas`) |-| gpui / Tailwind `Styled` methods | ~1,300 |+| Grid | **23 / 23** (including `grid-template-areas` and named lines) |+| Tailwind CSS v4 | Classes compile on first use (v4 theme, variants, arbitrary values); `tw!` checks them at compile time |-The CSS 2.1 properties that parse without effect: `float`, `clear`, `clip`,-`content`, `counter-increment`, `counter-reset`, `direction`,-`unicode-bidi`, `empty-cells`, `table-layout`, `list-style-image` and-`background-attachment` / `-position` / `-repeat` (there are no background-images; gradients are supported).+Beyond properties, the engine supports:+- **Values:** every CSS math function (`calc`, `min`, `max`, `clamp`, `round`, `mod`, `rem`, trigonometry, `pow`, `hypot` ...) with mixed units, every length unit, and `var()` / `env()`.+- **Colors:** CSS Color 4/5: `oklch`, `lab`, `color()`, `color-mix()`, relative colors and `light-dark()`.+- **Selectors:** Selectors Level 4 (`:has()`, `:is()`, `:where()`, `:nth-child(of S)` ...), nesting, and `::before` / `::after` with `content`.+- **At-rules:** `@media` (Media Queries 4 ranges), `@supports`, `@layer` and `@scope`.++```rust+div().class(tw!("grid grid-cols-3 gap-4 md:grid-cols-6 hover:bg-sky-500/50"))+div().style("width: calc(100% - 2 * var(--gap)); background: color-mix(in oklch, var(--brand) 60%, white)")+```++The CSS 2.1 properties that parse without effect: `clip`, `counter-increment`, `counter-reset`, `empty-cells`, `table-layout`, `unicode-bidi`, `list-style-image` and `background-attachment` / `-position` / `-repeat` (there are no background images; gradients are supported).++How much is left, against all 745 properties in the+[W3C index](https://www.w3.org/Style/CSS/all-properties.en.html):++| | Properties | Share |+|---|---:|---:|+| Change layout or rendering | 176 | 24% |+| Parsed, no effect yet | 75 | 10% |+| Not recognized | 494 | 66% |++The 494 unrecognized properties break down as:++| Group | Properties |+|---|---:|+| Draft border and corner shapes (`corner-shape`, `border-*-clip` ...) | ~78 |+| SVG fill, stroke and markers | ~40 |+| Gap decorations (`row-rule-*` ...) | 38 |+| Speech and aural | 31 |+| Animation triggers and scroll-driven animation | 26 |+| Paged media, regions, rhythm and others | ~25 |+| Scroll snap margins and padding | 23 |+| Masking | 18 |+| Everything else | ~215 |++The everyday screen CSS is much further along: Flexbox 12/12, Grid 23/23 and+CSS 2.1 80/90. The largest remaining gaps among common properties are visual+effects (transforms, filters, blend modes, `clip-path`), animations and+transitions, and background images.++Not done yet:+- **Parsed, not applied:** `@container` (queries parse, no container sizes yet), `@font-face`, `@keyframes`, transitions and animations.+- **Rendering effects:** 2D/3D `rotate` / `skew` transforms, `filter` / `backdrop-filter`, blend modes, `clip-path`, masks, `border-image` and border styles other than solid.+- **The rest of the W3C property index:** about 490 entries this engine doesn't know, mostly drafts, speech and paged media.+- **Box sizing:** the default is `border-box` (like Tailwind's preflight), not CSS's `content-box`.## Performance vs gpui-The same UI on blenderui, [gpui-fast](https://github.com/longbridge/gpui-fast)-0.1.13 and gpui 0.2.2: a window of N rounded, labelled cells that all change-every frame. Ryzen 7 5800U laptop at 60 Hz, one session, median of 3 runs.+The same UI on blenderui (GPU renderer and default software raster),+[gpui-fast](https://github.com/longbridge/gpui-fast) 0.1.13 and gpui 0.2.2:+a window of N rounded, labelled cells that all change every frame. Ryzen 7+5800U laptop at 60 Hz, all apps back to back in one session.[bindings/rust/bench](../bindings/rust/bench/README.md) has the full table andhow to re-run it.-| | blenderui | gpui-fast | gpui |-|---|---|---|---|-| 100 / 1000 animated cells | 60 / 60 fps (display cap; 529 / 157 uncapped) | 60 / 60 fps | 60 / 60 fps |-| 3000 animated cells | **57.5 fps** | 50.5 fps | 18.9 fps |-| CPU per frame, 1000 / 3000 cells | 13.7 / 27.3 ms (all threads) | **6.7 / 20.1 ms** + GPU | 14.7 / 53.1 ms + GPU |-| RAM (working set) | **18-31 MB** | 33-64 MB + 19-24 MB GPU | 31-76 MB + 16-21 MB GPU |-| First frame after launch | **~6 ms** | ~250 ms | ~260 ms |-| Idle CPU | **0 %** | 0-0.1 % | 0.7-1.4 % |--blenderui leads on memory and startup, and in this session on the 3000-cell-frame rate. gpui-fast does the least CPU work per frame; its heavy-scene frame-rate varies between sessions on this laptop (29.7-59.8 fps). blenderui rasterises on the CPU-in parallel bands (`BUI_RASTER_THREADS=1` forces one thread). `BUI_PROFILE=1`-prints its per-phase frame times.+| | blenderui GPU | blenderui CPU | gpui-fast | gpui |+|---|---|---|---|---|+| 1000 / 3000 animated cells | **60 / 59.9 fps** | 60 / 57.6 fps | 49.2 / 31.5 fps | 36.4 / 19.9 fps |+| CPU per frame, 100 / 1000 / 3000 cells | **1.2 / 4.7 / 11.6 ms** | 4.6 / 10.2 / 22.0 ms | 2.7 / 20.5 / 31.9 ms + GPU | 4.7 / 27.7 / 50.5 ms + GPU |+| RAM (working set) | 28-40 MB + 19-22 MB GPU | **21-30 MB**, no GPU | 45-65 MB + 19-24 MB GPU | 40-77 MB + 16-21 MB GPU |+| First frame after launch | **~5 ms** | **~5 ms** | ~200 ms | ~220 ms |+| Idle CPU | **0 %** | 0-0.9 % | 0-0.4 % | 0.9-1.4 % |++### The GPU renderer++```rust+Application::new().gpu(true).run(|cx| { /* every window on the GPU */ });+// or one window:+cx.open_window(WindowOptions { gpu: Some(true), ..Default::default() }, build);+// window.is_gpu() turns true a few frames in, once the device is ready+```++`BUI_GPU=1` / `0` overrides both. It is Direct3D 11 on Windows. Elsewhere,+or without a device, windows stay on the software raster. Every primitive+becomes one instance of a single shader, following Blender's instanced+widget-base batches. Text runs and images are cached in atlases. Frames+render into a persistent target, so only damaged regions redraw. Both+renderers produce the same pixels (the `gpu_parity` test).++The software raster draws in parallel bands (`BUI_RASTER_THREADS=1` forces+one thread). `BUI_PROFILE=1` prints per-phase frame times for either+renderer.++### Text++Windows draws text with GDI by default. Linux, macOS and wasm use the+bundled stb_truetype engine; enable it on Windows too with the+`portable-text` feature. It finds the platform's fonts, or `BUI_FONT` /+`BUI_FONT_DIR`. Where there are no system fonts (wasm), register one:++```rust+blenderui::add_font("Inter", false, false, include_bytes!("Inter-Regular.ttf"));+```## Limitations-- **No floats** (`float` is ignored), no `::before` / `::after` or generated- content, no right-to-left text.+- **Floats** place block boxes, but text does not wrap around them; `direction: rtl`+ lays boxes out right to left, but text itself is not shaped right to left.- **One font face**: the UI font in regular, bold and italic. `font-family`is parsed but `monospace` text uses the UI font.+- **Effects and animation**: see "Not done yet" under [Coverage](#coverage).- **Transforms**: `translate` only; `scale()` and `rotate()` are ignored.-- **No `var()`**: custom properties are accepted but not substituted.- **Inline boxes** paint their background per word; borders and padding oninline elements (`<kbd>`, `<code>`) are not drawn.- **Widgets draw above page content**, so a `z-index`ed box (a `<dialog>`)diff --git a/docs/tkinter.md b/docs/tkinter.mdindex 03d120a..0ba2574 100644--- a/docs/tkinter.md+++ b/docs/tkinter.md@@ -79,6 +79,24 @@ root.mainloop()The full version is `examples/tk_unchanged_app.py`.+## GPU rendering++Pass `gpu=True` to draw the window on the GPU (Direct3D 11) instead of the+CPU:++```python+import bui.tksyntax as tk++root = tk.Tk(gpu=True)+```++The pixels are the same, but rendering uses far less CPU, which helps busy+`Canvas` scenes most. For apps you run unchanged+(`python -m bui.tksyntax app.py`), set `BUI_GPU=1` instead, or call+`bui.set_gpu(True)` before the first `Tk()`. The first frames draw on the+CPU while the device starts. If no GPU is available, the window stays on+the software raster.+## Module map| tkinter | BUI | Notes |diff --git a/gpu/CMakeLists.txt b/gpu/CMakeLists.txtindex 01305ed..4009620 100644--- a/gpu/CMakeLists.txt+++ b/gpu/CMakeLists.txt@@ -1,4 +1,4 @@-# bui_gpu - drawing abstraction with a null backend+# bui_gpu - drawing abstraction with a null backend## The UI toolkit draws exclusively through these seam headers. Ship a real# renderer by implementing the same API (GL / Metal / software rasterizer).@@ -8,6 +8,7 @@set(SRCintern/gpu_null.cintern/gpu_raster.c+ intern/gpu_d3d11.c)add_library(bui_gpu STATIC ${SRC})@@ -21,6 +22,12 @@ target_link_libraries(bui_gpu PUBLIC bui::core)if(NOT MSVC)target_link_libraries(bui_gpu PRIVATE m)endif()+# Text: GDI on Windows; the portable stb_truetype engine everywhere else, or+# on Windows too with BUI_TEXT_STB=ON.+option(BUI_TEXT_STB "Use the portable (stb_truetype) text engine on Windows too" OFF)+if(BUI_TEXT_STB)+ target_compile_definitions(bui_gpu PRIVATE BUI_TEXT_STB=1)+endif()if(WIN32)# gpu_raster.c: GDI glyph-run text engine + native window present.target_link_libraries(bui_gpu PUBLIC gdi32 user32)diff --git a/gpu/extern/stb_truetype.h b/gpu/extern/stb_truetype.hnew file mode 100644index 0000000..90a5c2e--- /dev/null+++ b/gpu/extern/stb_truetype.h@@ -0,0 +1,5079 @@+// stb_truetype.h - v1.26 - public domain+// authored from 2009-2021 by Sean Barrett / RAD Game Tools+//+// =======================================================================+//+// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES+//+// This library does no range checking of the offsets found in the file,+// meaning an attacker can use it to read arbitrary memory.+//+// =======================================================================+//+// This library processes TrueType files:+// parse files+// extract glyph metrics+// extract glyph shapes+// render glyphs to one-channel bitmaps with antialiasing (box filter)+// render glyphs to one-channel SDF bitmaps (signed-distance field/function)+//+// Todo:+// non-MS cmaps+// crashproof on bad data+// hinting? (no longer patented)+// cleartype-style AA?+// optimize: use simple memory allocator for intermediates+// optimize: build edge-list directly from curves+// optimize: rasterize directly from curves?+//+// ADDITIONAL CONTRIBUTORS+//+// Mikko Mononen: compound shape support, more cmap formats+// Tor Andersson: kerning, subpixel rendering+// Dougall Johnson: OpenType / Type 2 font handling+// Daniel Ribeiro Maciel: basic GPOS-based kerning+//+// Misc other:+// Ryan Gordon+// Simon Glass+// github:IntellectualKitty+// Imanol Celaya+// Daniel Ribeiro Maciel+//+// Bug/warning reports/fixes:+// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe+// Cass Everitt Martins Mozeiko github:aloucks+// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam+// Brian Hook Omar Cornut github:vassvik+// Walter van Niftrik Ryan Griege+// David Gow Peter LaValle+// David Given Sergey Popov+// Ivan-Assen Ivanov Giumo X. Clanjor+// Anthony Pesch Higor Euripedes+// Johan Duparc Thomas Fields+// Hou Qiming Derek Vinyard+// Rob Loach Cort Stratton+// Kenney Phillis Jr. Brian Costabile+// Ken Voskuil (kaesve) Yakov Galka+//+// VERSION HISTORY+//+// 1.26 (2021-08-28) fix broken rasterizer+// 1.25 (2021-07-11) many fixes+// 1.24 (2020-02-05) fix warning+// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)+// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined+// 1.21 (2019-02-25) fix warning+// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()+// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod+// 1.18 (2018-01-29) add missing function+// 1.17 (2017-07-23) make more arguments const; doc fix+// 1.16 (2017-07-12) SDF support+// 1.15 (2017-03-03) make more arguments const+// 1.14 (2017-01-16) num-fonts-in-TTC function+// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts+// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual+// 1.11 (2016-04-02) fix unused-variable warning+// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef+// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly+// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges+// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;+// variant PackFontRanges to pack and render in separate phases;+// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);+// fixed an assert() bug in the new rasterizer+// replace assert() with STBTT_assert() in new rasterizer+//+// Full history can be found at the end of this file.+//+// LICENSE+//+// See end of file for license information.+//+// USAGE+//+// Include this file in whatever places need to refer to it. In ONE C/C+++// file, write:+// #define STB_TRUETYPE_IMPLEMENTATION+// before the #include of this file. This expands out the actual+// implementation into that C/C++ file.+//+// To make the implementation private to the file that generates the implementation,+// #define STBTT_STATIC+//+// Simple 3D API (don't ship this, but it's fine for tools and quick start)+// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture+// stbtt_GetBakedQuad() -- compute quad to draw for a given char+//+// Improved 3D API (more shippable):+// #include "stb_rect_pack.h" -- optional, but you really want it+// stbtt_PackBegin()+// stbtt_PackSetOversampling() -- for improved quality on small fonts+// stbtt_PackFontRanges() -- pack and renders+// stbtt_PackEnd()+// stbtt_GetPackedQuad()+//+// "Load" a font file from a memory buffer (you have to keep the buffer loaded)+// stbtt_InitFont()+// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections+// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections+//+// Render a unicode codepoint to a bitmap+// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap+// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide+// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be+//+// Character advance/positioning+// stbtt_GetCodepointHMetrics()+// stbtt_GetFontVMetrics()+// stbtt_GetFontVMetricsOS2()+// stbtt_GetCodepointKernAdvance()+//+// Starting with version 1.06, the rasterizer was replaced with a new,+// faster and generally-more-precise rasterizer. The new rasterizer more+// accurately measures pixel coverage for anti-aliasing, except in the case+// where multiple shapes overlap, in which case it overestimates the AA pixel+// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If+// this turns out to be a problem, you can re-enable the old rasterizer with+// #define STBTT_RASTERIZER_VERSION 1+// which will incur about a 15% speed hit.+//+// ADDITIONAL DOCUMENTATION+//+// Immediately after this block comment are a series of sample programs.+//+// After the sample programs is the "header file" section. This section+// includes documentation for each API function.+//+// Some important concepts to understand to use this library:+//+// Codepoint+// Characters are defined by unicode codepoints, e.g. 65 is+// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is+// the hiragana for "ma".+//+// Glyph+// A visual character shape (every codepoint is rendered as+// some glyph)+//+// Glyph index+// A font-specific integer ID representing a glyph+//+// Baseline+// Glyph shapes are defined relative to a baseline, which is the+// bottom of uppercase characters. Characters extend both above+// and below the baseline.+//+// Current Point+// As you draw text to the screen, you keep track of a "current point"+// which is the origin of each character. The current point's vertical+// position is the baseline. Even "baked fonts" use this model.+//+// Vertical Font Metrics+// The vertical qualities of the font, used to vertically position+// and space the characters. See docs for stbtt_GetFontVMetrics.+//+// Font Size in Pixels or Points+// The preferred interface for specifying font sizes in stb_truetype+// is to specify how tall the font's vertical extent should be in pixels.+// If that sounds good enough, skip the next paragraph.+//+// Most font APIs instead use "points", which are a common typographic+// measurement for describing font size, defined as 72 points per inch.+// stb_truetype provides a point API for compatibility. However, true+// "per inch" conventions don't make much sense on computer displays+// since different monitors have different number of pixels per+// inch. For example, Windows traditionally uses a convention that+// there are 96 pixels per inch, thus making 'inch' measurements have+// nothing to do with inches, and thus effectively defining a point to+// be 1.333 pixels. Additionally, the TrueType font data provides+// an explicit scale factor to scale a given font's glyphs to points,+// but the author has observed that this scale factor is often wrong+// for non-commercial fonts, thus making fonts scaled in points+// according to the TrueType spec incoherently sized in practice.+//+// DETAILED USAGE:+//+// Scale:+// Select how high you want the font to be, in points or pixels.+// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute+// a scale factor SF that will be used by all other functions.+//+// Baseline:+// You need to select a y-coordinate that is the baseline of where+// your text will appear. Call GetFontBoundingBox to get the baseline-relative+// bounding box for all characters. SF*-y0 will be the distance in pixels+// that the worst-case character could extend above the baseline, so if+// you want the top edge of characters to appear at the top of the+// screen where y=0, then you would set the baseline to SF*-y0.+//+// Current point:+// Set the current point where the first character will appear. The+// first character could extend left of the current point; this is font+// dependent. You can either choose a current point that is the leftmost+// point and hope, or add some padding, or check the bounding box or+// left-side-bearing of the first character to be displayed and set+// the current point based on that.+//+// Displaying a character:+// Compute the bounding box of the character. It will contain signed values+// relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,+// then the character should be displayed in the rectangle from+// <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).+//+// Advancing for the next character:+// Call GlyphHMetrics, and compute 'current_point += SF * advance'.+//+//+// ADVANCED USAGE+//+// Quality:+//+// - Use the functions with Subpixel at the end to allow your characters+// to have subpixel positioning. Since the font is anti-aliased, not+// hinted, this is very import for quality. (This is not possible with+// baked fonts.)+//+// - Kerning is now supported, and if you're supporting subpixel rendering+// then kerning is worth using to give your text a polished look.+//+// Performance:+//+// - Convert Unicode codepoints to glyph indexes and operate on the glyphs;+// if you don't do this, stb_truetype is forced to do the conversion on+// every call.+//+// - There are a lot of memory allocations. We should modify it to take+// a temp buffer and allocate from the temp buffer (without freeing),+// should help performance a lot.+//+// NOTES+//+// The system uses the raw data found in the .ttf file without changing it+// and without building auxiliary data structures. This is a bit inefficient+// on little-endian systems (the data is big-endian), but assuming you're+// caching the bitmaps or glyph shapes this shouldn't be a big deal.+//+// It appears to be very hard to programmatically determine what font a+// given file is in a general way. I provide an API for this, but I don't+// recommend it.+//+//+// PERFORMANCE MEASUREMENTS FOR 1.06:+//+// 32-bit 64-bit+// Previous release: 8.83 s 7.68 s+// Pool allocations: 7.72 s 6.34 s+// Inline sort : 6.54 s 5.65 s+// New rasterizer : 5.63 s 5.00 s++//////////////////////////////////////////////////////////////////////////////+//////////////////////////////////////////////////////////////////////////////+////+//// SAMPLE PROGRAMS+////+//+// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless.+// See "tests/truetype_demo_win32.c" for a complete version.+#if 0+#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation+#include "stb_truetype.h"++unsigned char ttf_buffer[1<<20];+unsigned char temp_bitmap[512*512];++stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs+GLuint ftex;++void my_stbtt_initfont(void)+{+ fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));+ stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!+ // can free ttf_buffer at this point+ glGenTextures(1, &ftex);+ glBindTexture(GL_TEXTURE_2D, ftex);+ glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);+ // can free temp_bitmap at this point+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);+}++void my_stbtt_print(float x, float y, char *text)+{+ // assume orthographic projection with units = screen pixels, origin at top left+ glEnable(GL_BLEND);+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);+ glEnable(GL_TEXTURE_2D);+ glBindTexture(GL_TEXTURE_2D, ftex);+ glBegin(GL_QUADS);+ while (*text) {+ if (*text >= 32 && *text < 128) {+ stbtt_aligned_quad q;+ stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9+ glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0);+ glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0);+ glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1);+ glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1);+ }+ ++text;+ }+ glEnd();+}+#endif+//+//+//////////////////////////////////////////////////////////////////////////////+//+// Complete program (this compiles): get a single bitmap, print as ASCII art+//+#if 0+#include <stdio.h>+#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation+#include "stb_truetype.h"++char ttf_buffer[1<<25];++int main(int argc, char **argv)+{+ stbtt_fontinfo font;+ unsigned char *bitmap;+ int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);++ fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));++ stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));+ bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);++ for (j=0; j < h; ++j) {+ for (i=0; i < w; ++i)+ putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);+ putchar('\n');+ }+ return 0;+}+#endif+//+// Output:+//+// .ii.+// @@@@@@.+// V@Mio@@o+// :i. V@V+// :oM@@M+// :@@@MM@M+// @@o o@M+// :@@. M@M+// @@@o@@@@+// :M@@V:@@.+//+//////////////////////////////////////////////////////////////////////////////+//+// Complete program: print "Hello World!" banner, with bugs+//+#if 0+char buffer[24<<20];+unsigned char screen[20][79];++int main(int arg, char **argv)+{+ stbtt_fontinfo font;+ int i,j,ascent,baseline,ch=0;+ float scale, xpos=2; // leave a little padding in case the character extends left+ char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness++ fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));+ stbtt_InitFont(&font, buffer, 0);++ scale = stbtt_ScaleForPixelHeight(&font, 15);+ stbtt_GetFontVMetrics(&font, &ascent,0,0);+ baseline = (int) (ascent*scale);++ while (text[ch]) {+ int advance,lsb,x0,y0,x1,y1;+ float x_shift = xpos - (float) floor(xpos);+ stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);+ stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);+ stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);+ // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong+ // because this API is really for baking character bitmaps into textures. if you want to render+ // a sequence of characters, you really need to render each bitmap to a temp buffer, then+ // "alpha blend" that into the working buffer+ xpos += (advance * scale);+ if (text[ch+1])+ xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);+ ++ch;+ }++ for (j=0; j < 20; ++j) {+ for (i=0; i < 78; ++i)+ putchar(" .:ioVM@"[screen[j][i]>>5]);+ putchar('\n');+ }++ return 0;+}+#endif+++//////////////////////////////////////////////////////////////////////////////+//////////////////////////////////////////////////////////////////////////////+////+//// INTEGRATION WITH YOUR CODEBASE+////+//// The following sections allow you to supply alternate definitions+//// of C library functions used by stb_truetype, e.g. if you don't+//// link with the C runtime library.++#ifdef STB_TRUETYPE_IMPLEMENTATION+ // #define your own (u)stbtt_int8/16/32 before including to override this+ #ifndef stbtt_uint8+ typedef unsigned char stbtt_uint8;+ typedef signed char stbtt_int8;+ typedef unsigned short stbtt_uint16;+ typedef signed short stbtt_int16;+ typedef unsigned int stbtt_uint32;+ typedef signed int stbtt_int32;+ #endif++ typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];+ typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];++ // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h+ #ifndef STBTT_ifloor+ #include <math.h>+ #define STBTT_ifloor(x) ((int) floor(x))+ #define STBTT_iceil(x) ((int) ceil(x))+ #endif++ #ifndef STBTT_sqrt+ #include <math.h>+ #define STBTT_sqrt(x) sqrt(x)+ #define STBTT_pow(x,y) pow(x,y)+ #endif++ #ifndef STBTT_fmod+ #include <math.h>+ #define STBTT_fmod(x,y) fmod(x,y)+ #endif++ #ifndef STBTT_cos+ #include <math.h>+ #define STBTT_cos(x) cos(x)+ #define STBTT_acos(x) acos(x)+ #endif++ #ifndef STBTT_fabs+ #include <math.h>+ #define STBTT_fabs(x) fabs(x)+ #endif++ // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h+ #ifndef STBTT_malloc+ #include <stdlib.h>+ #define STBTT_malloc(x,u) ((void)(u),malloc(x))+ #define STBTT_free(x,u) ((void)(u),free(x))+ #endif++ #ifndef STBTT_assert+ #include <assert.h>+ #define STBTT_assert(x) assert(x)+ #endif++ #ifndef STBTT_strlen+ #include <string.h>+ #define STBTT_strlen(x) strlen(x)+ #endif++ #ifndef STBTT_memcpy+ #include <string.h>+ #define STBTT_memcpy memcpy+ #define STBTT_memset memset+ #endif+#endif++///////////////////////////////////////////////////////////////////////////////+///////////////////////////////////////////////////////////////////////////////+////+//// INTERFACE+////+////++#ifndef __STB_INCLUDE_STB_TRUETYPE_H__+#define __STB_INCLUDE_STB_TRUETYPE_H__++#ifdef STBTT_STATIC+#define STBTT_DEF static+#else+#define STBTT_DEF extern+#endif++#ifdef __cplusplus+extern "C" {+#endif++// private structure+typedef struct+{+ unsigned char *data;+ int cursor;+ int size;+} stbtt__buf;++//////////////////////////////////////////////////////////////////////////////+//+// TEXTURE BAKING API+//+// If you use this API, you only have to call two functions ever.+//++typedef struct+{+ unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap+ float xoff,yoff,xadvance;+} stbtt_bakedchar;++STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)+ float pixel_height, // height of font in pixels+ unsigned char *pixels, int pw, int ph, // bitmap to be filled in+ int first_char, int num_chars, // characters to bake+ stbtt_bakedchar *chardata); // you allocate this, it's num_chars long+// if return is positive, the first unused row of the bitmap+// if return is negative, returns the negative of the number of characters that fit+// if return is 0, no characters fit and no rows were used+// This uses a very crappy packing.++typedef struct+{+ float x0,y0,s0,t0; // top-left+ float x1,y1,s1,t1; // bottom-right+} stbtt_aligned_quad;++STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above+ int char_index, // character to display+ float *xpos, float *ypos, // pointers to current position in screen pixel space+ stbtt_aligned_quad *q, // output: quad to draw+ int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier+// Call GetBakedQuad with char_index = 'character - first_char', and it+// creates the quad you need to draw and advances the current position.+//+// The coordinate system used assumes y increases downwards.+//+// Characters will extend both above and below the current position;+// see discussion of "BASELINE" above.+//+// It's inefficient; you might want to c&p it and optimize it.++STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);+// Query the font vertical metrics without having to create a font first.+++//////////////////////////////////////////////////////////////////////////////+//+// NEW TEXTURE BAKING API+//+// This provides options for packing multiple fonts into one atlas, not+// perfectly but better than nothing.++typedef struct+{+ unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap+ float xoff,yoff,xadvance;+ float xoff2,yoff2;+} stbtt_packedchar;++typedef struct stbtt_pack_context stbtt_pack_context;+typedef struct stbtt_fontinfo stbtt_fontinfo;+#ifndef STB_RECT_PACK_VERSION+typedef struct stbrp_rect stbrp_rect;+#endif++STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);+// Initializes a packing context stored in the passed-in stbtt_pack_context.+// Future calls using this context will pack characters into the bitmap passed+// in here: a 1-channel bitmap that is width * height. stride_in_bytes is+// the distance from one row to the next (or 0 to mean they are packed tightly+// together). "padding" is the amount of padding to leave between each+// character (normally you want '1' for bitmaps you'll use as textures with+// bilinear filtering).+//+// Returns 0 on failure, 1 on success.++STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);+// Cleans up the packing context and frees all memory.++#define STBTT_POINT_SIZE(x) (-(x))++STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,+ int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);+// Creates character bitmaps from the font_index'th font found in fontdata (use+// font_index=0 if you don't know what that is). It creates num_chars_in_range+// bitmaps for characters with unicode values starting at first_unicode_char_in_range+// and increasing. Data for how to render them is stored in chardata_for_range;+// pass these to stbtt_GetPackedQuad to get back renderable quads.+//+// font_size is the full height of the character from ascender to descender,+// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed+// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()+// and pass that result as 'font_size':+// ..., 20 , ... // font max minus min y is 20 pixels tall+// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall++typedef struct+{+ float font_size;+ int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint+ int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints+ int num_chars;+ stbtt_packedchar *chardata_for_range; // output+ unsigned char h_oversample, v_oversample; // don't set these, they're used internally+} stbtt_pack_range;++STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);+// Creates character bitmaps from multiple ranges of characters stored in+// ranges. This will usually create a better-packed bitmap than multiple+// calls to stbtt_PackFontRange. Note that you can call this multiple+// times within a single PackBegin/PackEnd.++STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);+// Oversampling a font increases the quality by allowing higher-quality subpixel+// positioning, and is especially valuable at smaller text sizes.+//+// This function sets the amount of oversampling for all following calls to+// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given+// pack context. The default (no oversampling) is achieved by h_oversample=1+// and v_oversample=1. The total number of pixels required is+// h_oversample*v_oversample larger than the default; for example, 2x2+// oversampling requires 4x the storage of 1x1. For best results, render+// oversampled textures with bilinear filtering. Look at the readme in+// stb/tests/oversample for information about oversampled fonts+//+// To use with PackFontRangesGather etc., you must set it before calls+// call to PackFontRangesGatherRects.++STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);+// If skip != 0, this tells stb_truetype to skip any codepoints for which+// there is no corresponding glyph. If skip=0, which is the default, then+// codepoints without a glyph recived the font's "missing character" glyph,+// typically an empty box by convention.++STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above+ int char_index, // character to display+ float *xpos, float *ypos, // pointers to current position in screen pixel space+ stbtt_aligned_quad *q, // output: quad to draw+ int align_to_integer);++STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);+STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);+STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);+// Calling these functions in sequence is roughly equivalent to calling+// stbtt_PackFontRanges(). If you more control over the packing of multiple+// fonts, or if you want to pack custom data into a font texture, take a look+// at the source to of stbtt_PackFontRanges() and create a custom version+// using these functions, e.g. call GatherRects multiple times,+// building up a single array of rects, then call PackRects once,+// then call RenderIntoRects repeatedly. This may result in a+// better packing than calling PackFontRanges multiple times+// (or it may not).++// this is an opaque structure that you shouldn't mess with which holds+// all the context needed from PackBegin to PackEnd.+struct stbtt_pack_context {+ void *user_allocator_context;+ void *pack_info;+ int width;+ int height;+ int stride_in_bytes;+ int padding;+ int skip_missing;+ unsigned int h_oversample, v_oversample;+ unsigned char *pixels;+ void *nodes;+};++//////////////////////////////////////////////////////////////////////////////+//+// FONT LOADING+//+//++STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);+// This function will determine the number of fonts in a font file. TrueType+// collection (.ttc) files may contain multiple fonts, while TrueType font+// (.ttf) files only contain one font. The number of fonts can be used for+// indexing with the previous function where the index is between zero and one+// less than the total fonts. If an error occurs, -1 is returned.++STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);+// Each .ttf/.ttc file may have more than one font. Each font has a sequential+// index number starting from 0. Call this function to get the font offset for+// a given index; it returns -1 if the index is out of range. A regular .ttf+// file will only define one font and it always be at offset 0, so it will+// return '0' for index 0, and -1 for all other indices.++// The following structure is defined publicly so you can declare one on+// the stack or as a global or etc, but you should treat it as opaque.+struct stbtt_fontinfo+{+ void * userdata;+ unsigned char * data; // pointer to .ttf file+ int fontstart; // offset of start of font++ int numGlyphs; // number of glyphs, needed for range checking++ int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf+ int index_map; // a cmap mapping for our chosen character encoding+ int indexToLocFormat; // format needed to map from glyph index to glyph++ stbtt__buf cff; // cff font data+ stbtt__buf charstrings; // the charstring index+ stbtt__buf gsubrs; // global charstring subroutines index+ stbtt__buf subrs; // private charstring subroutines index+ stbtt__buf fontdicts; // array of font dicts+ stbtt__buf fdselect; // map from glyph to fontdict+};++STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);+// Given an offset into the file that defines a font, this function builds+// the necessary cached info for the rest of the system. You must allocate+// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't+// need to do anything special to free it, because the contents are pure+// value data with no additional data structures. Returns 0 on failure.+++//////////////////////////////////////////////////////////////////////////////+//+// CHARACTER TO GLYPH-INDEX CONVERSIOn++STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);+// If you're going to perform multiple operations on the same character+// and you want a speed-up, call this function with the character you're+// going to process, then use glyph-based functions instead of the+// codepoint-based functions.+// Returns 0 if the character codepoint is not defined in the font.+++//////////////////////////////////////////////////////////////////////////////+//+// CHARACTER PROPERTIES+//++STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);+// computes a scale factor to produce a font whose "height" is 'pixels' tall.+// Height is measured as the distance from the highest ascender to the lowest+// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics+// and computing:+// scale = pixels / (ascent - descent)+// so if you prefer to measure height by the ascent only, use a similar calculation.++STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);+// computes a scale factor to produce a font whose EM size is mapped to+// 'pixels' tall. This is probably what traditional APIs compute, but+// I'm not positive.++STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);+// ascent is the coordinate above the baseline the font extends; descent+// is the coordinate below the baseline the font extends (i.e. it is typically negative)+// lineGap is the spacing between one row's descent and the next row's ascent...+// so you should advance the vertical position by "*ascent - *descent + *lineGap"+// these are expressed in unscaled coordinates, so you must multiply by+// the scale factor for a given size++STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);+// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2+// table (specific to MS/Windows TTF files).+//+// Returns 1 on success (table present), 0 on failure.++STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);+// the bounding box around all possible characters++STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);+// leftSideBearing is the offset from the current horizontal position to the left edge of the character+// advanceWidth is the offset from the current horizontal position to the next horizontal position+// these are expressed in unscaled coordinates++STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);+// an additional amount to add to the 'advance' value between ch1 and ch2++STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);+// Gets the bounding box of the visible part of the glyph, in unscaled coordinates++STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);+STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);+STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);+// as above, but takes one or more glyph indices for greater efficiency++typedef struct stbtt_kerningentry+{+ int glyph1; // use stbtt_FindGlyphIndex+ int glyph2;+ int advance;+} stbtt_kerningentry;++STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info);+STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length);+// Retrieves a complete list of all of the kerning pairs provided by the font+// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write.+// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1)++//////////////////////////////////////////////////////////////////////////////+//+// GLYPH SHAPES (you probably don't need these, but they have to go before+// the bitmaps for C declaration-order reasons)+//++#ifndef STBTT_vmove // you can predefine these to use different values (but why?)+ enum {+ STBTT_vmove=1,+ STBTT_vline,+ STBTT_vcurve,+ STBTT_vcubic+ };+#endif++#ifndef stbtt_vertex // you can predefine this to use different values+ // (we share this with other code at RAD)+ #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file+ typedef struct+ {+ stbtt_vertex_type x,y,cx,cy,cx1,cy1;+ unsigned char type,padding;+ } stbtt_vertex;+#endif++STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);+// returns non-zero if nothing is drawn for this glyph++STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);+STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);+// returns # of vertices and fills *vertices with the pointer to them+// these are expressed in "unscaled" coordinates+//+// The shape is a series of contours. Each one starts with+// a STBTT_moveto, then consists of a series of mixed+// STBTT_lineto and STBTT_curveto segments. A lineto+// draws a line from previous endpoint to its x,y; a curveto+// draws a quadratic bezier from previous endpoint to+// its x,y, using cx,cy as the bezier control point.++STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);+// frees the data allocated above++STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl);+STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg);+STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg);+// fills svg with the character's SVG data.+// returns data size or 0 if SVG not found.++//////////////////////////////////////////////////////////////////////////////+//+// BITMAP RENDERING+//++STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);+// frees the bitmap allocated below++STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);+// allocates a large-enough single-channel 8bpp bitmap and renders the+// specified character/glyph at the specified scale into it, with+// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).+// *width & *height are filled out with the width & height of the bitmap,+// which is stored left-to-right, top-to-bottom.+//+// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap++STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);+// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel+// shift for the character++STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);+// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap+// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap+// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the+// width and height and positioning info for it first.++STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);+// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel+// shift for the character++STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);+// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering+// is performed (see stbtt_PackSetOversampling)++STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);+// get the bbox of the bitmap centered around the glyph origin; so the+// bitmap width is ix1-ix0, height is iy1-iy0, and location to place+// the bitmap top left is (leftSideBearing*scale,iy0).+// (Note that the bitmap uses y-increases-down, but the shape uses+// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)++STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);+// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel+// shift for the character++// the following functions are equivalent to the above functions, but operate+// on glyph indices instead of Unicode codepoints (for efficiency)+STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);+STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);+STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);+STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);+STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);+++// @TODO: don't expose this structure+typedef struct+{+ int w,h,stride;+ unsigned char *pixels;+} stbtt__bitmap;++// rasterize a shape with quadratic beziers into a bitmap+STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into+ float flatness_in_pixels, // allowable error of curve in pixels+ stbtt_vertex *vertices, // array of vertices defining shape+ int num_verts, // number of vertices in above array+ float scale_x, float scale_y, // scale applied to input vertices+ float shift_x, float shift_y, // translation applied to input vertices+ int x_off, int y_off, // another translation applied to input+ int invert, // if non-zero, vertically flip shape+ void *userdata); // context for to STBTT_MALLOC++//////////////////////////////////////////////////////////////////////////////+//+// Signed Distance Function (or Field) rendering++STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);+// frees the SDF bitmap allocated below++STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);+STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);+// These functions compute a discretized SDF field for a single character, suitable for storing+// in a single-channel texture, sampling with bilinear filtering, and testing against+// larger than some threshold to produce scalable fonts.+// info -- the font+// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap+// glyph/codepoint -- the character to generate the SDF for+// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),+// which allows effects like bit outlines+// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)+// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)+// if positive, > onedge_value is inside; if negative, < onedge_value is inside+// width,height -- output height & width of the SDF bitmap (including padding)+// xoff,yoff -- output origin of the character+// return value -- a 2D array of bytes 0..255, width*height in size+//+// pixel_dist_scale & onedge_value are a scale & bias that allows you to make+// optimal use of the limited 0..255 for your application, trading off precision+// and special effects. SDF values outside the range 0..255 are clamped to 0..255.+//+// Example:+// scale = stbtt_ScaleForPixelHeight(22)+// padding = 5+// onedge_value = 180+// pixel_dist_scale = 180/5.0 = 36.0+//+// This will create an SDF bitmap in which the character is about 22 pixels+// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled+// shape, sample the SDF at each pixel and fill the pixel if the SDF value+// is greater than or equal to 180/255. (You'll actually want to antialias,+// which is beyond the scope of this example.) Additionally, you can compute+// offset outlines (e.g. to stroke the character border inside & outside,+// or only outside). For example, to fill outside the character up to 3 SDF+// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above+// choice of variables maps a range from 5 pixels outside the shape to+// 2 pixels inside the shape to 0..255; this is intended primarily for apply+// outside effects only (the interior range is needed to allow proper+// antialiasing of the font at *smaller* sizes)+//+// The function computes the SDF analytically at each SDF pixel, not by e.g.+// building a higher-res bitmap and approximating it. In theory the quality+// should be as high as possible for an SDF of this size & representation, but+// unclear if this is true in practice (perhaps building a higher-res bitmap+// and computing from that can allow drop-out prevention).+//+// The algorithm has not been optimized at all, so expect it to be slow+// if computing lots of characters or very large sizes.++++//////////////////////////////////////////////////////////////////////////////+//+// Finding the right font...+//+// You should really just solve this offline, keep your own tables+// of what font is what, and don't try to get it out of the .ttf file.+// That's because getting it out of the .ttf file is really hard, because+// the names in the file can appear in many possible encodings, in many+// possible languages, and e.g. if you need a case-insensitive comparison,+// the details of that depend on the encoding & language in a complex way+// (actually underspecified in truetype, but also gigantic).+//+// But you can use the provided functions in two possible ways:+// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on+// unicode-encoded names to try to find the font you want;+// you can run this before calling stbtt_InitFont()+//+// stbtt_GetFontNameString() lets you get any of the various strings+// from the file yourself and do your own comparisons on them.+// You have to have called stbtt_InitFont() first.+++STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);+// returns the offset (not index) of the font that matches, or -1 if none+// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".+// if you use any other flag, use a font name like "Arial"; this checks+// the 'macStyle' header field; i don't know if fonts set this consistently+#define STBTT_MACSTYLE_DONTCARE 0+#define STBTT_MACSTYLE_BOLD 1+#define STBTT_MACSTYLE_ITALIC 2+#define STBTT_MACSTYLE_UNDERSCORE 4+#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0++STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);+// returns 1/0 whether the first string interpreted as utf8 is identical to+// the second string interpreted as big-endian utf16... useful for strings from next func++STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);+// returns the string (which may be big-endian double byte, e.g. for unicode)+// and puts the length in bytes in *length.+//+// some of the values for the IDs are below; for more see the truetype spec:+// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html+// http://www.microsoft.com/typography/otspec/name.htm++enum { // platformID+ STBTT_PLATFORM_ID_UNICODE =0,+ STBTT_PLATFORM_ID_MAC =1,+ STBTT_PLATFORM_ID_ISO =2,+ STBTT_PLATFORM_ID_MICROSOFT =3+};++enum { // encodingID for STBTT_PLATFORM_ID_UNICODE+ STBTT_UNICODE_EID_UNICODE_1_0 =0,+ STBTT_UNICODE_EID_UNICODE_1_1 =1,+ STBTT_UNICODE_EID_ISO_10646 =2,+ STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,+ STBTT_UNICODE_EID_UNICODE_2_0_FULL=4+};++enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT+ STBTT_MS_EID_SYMBOL =0,+ STBTT_MS_EID_UNICODE_BMP =1,+ STBTT_MS_EID_SHIFTJIS =2,+ STBTT_MS_EID_UNICODE_FULL =10+};++enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes+ STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,+ STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,+ STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,+ STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7+};++enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...+ // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs+ STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,+ STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,+ STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,+ STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,+ STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,+ STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D+};++enum { // languageID for STBTT_PLATFORM_ID_MAC+ STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,+ STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,+ STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,+ STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,+ STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,+ STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,+ STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19+};++#ifdef __cplusplus+}+#endif++#endif // __STB_INCLUDE_STB_TRUETYPE_H__++///////////////////////////////////////////////////////////////////////////////+///////////////////////////////////////////////////////////////////////////////+////+//// IMPLEMENTATION+////+////++#ifdef STB_TRUETYPE_IMPLEMENTATION++#ifndef STBTT_MAX_OVERSAMPLE+#define STBTT_MAX_OVERSAMPLE 8+#endif++#if STBTT_MAX_OVERSAMPLE > 255+#error "STBTT_MAX_OVERSAMPLE cannot be > 255"+#endif++typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];++#ifndef STBTT_RASTERIZER_VERSION+#define STBTT_RASTERIZER_VERSION 2+#endif++#ifdef _MSC_VER+#define STBTT__NOTUSED(v) (void)(v)+#else+#define STBTT__NOTUSED(v) (void)sizeof(v)+#endif++//////////////////////////////////////////////////////////////////////////+//+// stbtt__buf helpers to parse data from file+//++static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)+{+ if (b->cursor >= b->size)+ return 0;+ return b->data[b->cursor++];+}++static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)+{+ if (b->cursor >= b->size)+ return 0;+ return b->data[b->cursor];+}++static void stbtt__buf_seek(stbtt__buf *b, int o)+{+ STBTT_assert(!(o > b->size || o < 0));+ b->cursor = (o > b->size || o < 0) ? b->size : o;+}++static void stbtt__buf_skip(stbtt__buf *b, int o)+{+ stbtt__buf_seek(b, b->cursor + o);+}++static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)+{+ stbtt_uint32 v = 0;+ int i;+ STBTT_assert(n >= 1 && n <= 4);+ for (i = 0; i < n; i++)+ v = (v << 8) | stbtt__buf_get8(b);+ return v;+}++static stbtt__buf stbtt__new_buf(const void *p, size_t size)+{+ stbtt__buf r;+ STBTT_assert(size < 0x40000000);+ r.data = (stbtt_uint8*) p;+ r.size = (int) size;+ r.cursor = 0;+ return r;+}++#define stbtt__buf_get16(b) stbtt__buf_get((b), 2)+#define stbtt__buf_get32(b) stbtt__buf_get((b), 4)++static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)+{+ stbtt__buf r = stbtt__new_buf(NULL, 0);+ if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;+ r.data = b->data + o;+ r.size = s;+ return r;+}++static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)+{+ int count, start, offsize;+ start = b->cursor;+ count = stbtt__buf_get16(b);+ if (count) {+ offsize = stbtt__buf_get8(b);+ STBTT_assert(offsize >= 1 && offsize <= 4);+ stbtt__buf_skip(b, offsize * count);+ stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);+ }+ return stbtt__buf_range(b, start, b->cursor - start);+}++static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)+{+ int b0 = stbtt__buf_get8(b);+ if (b0 >= 32 && b0 <= 246) return b0 - 139;+ else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;+ else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;+ else if (b0 == 28) return stbtt__buf_get16(b);+ else if (b0 == 29) return stbtt__buf_get32(b);+ STBTT_assert(0);+ return 0;+}++static void stbtt__cff_skip_operand(stbtt__buf *b) {+ int v, b0 = stbtt__buf_peek8(b);+ STBTT_assert(b0 >= 28);+ if (b0 == 30) {+ stbtt__buf_skip(b, 1);+ while (b->cursor < b->size) {+ v = stbtt__buf_get8(b);+ if ((v & 0xF) == 0xF || (v >> 4) == 0xF)+ break;+ }+ } else {+ stbtt__cff_int(b);+ }+}++static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)+{+ stbtt__buf_seek(b, 0);+ while (b->cursor < b->size) {+ int start = b->cursor, end, op;+ while (stbtt__buf_peek8(b) >= 28)+ stbtt__cff_skip_operand(b);+ end = b->cursor;+ op = stbtt__buf_get8(b);+ if (op == 12) op = stbtt__buf_get8(b) | 0x100;+ if (op == key) return stbtt__buf_range(b, start, end-start);+ }+ return stbtt__buf_range(b, 0, 0);+}++static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)+{+ int i;+ stbtt__buf operands = stbtt__dict_get(b, key);+ for (i = 0; i < outcount && operands.cursor < operands.size; i++)+ out[i] = stbtt__cff_int(&operands);+}++static int stbtt__cff_index_count(stbtt__buf *b)+{+ stbtt__buf_seek(b, 0);+ return stbtt__buf_get16(b);+}++static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)+{+ int count, offsize, start, end;+ stbtt__buf_seek(&b, 0);+ count = stbtt__buf_get16(&b);+ offsize = stbtt__buf_get8(&b);+ STBTT_assert(i >= 0 && i < count);+ STBTT_assert(offsize >= 1 && offsize <= 4);+ stbtt__buf_skip(&b, i*offsize);+ start = stbtt__buf_get(&b, offsize);+ end = stbtt__buf_get(&b, offsize);+ return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);+}++//////////////////////////////////////////////////////////////////////////+//+// accessors to parse data from file+//++// on platforms that don't allow misaligned reads, if we want to allow+// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE++#define ttBYTE(p) (* (stbtt_uint8 *) (p))+#define ttCHAR(p) (* (stbtt_int8 *) (p))+#define ttFixed(p) ttLONG(p)++static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }+static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }+static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }+static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }++#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))+#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])++static int stbtt__isfont(stbtt_uint8 *font)+{+ // check the version number+ if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1+ if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!+ if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF+ if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0+ if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts+ return 0;+}++// @OPTIMIZE: binary search+static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)+{+ stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);+ stbtt_uint32 tabledir = fontstart + 12;+ stbtt_int32 i;+ for (i=0; i < num_tables; ++i) {+ stbtt_uint32 loc = tabledir + 16*i;+ if (stbtt_tag(data+loc+0, tag))+ return ttULONG(data+loc+8);+ }+ return 0;+}++static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)+{+ // if it's just a font, there's only one valid index+ if (stbtt__isfont(font_collection))+ return index == 0 ? 0 : -1;++ // check if it's a TTC+ if (stbtt_tag(font_collection, "ttcf")) {+ // version 1?+ if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {+ stbtt_int32 n = ttLONG(font_collection+8);+ if (index >= n)+ return -1;+ return ttULONG(font_collection+12+index*4);+ }+ }+ return -1;+}++static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)+{+ // if it's just a font, there's only one valid font+ if (stbtt__isfont(font_collection))+ return 1;++ // check if it's a TTC+ if (stbtt_tag(font_collection, "ttcf")) {+ // version 1?+ if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {+ return ttLONG(font_collection+8);+ }+ }+ return 0;+}++static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)+{+ stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };+ stbtt__buf pdict;+ stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);+ if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);+ pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);+ stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);+ if (!subrsoff) return stbtt__new_buf(NULL, 0);+ stbtt__buf_seek(&cff, private_loc[1]+subrsoff);+ return stbtt__cff_get_index(&cff);+}++// since most people won't use this, find this table the first time it's needed+static int stbtt__get_svg(stbtt_fontinfo *info)+{+ stbtt_uint32 t;+ if (info->svg < 0) {+ t = stbtt__find_table(info->data, info->fontstart, "SVG ");+ if (t) {+ stbtt_uint32 offset = ttULONG(info->data + t + 2);+ info->svg = t + offset;+ } else {+ info->svg = 0;+ }+ }+ return info->svg;+}++static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)+{+ stbtt_uint32 cmap, t;+ stbtt_int32 i,numTables;++ info->data = data;+ info->fontstart = fontstart;+ info->cff = stbtt__new_buf(NULL, 0);++ cmap = stbtt__find_table(data, fontstart, "cmap"); // required+ info->loca = stbtt__find_table(data, fontstart, "loca"); // required+ info->head = stbtt__find_table(data, fontstart, "head"); // required+ info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required+ info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required+ info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required+ info->kern = stbtt__find_table(data, fontstart, "kern"); // not required+ info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required++ if (!cmap || !info->head || !info->hhea || !info->hmtx)+ return 0;+ if (info->glyf) {+ // required for truetype+ if (!info->loca) return 0;+ } else {+ // initialization for CFF / Type2 fonts (OTF)+ stbtt__buf b, topdict, topdictidx;+ stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;+ stbtt_uint32 cff;++ cff = stbtt__find_table(data, fontstart, "CFF ");+ if (!cff) return 0;++ info->fontdicts = stbtt__new_buf(NULL, 0);+ info->fdselect = stbtt__new_buf(NULL, 0);++ // @TODO this should use size from table (not 512MB)+ info->cff = stbtt__new_buf(data+cff, 512*1024*1024);+ b = info->cff;++ // read the header+ stbtt__buf_skip(&b, 2);+ stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize++ // @TODO the name INDEX could list multiple fonts,+ // but we just use the first one.+ stbtt__cff_get_index(&b); // name INDEX+ topdictidx = stbtt__cff_get_index(&b);+ topdict = stbtt__cff_index_get(topdictidx, 0);+ stbtt__cff_get_index(&b); // string INDEX+ info->gsubrs = stbtt__cff_get_index(&b);++ stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);+ stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);+ stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);+ stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);+ info->subrs = stbtt__get_subrs(b, topdict);++ // we only support Type 2 charstrings+ if (cstype != 2) return 0;+ if (charstrings == 0) return 0;++ if (fdarrayoff) {+ // looks like a CID font+ if (!fdselectoff) return 0;+ stbtt__buf_seek(&b, fdarrayoff);+ info->fontdicts = stbtt__cff_get_index(&b);+ info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);+ }++ stbtt__buf_seek(&b, charstrings);+ info->charstrings = stbtt__cff_get_index(&b);+ }++ t = stbtt__find_table(data, fontstart, "maxp");+ if (t)+ info->numGlyphs = ttUSHORT(data+t+4);+ else+ info->numGlyphs = 0xffff;++ info->svg = -1;++ // find a cmap encoding table we understand *now* to avoid searching+ // later. (todo: could make this installable)+ // the same regardless of glyph.+ numTables = ttUSHORT(data + cmap + 2);+ info->index_map = 0;+ for (i=0; i < numTables; ++i) {+ stbtt_uint32 encoding_record = cmap + 4 + 8 * i;+ // find an encoding we understand:+ switch(ttUSHORT(data+encoding_record)) {+ case STBTT_PLATFORM_ID_MICROSOFT:+ switch (ttUSHORT(data+encoding_record+2)) {+ case STBTT_MS_EID_UNICODE_BMP:+ case STBTT_MS_EID_UNICODE_FULL:+ // MS/Unicode+ info->index_map = cmap + ttULONG(data+encoding_record+4);+ break;+ }+ break;+ case STBTT_PLATFORM_ID_UNICODE:+ // Mac/iOS has these+ // all the encodingIDs are unicode, so we don't bother to check it+ info->index_map = cmap + ttULONG(data+encoding_record+4);+ break;+ }+ }+ if (info->index_map == 0)+ return 0;++ info->indexToLocFormat = ttUSHORT(data+info->head + 50);+ return 1;+}++STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)+{+ stbtt_uint8 *data = info->data;+ stbtt_uint32 index_map = info->index_map;++ stbtt_uint16 format = ttUSHORT(data + index_map + 0);+ if (format == 0) { // apple byte encoding+ stbtt_int32 bytes = ttUSHORT(data + index_map + 2);+ if (unicode_codepoint < bytes-6)+ return ttBYTE(data + index_map + 6 + unicode_codepoint);+ return 0;+ } else if (format == 6) {+ stbtt_uint32 first = ttUSHORT(data + index_map + 6);+ stbtt_uint32 count = ttUSHORT(data + index_map + 8);+ if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)+ return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);+ return 0;+ } else if (format == 2) {+ STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean+ return 0;+ } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges+ stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;+ stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;+ stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);+ stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;++ // do a binary search of the segments+ stbtt_uint32 endCount = index_map + 14;+ stbtt_uint32 search = endCount;++ if (unicode_codepoint > 0xffff)+ return 0;++ // they lie from endCount .. endCount + segCount+ // but searchRange is the nearest power of two, so...+ if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))+ search += rangeShift*2;++ // now decrement to bias correctly to find smallest+ search -= 2;+ while (entrySelector) {+ stbtt_uint16 end;+ searchRange >>= 1;+ end = ttUSHORT(data + search + searchRange*2);+ if (unicode_codepoint > end)+ search += searchRange*2;+ --entrySelector;+ }+ search += 2;++ {+ stbtt_uint16 offset, start, last;+ stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);++ start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);+ last = ttUSHORT(data + endCount + 2*item);+ if (unicode_codepoint < start || unicode_codepoint > last)+ return 0;++ offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);+ if (offset == 0)+ return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));++ return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);+ }+ } else if (format == 12 || format == 13) {+ stbtt_uint32 ngroups = ttULONG(data+index_map+12);+ stbtt_int32 low,high;+ low = 0; high = (stbtt_int32)ngroups;+ // Binary search the right group.+ while (low < high) {+ stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high+ stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);+ stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);+ if ((stbtt_uint32) unicode_codepoint < start_char)+ high = mid;+ else if ((stbtt_uint32) unicode_codepoint > end_char)+ low = mid+1;+ else {+ stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);+ if (format == 12)+ return start_glyph + unicode_codepoint-start_char;+ else // format == 13+ return start_glyph;+ }+ }+ return 0; // not found+ }+ // @TODO+ STBTT_assert(0);+ return 0;+}++STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)+{+ return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);+}++static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)+{+ v->type = type;+ v->x = (stbtt_int16) x;+ v->y = (stbtt_int16) y;+ v->cx = (stbtt_int16) cx;+ v->cy = (stbtt_int16) cy;+}++static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)+{+ int g1,g2;++ STBTT_assert(!info->cff.size);++ if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range+ if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format++ if (info->indexToLocFormat == 0) {+ g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;+ g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;+ } else {+ g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);+ g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);+ }++ return g1==g2 ? -1 : g1; // if length is 0, return -1+}++static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);++STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)+{+ if (info->cff.size) {+ stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);+ } else {+ int g = stbtt__GetGlyfOffset(info, glyph_index);+ if (g < 0) return 0;++ if (x0) *x0 = ttSHORT(info->data + g + 2);+ if (y0) *y0 = ttSHORT(info->data + g + 4);+ if (x1) *x1 = ttSHORT(info->data + g + 6);+ if (y1) *y1 = ttSHORT(info->data + g + 8);+ }+ return 1;+}++STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)+{+ return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);+}++STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)+{+ stbtt_int16 numberOfContours;+ int g;+ if (info->cff.size)+ return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;+ g = stbtt__GetGlyfOffset(info, glyph_index);+ if (g < 0) return 1;+ numberOfContours = ttSHORT(info->data + g);+ return numberOfContours == 0;+}++static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,+ stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)+{+ if (start_off) {+ if (was_off)+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);+ } else {+ if (was_off)+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);+ else+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);+ }+ return num_vertices;+}++static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)+{+ stbtt_int16 numberOfContours;+ stbtt_uint8 *endPtsOfContours;+ stbtt_uint8 *data = info->data;+ stbtt_vertex *vertices=0;+ int num_vertices=0;+ int g = stbtt__GetGlyfOffset(info, glyph_index);++ *pvertices = NULL;++ if (g < 0) return 0;++ numberOfContours = ttSHORT(data + g);++ if (numberOfContours > 0) {+ stbtt_uint8 flags=0,flagcount;+ stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;+ stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;+ stbtt_uint8 *points;+ endPtsOfContours = (data + g + 10);+ ins = ttUSHORT(data + g + 10 + numberOfContours * 2);+ points = data + g + 10 + numberOfContours * 2 + 2 + ins;++ n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);++ m = n + 2*numberOfContours; // a loose bound on how many vertices we might need+ vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);+ if (vertices == 0)+ return 0;++ next_move = 0;+ flagcount=0;++ // in first pass, we load uninterpreted data into the allocated array+ // above, shifted to the end of the array so we won't overwrite it when+ // we create our final data starting from the front++ off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated++ // first load flags++ for (i=0; i < n; ++i) {+ if (flagcount == 0) {+ flags = *points++;+ if (flags & 8)+ flagcount = *points++;+ } else+ --flagcount;+ vertices[off+i].type = flags;+ }++ // now load x coordinates+ x=0;+ for (i=0; i < n; ++i) {+ flags = vertices[off+i].type;+ if (flags & 2) {+ stbtt_int16 dx = *points++;+ x += (flags & 16) ? dx : -dx; // ???+ } else {+ if (!(flags & 16)) {+ x = x + (stbtt_int16) (points[0]*256 + points[1]);+ points += 2;+ }+ }+ vertices[off+i].x = (stbtt_int16) x;+ }++ // now load y coordinates+ y=0;+ for (i=0; i < n; ++i) {+ flags = vertices[off+i].type;+ if (flags & 4) {+ stbtt_int16 dy = *points++;+ y += (flags & 32) ? dy : -dy; // ???+ } else {+ if (!(flags & 32)) {+ y = y + (stbtt_int16) (points[0]*256 + points[1]);+ points += 2;+ }+ }+ vertices[off+i].y = (stbtt_int16) y;+ }++ // now convert them to our format+ num_vertices=0;+ sx = sy = cx = cy = scx = scy = 0;+ for (i=0; i < n; ++i) {+ flags = vertices[off+i].type;+ x = (stbtt_int16) vertices[off+i].x;+ y = (stbtt_int16) vertices[off+i].y;++ if (next_move == i) {+ if (i != 0)+ num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);++ // now start the new one+ start_off = !(flags & 1);+ if (start_off) {+ // if we start off with an off-curve point, then when we need to find a point on the curve+ // where we can start, and we need to save some state for when we wraparound.+ scx = x;+ scy = y;+ if (!(vertices[off+i+1].type & 1)) {+ // next point is also a curve point, so interpolate an on-point curve+ sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;+ sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;+ } else {+ // otherwise just use the next point as our start point+ sx = (stbtt_int32) vertices[off+i+1].x;+ sy = (stbtt_int32) vertices[off+i+1].y;+ ++i; // we're using point i+1 as the starting point, so skip it+ }+ } else {+ sx = x;+ sy = y;+ }+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);+ was_off = 0;+ next_move = 1 + ttUSHORT(endPtsOfContours+j*2);+ ++j;+ } else {+ if (!(flags & 1)) { // if it's a curve+ if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);+ cx = x;+ cy = y;+ was_off = 1;+ } else {+ if (was_off)+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);+ else+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);+ was_off = 0;+ }+ }+ }+ num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);+ } else if (numberOfContours < 0) {+ // Compound shapes.+ int more = 1;+ stbtt_uint8 *comp = data + g + 10;+ num_vertices = 0;+ vertices = 0;+ while (more) {+ stbtt_uint16 flags, gidx;+ int comp_num_verts = 0, i;+ stbtt_vertex *comp_verts = 0, *tmp = 0;+ float mtx[6] = {1,0,0,1,0,0}, m, n;++ flags = ttSHORT(comp); comp+=2;+ gidx = ttSHORT(comp); comp+=2;++ if (flags & 2) { // XY values+ if (flags & 1) { // shorts+ mtx[4] = ttSHORT(comp); comp+=2;+ mtx[5] = ttSHORT(comp); comp+=2;+ } else {+ mtx[4] = ttCHAR(comp); comp+=1;+ mtx[5] = ttCHAR(comp); comp+=1;+ }+ }+ else {+ // @TODO handle matching point+ STBTT_assert(0);+ }+ if (flags & (1<<3)) { // WE_HAVE_A_SCALE+ mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;+ mtx[1] = mtx[2] = 0;+ } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;+ mtx[1] = mtx[2] = 0;+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;+ } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;+ mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;+ mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;+ }++ // Find transformation scales.+ m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);+ n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);++ // Get indexed glyph.+ comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);+ if (comp_num_verts > 0) {+ // Transform vertices.+ for (i = 0; i < comp_num_verts; ++i) {+ stbtt_vertex* v = &comp_verts[i];+ stbtt_vertex_type x,y;+ x=v->x; y=v->y;+ v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));+ v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));+ x=v->cx; y=v->cy;+ v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));+ v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));+ }+ // Append vertices.+ tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);+ if (!tmp) {+ if (vertices) STBTT_free(vertices, info->userdata);+ if (comp_verts) STBTT_free(comp_verts, info->userdata);+ return 0;+ }+ if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));+ STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));+ if (vertices) STBTT_free(vertices, info->userdata);+ vertices = tmp;+ STBTT_free(comp_verts, info->userdata);+ num_vertices += comp_num_verts;+ }+ // More components ?+ more = flags & (1<<5);+ }+ } else {+ // numberOfCounters == 0, do nothing+ }++ *pvertices = vertices;+ return num_vertices;+}++typedef struct+{+ int bounds;+ int started;+ float first_x, first_y;+ float x, y;+ stbtt_int32 min_x, max_x, min_y, max_y;++ stbtt_vertex *pvertices;+ int num_vertices;+} stbtt__csctx;++#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}++static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)+{+ if (x > c->max_x || !c->started) c->max_x = x;+ if (y > c->max_y || !c->started) c->max_y = y;+ if (x < c->min_x || !c->started) c->min_x = x;+ if (y < c->min_y || !c->started) c->min_y = y;+ c->started = 1;+}++static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)+{+ if (c->bounds) {+ stbtt__track_vertex(c, x, y);+ if (type == STBTT_vcubic) {+ stbtt__track_vertex(c, cx, cy);+ stbtt__track_vertex(c, cx1, cy1);+ }+ } else {+ stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);+ c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;+ c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;+ }+ c->num_vertices++;+}++static void stbtt__csctx_close_shape(stbtt__csctx *ctx)+{+ if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)+ stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);+}++static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)+{+ stbtt__csctx_close_shape(ctx);+ ctx->first_x = ctx->x = ctx->x + dx;+ ctx->first_y = ctx->y = ctx->y + dy;+ stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);+}++static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)+{+ ctx->x += dx;+ ctx->y += dy;+ stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);+}++static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)+{+ float cx1 = ctx->x + dx1;+ float cy1 = ctx->y + dy1;+ float cx2 = cx1 + dx2;+ float cy2 = cy1 + dy2;+ ctx->x = cx2 + dx3;+ ctx->y = cy2 + dy3;+ stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);+}++static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)+{+ int count = stbtt__cff_index_count(&idx);+ int bias = 107;+ if (count >= 33900)+ bias = 32768;+ else if (count >= 1240)+ bias = 1131;+ n += bias;+ if (n < 0 || n >= count)+ return stbtt__new_buf(NULL, 0);+ return stbtt__cff_index_get(idx, n);+}++static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)+{+ stbtt__buf fdselect = info->fdselect;+ int nranges, start, end, v, fmt, fdselector = -1, i;++ stbtt__buf_seek(&fdselect, 0);+ fmt = stbtt__buf_get8(&fdselect);+ if (fmt == 0) {+ // untested+ stbtt__buf_skip(&fdselect, glyph_index);+ fdselector = stbtt__buf_get8(&fdselect);+ } else if (fmt == 3) {+ nranges = stbtt__buf_get16(&fdselect);+ start = stbtt__buf_get16(&fdselect);+ for (i = 0; i < nranges; i++) {+ v = stbtt__buf_get8(&fdselect);+ end = stbtt__buf_get16(&fdselect);+ if (glyph_index >= start && glyph_index < end) {+ fdselector = v;+ break;+ }+ start = end;+ }+ }+ if (fdselector == -1) stbtt__new_buf(NULL, 0);+ return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));+}++static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)+{+ int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;+ int has_subrs = 0, clear_stack;+ float s[48];+ stbtt__buf subr_stack[10], subrs = info->subrs, b;+ float f;++#define STBTT__CSERR(s) (0)++ // this currently ignores the initial width value, which isn't needed if we have hmtx+ b = stbtt__cff_index_get(info->charstrings, glyph_index);+ while (b.cursor < b.size) {+ i = 0;+ clear_stack = 1;+ b0 = stbtt__buf_get8(&b);+ switch (b0) {+ // @TODO implement hinting+ case 0x13: // hintmask+ case 0x14: // cntrmask+ if (in_header)+ maskbits += (sp / 2); // implicit "vstem"+ in_header = 0;+ stbtt__buf_skip(&b, (maskbits + 7) / 8);+ break;++ case 0x01: // hstem+ case 0x03: // vstem+ case 0x12: // hstemhm+ case 0x17: // vstemhm+ maskbits += (sp / 2);+ break;++ case 0x15: // rmoveto+ in_header = 0;+ if (sp < 2) return STBTT__CSERR("rmoveto stack");+ stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);+ break;+ case 0x04: // vmoveto+ in_header = 0;+ if (sp < 1) return STBTT__CSERR("vmoveto stack");+ stbtt__csctx_rmove_to(c, 0, s[sp-1]);+ break;+ case 0x16: // hmoveto+ in_header = 0;+ if (sp < 1) return STBTT__CSERR("hmoveto stack");+ stbtt__csctx_rmove_to(c, s[sp-1], 0);+ break;++ case 0x05: // rlineto+ if (sp < 2) return STBTT__CSERR("rlineto stack");+ for (; i + 1 < sp; i += 2)+ stbtt__csctx_rline_to(c, s[i], s[i+1]);+ break;++ // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical+ // starting from a different place.++ case 0x07: // vlineto+ if (sp < 1) return STBTT__CSERR("vlineto stack");+ goto vlineto;+ case 0x06: // hlineto+ if (sp < 1) return STBTT__CSERR("hlineto stack");+ for (;;) {+ if (i >= sp) break;+ stbtt__csctx_rline_to(c, s[i], 0);+ i++;+ vlineto:+ if (i >= sp) break;+ stbtt__csctx_rline_to(c, 0, s[i]);+ i++;+ }+ break;++ case 0x1F: // hvcurveto+ if (sp < 4) return STBTT__CSERR("hvcurveto stack");+ goto hvcurveto;+ case 0x1E: // vhcurveto+ if (sp < 4) return STBTT__CSERR("vhcurveto stack");+ for (;;) {+ if (i + 3 >= sp) break;+ stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);+ i += 4;+ hvcurveto:+ if (i + 3 >= sp) break;+ stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);+ i += 4;+ }+ break;++ case 0x08: // rrcurveto+ if (sp < 6) return STBTT__CSERR("rcurveline stack");+ for (; i + 5 < sp; i += 6)+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);+ break;++ case 0x18: // rcurveline+ if (sp < 8) return STBTT__CSERR("rcurveline stack");+ for (; i + 5 < sp - 2; i += 6)+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);+ if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");+ stbtt__csctx_rline_to(c, s[i], s[i+1]);+ break;++ case 0x19: // rlinecurve+ if (sp < 8) return STBTT__CSERR("rlinecurve stack");+ for (; i + 1 < sp - 6; i += 2)+ stbtt__csctx_rline_to(c, s[i], s[i+1]);+ if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);+ break;++ case 0x1A: // vvcurveto+ case 0x1B: // hhcurveto+ if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");+ f = 0.0;+ if (sp & 1) { f = s[i]; i++; }+ for (; i + 3 < sp; i += 4) {+ if (b0 == 0x1B)+ stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);+ else+ stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);+ f = 0.0;+ }+ break;++ case 0x0A: // callsubr+ if (!has_subrs) {+ if (info->fdselect.size)+ subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);+ has_subrs = 1;+ }+ // FALLTHROUGH+ case 0x1D: // callgsubr+ if (sp < 1) return STBTT__CSERR("call(g|)subr stack");+ v = (int) s[--sp];+ if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");+ subr_stack[subr_stack_height++] = b;+ b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);+ if (b.size == 0) return STBTT__CSERR("subr not found");+ b.cursor = 0;+ clear_stack = 0;+ break;++ case 0x0B: // return+ if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");+ b = subr_stack[--subr_stack_height];+ clear_stack = 0;+ break;++ case 0x0E: // endchar+ stbtt__csctx_close_shape(c);+ return 1;++ case 0x0C: { // two-byte escape+ float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;+ float dx, dy;+ int b1 = stbtt__buf_get8(&b);+ switch (b1) {+ // @TODO These "flex" implementations ignore the flex-depth and resolution,+ // and always draw beziers.+ case 0x22: // hflex+ if (sp < 7) return STBTT__CSERR("hflex stack");+ dx1 = s[0];+ dx2 = s[1];+ dy2 = s[2];+ dx3 = s[3];+ dx4 = s[4];+ dx5 = s[5];+ dx6 = s[6];+ stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);+ stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);+ break;++ case 0x23: // flex+ if (sp < 13) return STBTT__CSERR("flex stack");+ dx1 = s[0];+ dy1 = s[1];+ dx2 = s[2];+ dy2 = s[3];+ dx3 = s[4];+ dy3 = s[5];+ dx4 = s[6];+ dy4 = s[7];+ dx5 = s[8];+ dy5 = s[9];+ dx6 = s[10];+ dy6 = s[11];+ //fd is s[12]+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);+ stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);+ break;++ case 0x24: // hflex1+ if (sp < 9) return STBTT__CSERR("hflex1 stack");+ dx1 = s[0];+ dy1 = s[1];+ dx2 = s[2];+ dy2 = s[3];+ dx3 = s[4];+ dx4 = s[5];+ dx5 = s[6];+ dy5 = s[7];+ dx6 = s[8];+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);+ stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));+ break;++ case 0x25: // flex1+ if (sp < 11) return STBTT__CSERR("flex1 stack");+ dx1 = s[0];+ dy1 = s[1];+ dx2 = s[2];+ dy2 = s[3];+ dx3 = s[4];+ dy3 = s[5];+ dx4 = s[6];+ dy4 = s[7];+ dx5 = s[8];+ dy5 = s[9];+ dx6 = dy6 = s[10];+ dx = dx1+dx2+dx3+dx4+dx5;+ dy = dy1+dy2+dy3+dy4+dy5;+ if (STBTT_fabs(dx) > STBTT_fabs(dy))+ dy6 = -dy;+ else+ dx6 = -dx;+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);+ stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);+ break;++ default:+ return STBTT__CSERR("unimplemented");+ }+ } break;++ default:+ if (b0 != 255 && b0 != 28 && b0 < 32)+ return STBTT__CSERR("reserved operator");++ // push immediate+ if (b0 == 255) {+ f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;+ } else {+ stbtt__buf_skip(&b, -1);+ f = (float)(stbtt_int16)stbtt__cff_int(&b);+ }+ if (sp >= 48) return STBTT__CSERR("push stack overflow");+ s[sp++] = f;+ clear_stack = 0;+ break;+ }+ if (clear_stack) sp = 0;+ }+ return STBTT__CSERR("no endchar");++#undef STBTT__CSERR+}++static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)+{+ // runs the charstring twice, once to count and once to output (to avoid realloc)+ stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);+ stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);+ if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {+ *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);+ output_ctx.pvertices = *pvertices;+ if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {+ STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);+ return output_ctx.num_vertices;+ }+ }+ *pvertices = NULL;+ return 0;+}++static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)+{+ stbtt__csctx c = STBTT__CSCTX_INIT(1);+ int r = stbtt__run_charstring(info, glyph_index, &c);+ if (x0) *x0 = r ? c.min_x : 0;+ if (y0) *y0 = r ? c.min_y : 0;+ if (x1) *x1 = r ? c.max_x : 0;+ if (y1) *y1 = r ? c.max_y : 0;+ return r ? c.num_vertices : 0;+}++STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)+{+ if (!info->cff.size)+ return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);+ else+ return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);+}++STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)+{+ stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);+ if (glyph_index < numOfLongHorMetrics) {+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);+ } else {+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));+ }+}++STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info)+{+ stbtt_uint8 *data = info->data + info->kern;++ // we only look at the first table. it must be 'horizontal' and format 0.+ if (!info->kern)+ return 0;+ if (ttUSHORT(data+2) < 1) // number of tables, need at least 1+ return 0;+ if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format+ return 0;++ return ttUSHORT(data+10);+}++STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length)+{+ stbtt_uint8 *data = info->data + info->kern;+ int k, length;++ // we only look at the first table. it must be 'horizontal' and format 0.+ if (!info->kern)+ return 0;+ if (ttUSHORT(data+2) < 1) // number of tables, need at least 1+ return 0;+ if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format+ return 0;++ length = ttUSHORT(data+10);+ if (table_length < length)+ length = table_length;++ for (k = 0; k < length; k++)+ {+ table[k].glyph1 = ttUSHORT(data+18+(k*6));+ table[k].glyph2 = ttUSHORT(data+20+(k*6));+ table[k].advance = ttSHORT(data+22+(k*6));+ }++ return length;+}++static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)+{+ stbtt_uint8 *data = info->data + info->kern;+ stbtt_uint32 needle, straw;+ int l, r, m;++ // we only look at the first table. it must be 'horizontal' and format 0.+ if (!info->kern)+ return 0;+ if (ttUSHORT(data+2) < 1) // number of tables, need at least 1+ return 0;+ if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format+ return 0;++ l = 0;+ r = ttUSHORT(data+10) - 1;+ needle = glyph1 << 16 | glyph2;+ while (l <= r) {+ m = (l + r) >> 1;+ straw = ttULONG(data+18+(m*6)); // note: unaligned read+ if (needle < straw)+ r = m - 1;+ else if (needle > straw)+ l = m + 1;+ else+ return ttSHORT(data+22+(m*6));+ }+ return 0;+}++static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)+{+ stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);+ switch (coverageFormat) {+ case 1: {+ stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);++ // Binary search.+ stbtt_int32 l=0, r=glyphCount-1, m;+ int straw, needle=glyph;+ while (l <= r) {+ stbtt_uint8 *glyphArray = coverageTable + 4;+ stbtt_uint16 glyphID;+ m = (l + r) >> 1;+ glyphID = ttUSHORT(glyphArray + 2 * m);+ straw = glyphID;+ if (needle < straw)+ r = m - 1;+ else if (needle > straw)+ l = m + 1;+ else {+ return m;+ }+ }+ break;+ }++ case 2: {+ stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);+ stbtt_uint8 *rangeArray = coverageTable + 4;++ // Binary search.+ stbtt_int32 l=0, r=rangeCount-1, m;+ int strawStart, strawEnd, needle=glyph;+ while (l <= r) {+ stbtt_uint8 *rangeRecord;+ m = (l + r) >> 1;+ rangeRecord = rangeArray + 6 * m;+ strawStart = ttUSHORT(rangeRecord);+ strawEnd = ttUSHORT(rangeRecord + 2);+ if (needle < strawStart)+ r = m - 1;+ else if (needle > strawEnd)+ l = m + 1;+ else {+ stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);+ return startCoverageIndex + glyph - strawStart;+ }+ }+ break;+ }++ default: return -1; // unsupported+ }++ return -1;+}++static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)+{+ stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);+ switch (classDefFormat)+ {+ case 1: {+ stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);+ stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);+ stbtt_uint8 *classDef1ValueArray = classDefTable + 6;++ if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)+ return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));+ break;+ }++ case 2: {+ stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);+ stbtt_uint8 *classRangeRecords = classDefTable + 4;++ // Binary search.+ stbtt_int32 l=0, r=classRangeCount-1, m;+ int strawStart, strawEnd, needle=glyph;+ while (l <= r) {+ stbtt_uint8 *classRangeRecord;+ m = (l + r) >> 1;+ classRangeRecord = classRangeRecords + 6 * m;+ strawStart = ttUSHORT(classRangeRecord);+ strawEnd = ttUSHORT(classRangeRecord + 2);+ if (needle < strawStart)+ r = m - 1;+ else if (needle > strawEnd)+ l = m + 1;+ else+ return (stbtt_int32)ttUSHORT(classRangeRecord + 4);+ }+ break;+ }++ default:+ return -1; // Unsupported definition type, return an error.+ }++ // "All glyphs not assigned to a class fall into class 0". (OpenType spec)+ return 0;+}++// Define to STBTT_assert(x) if you want to break on unimplemented formats.+#define STBTT_GPOS_TODO_assert(x)++static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)+{+ stbtt_uint16 lookupListOffset;+ stbtt_uint8 *lookupList;+ stbtt_uint16 lookupCount;+ stbtt_uint8 *data;+ stbtt_int32 i, sti;++ if (!info->gpos) return 0;++ data = info->data + info->gpos;++ if (ttUSHORT(data+0) != 1) return 0; // Major version 1+ if (ttUSHORT(data+2) != 0) return 0; // Minor version 0++ lookupListOffset = ttUSHORT(data+8);+ lookupList = data + lookupListOffset;+ lookupCount = ttUSHORT(lookupList);++ for (i=0; i<lookupCount; ++i) {+ stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);+ stbtt_uint8 *lookupTable = lookupList + lookupOffset;++ stbtt_uint16 lookupType = ttUSHORT(lookupTable);+ stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);+ stbtt_uint8 *subTableOffsets = lookupTable + 6;+ if (lookupType != 2) // Pair Adjustment Positioning Subtable+ continue;++ for (sti=0; sti<subTableCount; sti++) {+ stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);+ stbtt_uint8 *table = lookupTable + subtableOffset;+ stbtt_uint16 posFormat = ttUSHORT(table);+ stbtt_uint16 coverageOffset = ttUSHORT(table + 2);+ stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);+ if (coverageIndex == -1) continue;++ switch (posFormat) {+ case 1: {+ stbtt_int32 l, r, m;+ int straw, needle;+ stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);+ stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);+ if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats?+ stbtt_int32 valueRecordPairSizeInBytes = 2;+ stbtt_uint16 pairSetCount = ttUSHORT(table + 8);+ stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);+ stbtt_uint8 *pairValueTable = table + pairPosOffset;+ stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);+ stbtt_uint8 *pairValueArray = pairValueTable + 2;++ if (coverageIndex >= pairSetCount) return 0;++ needle=glyph2;+ r=pairValueCount-1;+ l=0;++ // Binary search.+ while (l <= r) {+ stbtt_uint16 secondGlyph;+ stbtt_uint8 *pairValue;+ m = (l + r) >> 1;+ pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;+ secondGlyph = ttUSHORT(pairValue);+ straw = secondGlyph;+ if (needle < straw)+ r = m - 1;+ else if (needle > straw)+ l = m + 1;+ else {+ stbtt_int16 xAdvance = ttSHORT(pairValue + 2);+ return xAdvance;+ }+ }+ } else+ return 0;+ break;+ }++ case 2: {+ stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);+ stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);+ if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats?+ stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);+ stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);+ int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);+ int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);++ stbtt_uint16 class1Count = ttUSHORT(table + 12);+ stbtt_uint16 class2Count = ttUSHORT(table + 14);+ stbtt_uint8 *class1Records, *class2Records;+ stbtt_int16 xAdvance;++ if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed+ if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed++ class1Records = table + 16;+ class2Records = class1Records + 2 * (glyph1class * class2Count);+ xAdvance = ttSHORT(class2Records + 2 * glyph2class);+ return xAdvance;+ } else+ return 0;+ break;+ }++ default:+ return 0; // Unsupported position format+ }+ }+ }++ return 0;+}++STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)+{+ int xAdvance = 0;++ if (info->gpos)+ xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);+ else if (info->kern)+ xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);++ return xAdvance;+}++STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)+{+ if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs+ return 0;+ return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));+}++STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)+{+ stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);+}++STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)+{+ if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);+ if (descent) *descent = ttSHORT(info->data+info->hhea + 6);+ if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);+}++STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)+{+ int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");+ if (!tab)+ return 0;+ if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68);+ if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);+ if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);+ return 1;+}++STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)+{+ *x0 = ttSHORT(info->data + info->head + 36);+ *y0 = ttSHORT(info->data + info->head + 38);+ *x1 = ttSHORT(info->data + info->head + 40);+ *y1 = ttSHORT(info->data + info->head + 42);+}++STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)+{+ int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);+ return (float) height / fheight;+}++STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)+{+ int unitsPerEm = ttUSHORT(info->data + info->head + 18);+ return pixels / unitsPerEm;+}++STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)+{+ STBTT_free(v, info->userdata);+}++STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl)+{+ int i;+ stbtt_uint8 *data = info->data;+ stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info);++ int numEntries = ttUSHORT(svg_doc_list);+ stbtt_uint8 *svg_docs = svg_doc_list + 2;++ for(i=0; i<numEntries; i++) {+ stbtt_uint8 *svg_doc = svg_docs + (12 * i);+ if ((gl >= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2)))+ return svg_doc;+ }+ return 0;+}++STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg)+{+ stbtt_uint8 *data = info->data;+ stbtt_uint8 *svg_doc;++ if (info->svg == 0)+ return 0;++ svg_doc = stbtt_FindSVGDoc(info, gl);+ if (svg_doc != NULL) {+ *svg = (char *) data + info->svg + ttULONG(svg_doc + 4);+ return ttULONG(svg_doc + 8);+ } else {+ return 0;+ }+}++STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg)+{+ return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg);+}++//////////////////////////////////////////////////////////////////////////////+//+// antialiasing software rasterizer+//++STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)+{+ int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning+ if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {+ // e.g. space character+ if (ix0) *ix0 = 0;+ if (iy0) *iy0 = 0;+ if (ix1) *ix1 = 0;+ if (iy1) *iy1 = 0;+ } else {+ // move to integral bboxes (treating pixels as little squares, what pixels get touched)?+ if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);+ if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);+ if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);+ if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);+ }+}++STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)+{+ stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);+}++STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)+{+ stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);+}++STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)+{+ stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);+}++//////////////////////////////////////////////////////////////////////////////+//+// Rasterizer++typedef struct stbtt__hheap_chunk+{+ struct stbtt__hheap_chunk *next;+} stbtt__hheap_chunk;++typedef struct stbtt__hheap+{+ struct stbtt__hheap_chunk *head;+ void *first_free;+ int num_remaining_in_head_chunk;+} stbtt__hheap;++static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)+{+ if (hh->first_free) {+ void *p = hh->first_free;+ hh->first_free = * (void **) p;+ return p;+ } else {+ if (hh->num_remaining_in_head_chunk == 0) {+ int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);+ stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);+ if (c == NULL)+ return NULL;+ c->next = hh->head;+ hh->head = c;+ hh->num_remaining_in_head_chunk = count;+ }+ --hh->num_remaining_in_head_chunk;+ return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;+ }+}++static void stbtt__hheap_free(stbtt__hheap *hh, void *p)+{+ *(void **) p = hh->first_free;+ hh->first_free = p;+}++static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)+{+ stbtt__hheap_chunk *c = hh->head;+ while (c) {+ stbtt__hheap_chunk *n = c->next;+ STBTT_free(c, userdata);+ c = n;+ }+}++typedef struct stbtt__edge {+ float x0,y0, x1,y1;+ int invert;+} stbtt__edge;+++typedef struct stbtt__active_edge+{+ struct stbtt__active_edge *next;+ #if STBTT_RASTERIZER_VERSION==1+ int x,dx;+ float ey;+ int direction;+ #elif STBTT_RASTERIZER_VERSION==2+ float fx,fdx,fdy;+ float direction;+ float sy;+ float ey;+ #else+ #error "Unrecognized value of STBTT_RASTERIZER_VERSION"+ #endif+} stbtt__active_edge;++#if STBTT_RASTERIZER_VERSION == 1+#define STBTT_FIXSHIFT 10+#define STBTT_FIX (1 << STBTT_FIXSHIFT)+#define STBTT_FIXMASK (STBTT_FIX-1)++static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)+{+ stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);+ float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);+ STBTT_assert(z != NULL);+ if (!z) return z;++ // round dx down to avoid overshooting+ if (dxdy < 0)+ z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);+ else+ z->dx = STBTT_ifloor(STBTT_FIX * dxdy);++ z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount+ z->x -= off_x * STBTT_FIX;++ z->ey = e->y1;+ z->next = 0;+ z->direction = e->invert ? 1 : -1;+ return z;+}+#elif STBTT_RASTERIZER_VERSION == 2+static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)+{+ stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);+ float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);+ STBTT_assert(z != NULL);+ //STBTT_assert(e->y0 <= start_point);+ if (!z) return z;+ z->fdx = dxdy;+ z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;+ z->fx = e->x0 + dxdy * (start_point - e->y0);+ z->fx -= off_x;+ z->direction = e->invert ? 1.0f : -1.0f;+ z->sy = e->y0;+ z->ey = e->y1;+ z->next = 0;+ return z;+}+#else+#error "Unrecognized value of STBTT_RASTERIZER_VERSION"+#endif++#if STBTT_RASTERIZER_VERSION == 1+// note: this routine clips fills that extend off the edges... ideally this+// wouldn't happen, but it could happen if the truetype glyph bounding boxes+// are wrong, or if the user supplies a too-small bitmap+static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)+{+ // non-zero winding fill+ int x0=0, w=0;++ while (e) {+ if (w == 0) {+ // if we're currently at zero, we need to record the edge start point+ x0 = e->x; w += e->direction;+ } else {+ int x1 = e->x; w += e->direction;+ // if we went to zero, we need to draw+ if (w == 0) {+ int i = x0 >> STBTT_FIXSHIFT;+ int j = x1 >> STBTT_FIXSHIFT;++ if (i < len && j >= 0) {+ if (i == j) {+ // x0,x1 are the same pixel, so compute combined coverage+ scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);+ } else {+ if (i >= 0) // add antialiasing for x0+ scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);+ else+ i = -1; // clip++ if (j < len) // add antialiasing for x1+ scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);+ else+ j = len; // clip++ for (++i; i < j; ++i) // fill pixels between x0 and x1+ scanline[i] = scanline[i] + (stbtt_uint8) max_weight;+ }+ }+ }+ }++ e = e->next;+ }+}++static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)+{+ stbtt__hheap hh = { 0, 0, 0 };+ stbtt__active_edge *active = NULL;+ int y,j=0;+ int max_weight = (255 / vsubsample); // weight per vertical scanline+ int s; // vertical subsample index+ unsigned char scanline_data[512], *scanline;++ if (result->w > 512)+ scanline = (unsigned char *) STBTT_malloc(result->w, userdata);+ else+ scanline = scanline_data;++ y = off_y * vsubsample;+ e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;++ while (j < result->h) {+ STBTT_memset(scanline, 0, result->w);+ for (s=0; s < vsubsample; ++s) {+ // find center of pixel for this scanline+ float scan_y = y + 0.5f;+ stbtt__active_edge **step = &active;++ // update all active edges;+ // remove all active edges that terminate before the center of this scanline+ while (*step) {+ stbtt__active_edge * z = *step;+ if (z->ey <= scan_y) {+ *step = z->next; // delete from list+ STBTT_assert(z->direction);+ z->direction = 0;+ stbtt__hheap_free(&hh, z);+ } else {+ z->x += z->dx; // advance to position for current scanline+ step = &((*step)->next); // advance through list+ }+ }++ // resort the list if needed+ for(;;) {+ int changed=0;+ step = &active;+ while (*step && (*step)->next) {+ if ((*step)->x > (*step)->next->x) {+ stbtt__active_edge *t = *step;+ stbtt__active_edge *q = t->next;++ t->next = q->next;+ q->next = t;+ *step = q;+ changed = 1;+ }+ step = &(*step)->next;+ }+ if (!changed) break;+ }++ // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline+ while (e->y0 <= scan_y) {+ if (e->y1 > scan_y) {+ stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);+ if (z != NULL) {+ // find insertion point+ if (active == NULL)+ active = z;+ else if (z->x < active->x) {+ // insert at front+ z->next = active;+ active = z;+ } else {+ // find thing to insert AFTER+ stbtt__active_edge *p = active;+ while (p->next && p->next->x < z->x)+ p = p->next;+ // at this point, p->next->x is NOT < z->x+ z->next = p->next;+ p->next = z;+ }+ }+ }+ ++e;+ }++ // now process all active edges in XOR fashion+ if (active)+ stbtt__fill_active_edges(scanline, result->w, active, max_weight);++ ++y;+ }+ STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);+ ++j;+ }++ stbtt__hheap_cleanup(&hh, userdata);++ if (scanline != scanline_data)+ STBTT_free(scanline, userdata);+}++#elif STBTT_RASTERIZER_VERSION == 2++// the edge passed in here does not cross the vertical line at x or the vertical line at x+1+// (i.e. it has already been clipped to those)+static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)+{+ if (y0 == y1) return;+ STBTT_assert(y0 < y1);+ STBTT_assert(e->sy <= e->ey);+ if (y0 > e->ey) return;+ if (y1 < e->sy) return;+ if (y0 < e->sy) {+ x0 += (x1-x0) * (e->sy - y0) / (y1-y0);+ y0 = e->sy;+ }+ if (y1 > e->ey) {+ x1 += (x1-x0) * (e->ey - y1) / (y1-y0);+ y1 = e->ey;+ }++ if (x0 == x)+ STBTT_assert(x1 <= x+1);+ else if (x0 == x+1)+ STBTT_assert(x1 >= x);+ else if (x0 <= x)+ STBTT_assert(x1 <= x);+ else if (x0 >= x+1)+ STBTT_assert(x1 >= x+1);+ else+ STBTT_assert(x1 >= x && x1 <= x+1);++ if (x0 <= x && x1 <= x)+ scanline[x] += e->direction * (y1-y0);+ else if (x0 >= x+1 && x1 >= x+1)+ ;+ else {+ STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);+ scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position+ }+}++static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width)+{+ STBTT_assert(top_width >= 0);+ STBTT_assert(bottom_width >= 0);+ return (top_width + bottom_width) / 2.0f * height;+}++static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1)+{+ return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0);+}++static float stbtt__sized_triangle_area(float height, float width)+{+ return height * width / 2;+}++static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)+{+ float y_bottom = y_top+1;++ while (e) {+ // brute force every pixel++ // compute intersection points with top & bottom+ STBTT_assert(e->ey >= y_top);++ if (e->fdx == 0) {+ float x0 = e->fx;+ if (x0 < len) {+ if (x0 >= 0) {+ stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);+ stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);+ } else {+ stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);+ }+ }+ } else {+ float x0 = e->fx;+ float dx = e->fdx;+ float xb = x0 + dx;+ float x_top, x_bottom;+ float sy0,sy1;+ float dy = e->fdy;+ STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);++ // compute endpoints of line segment clipped to this scanline (if the+ // line segment starts on this scanline. x0 is the intersection of the+ // line with y_top, but that may be off the line segment.+ if (e->sy > y_top) {+ x_top = x0 + dx * (e->sy - y_top);+ sy0 = e->sy;+ } else {+ x_top = x0;+ sy0 = y_top;+ }+ if (e->ey < y_bottom) {+ x_bottom = x0 + dx * (e->ey - y_top);+ sy1 = e->ey;+ } else {+ x_bottom = xb;+ sy1 = y_bottom;+ }++ if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {+ // from here on, we don't have to range check x values++ if ((int) x_top == (int) x_bottom) {+ float height;+ // simple case, only spans one pixel+ int x = (int) x_top;+ height = (sy1 - sy0) * e->direction;+ STBTT_assert(x >= 0 && x < len);+ scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f);+ scanline_fill[x] += height; // everything right of this pixel is filled+ } else {+ int x,x1,x2;+ float y_crossing, y_final, step, sign, area;+ // covers 2+ pixels+ if (x_top > x_bottom) {+ // flip scanline vertically; signed area is the same+ float t;+ sy0 = y_bottom - (sy0 - y_top);+ sy1 = y_bottom - (sy1 - y_top);+ t = sy0, sy0 = sy1, sy1 = t;+ t = x_bottom, x_bottom = x_top, x_top = t;+ dx = -dx;+ dy = -dy;+ t = x0, x0 = xb, xb = t;+ }+ STBTT_assert(dy >= 0);+ STBTT_assert(dx >= 0);++ x1 = (int) x_top;+ x2 = (int) x_bottom;+ // compute intersection with y axis at x1+1+ y_crossing = y_top + dy * (x1+1 - x0);++ // compute intersection with y axis at x2+ y_final = y_top + dy * (x2 - x0);++ // x1 x_top x2 x_bottom+ // y_top +------|-----+------------+------------+--------|---+------------++ // | | | | | |+ // | | | | | |+ // sy0 | Txxxxx|............|............|............|............|+ // y_crossing | *xxxxx.......|............|............|............|+ // | | xxxxx..|............|............|............|+ // | | /- xx*xxxx........|............|............|+ // | | dy < | xxxxxx..|............|............|+ // y_final | | \- | xx*xxx.........|............|+ // sy1 | | | | xxxxxB...|............|+ // | | | | | |+ // | | | | | |+ // y_bottom +------------+------------+------------+------------+------------++ //+ // goal is to measure the area covered by '.' in each pixel++ // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057+ // @TODO: maybe test against sy1 rather than y_bottom?+ if (y_crossing > y_bottom)+ y_crossing = y_bottom;++ sign = e->direction;++ // area of the rectangle covered from sy0..y_crossing+ area = sign * (y_crossing-sy0);++ // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing)+ scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top);++ // check if final y_crossing is blown up; no test case for this+ if (y_final > y_bottom) {+ y_final = y_bottom;+ dy = (y_final - y_crossing ) / (x2 - (x1+1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom+ }++ // in second pixel, area covered by line segment found in first pixel+ // is always a rectangle 1 wide * the height of that line segment; this+ // is exactly what the variable 'area' stores. it also gets a contribution+ // from the line segment within it. the THIRD pixel will get the first+ // pixel's rectangle contribution, the second pixel's rectangle contribution,+ // and its own contribution. the 'own contribution' is the same in every pixel except+ // the leftmost and rightmost, a trapezoid that slides down in each pixel.+ // the second pixel's contribution to the third pixel will be the+ // rectangle 1 wide times the height change in the second pixel, which is dy.++ step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x,+ // which multiplied by 1-pixel-width is how much pixel area changes for each step in x+ // so the area advances by 'step' every time++ for (x = x1+1; x < x2; ++x) {+ scanline[x] += area + step/2; // area of trapezoid is 1*step/2+ area += step;+ }+ STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down+ STBTT_assert(sy1 > y_final-0.01f);++ // area covered in the last pixel is the rectangle from all the pixels to the left,+ // plus the trapezoid filled by the line segment in this pixel all the way to the right edge+ scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f);++ // the rest of the line is filled based on the total height of the line segment in this pixel+ scanline_fill[x2] += sign * (sy1-sy0);+ }+ } else {+ // if edge goes outside of box we're drawing, we require+ // clipping logic. since this does not match the intended use+ // of this library, we use a different, very slow brute+ // force implementation+ // note though that this does happen some of the time because+ // x_top and x_bottom can be extrapolated at the top & bottom of+ // the shape and actually lie outside the bounding box+ int x;+ for (x=0; x < len; ++x) {+ // cases:+ //+ // there can be up to two intersections with the pixel. any intersection+ // with left or right edges can be handled by splitting into two (or three)+ // regions. intersections with top & bottom do not necessitate case-wise logic.+ //+ // the old way of doing this found the intersections with the left & right edges,+ // then used some simple logic to produce up to three segments in sorted order+ // from top-to-bottom. however, this had a problem: if an x edge was epsilon+ // across the x border, then the corresponding y position might not be distinct+ // from the other y segment, and it might ignored as an empty segment. to avoid+ // that, we need to explicitly produce segments based on x positions.++ // rename variables to clearly-defined pairs+ float y0 = y_top;+ float x1 = (float) (x);+ float x2 = (float) (x+1);+ float x3 = xb;+ float y3 = y_bottom;++ // x = e->x + e->dx * (y-y_top)+ // (y-y_top) = (x - e->x) / e->dx+ // y = (x - e->x) / e->dx + y_top+ float y1 = (x - x0) / dx + y_top;+ float y2 = (x+1 - x0) / dx + y_top;++ if (x0 < x1 && x3 > x2) { // three segments descending down-right+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);+ } else if (x3 < x1 && x0 > x2) { // three segments descending down-left+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);+ } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);+ } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);+ } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);+ } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);+ } else { // one segment+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);+ }+ }+ }+ }+ e = e->next;+ }+}++// directly AA rasterize edges w/o supersampling+static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)+{+ stbtt__hheap hh = { 0, 0, 0 };+ stbtt__active_edge *active = NULL;+ int y,j=0, i;+ float scanline_data[129], *scanline, *scanline2;++ STBTT__NOTUSED(vsubsample);++ if (result->w > 64)+ scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);+ else+ scanline = scanline_data;++ scanline2 = scanline + result->w;++ y = off_y;+ e[n].y0 = (float) (off_y + result->h) + 1;++ while (j < result->h) {+ // find center of pixel for this scanline+ float scan_y_top = y + 0.0f;+ float scan_y_bottom = y + 1.0f;+ stbtt__active_edge **step = &active;++ STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));+ STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));++ // update all active edges;+ // remove all active edges that terminate before the top of this scanline+ while (*step) {+ stbtt__active_edge * z = *step;+ if (z->ey <= scan_y_top) {+ *step = z->next; // delete from list+ STBTT_assert(z->direction);+ z->direction = 0;+ stbtt__hheap_free(&hh, z);+ } else {+ step = &((*step)->next); // advance through list+ }+ }++ // insert all edges that start before the bottom of this scanline+ while (e->y0 <= scan_y_bottom) {+ if (e->y0 != e->y1) {+ stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);+ if (z != NULL) {+ if (j == 0 && off_y != 0) {+ if (z->ey < scan_y_top) {+ // this can happen due to subpixel positioning and some kind of fp rounding error i think+ z->ey = scan_y_top;+ }+ }+ STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds+ // insert at front+ z->next = active;+ active = z;+ }+ }+ ++e;+ }++ // now process all active edges+ if (active)+ stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);++ {+ float sum = 0;+ for (i=0; i < result->w; ++i) {+ float k;+ int m;+ sum += scanline2[i];+ k = scanline[i] + sum;+ k = (float) STBTT_fabs(k)*255 + 0.5f;+ m = (int) k;+ if (m > 255) m = 255;+ result->pixels[j*result->stride + i] = (unsigned char) m;+ }+ }+ // advance all the edges+ step = &active;+ while (*step) {+ stbtt__active_edge *z = *step;+ z->fx += z->fdx; // advance to position for current scanline+ step = &((*step)->next); // advance through list+ }++ ++y;+ ++j;+ }++ stbtt__hheap_cleanup(&hh, userdata);++ if (scanline != scanline_data)+ STBTT_free(scanline, userdata);+}+#else+#error "Unrecognized value of STBTT_RASTERIZER_VERSION"+#endif++#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)++static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)+{+ int i,j;+ for (i=1; i < n; ++i) {+ stbtt__edge t = p[i], *a = &t;+ j = i;+ while (j > 0) {+ stbtt__edge *b = &p[j-1];+ int c = STBTT__COMPARE(a,b);+ if (!c) break;+ p[j] = p[j-1];+ --j;+ }+ if (i != j)+ p[j] = t;+ }+}++static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)+{+ /* threshold for transitioning to insertion sort */+ while (n > 12) {+ stbtt__edge t;+ int c01,c12,c,m,i,j;++ /* compute median of three */+ m = n >> 1;+ c01 = STBTT__COMPARE(&p[0],&p[m]);+ c12 = STBTT__COMPARE(&p[m],&p[n-1]);+ /* if 0 >= mid >= end, or 0 < mid < end, then use mid */+ if (c01 != c12) {+ /* otherwise, we'll need to swap something else to middle */+ int z;+ c = STBTT__COMPARE(&p[0],&p[n-1]);+ /* 0>mid && mid<n: 0>n => n; 0<n => 0 */+ /* 0<mid && mid>n: 0>n => 0; 0<n => n */+ z = (c == c12) ? 0 : n-1;+ t = p[z];+ p[z] = p[m];+ p[m] = t;+ }+ /* now p[m] is the median-of-three */+ /* swap it to the beginning so it won't move around */+ t = p[0];+ p[0] = p[m];+ p[m] = t;++ /* partition loop */+ i=1;+ j=n-1;+ for(;;) {+ /* handling of equality is crucial here */+ /* for sentinels & efficiency with duplicates */+ for (;;++i) {+ if (!STBTT__COMPARE(&p[i], &p[0])) break;+ }+ for (;;--j) {+ if (!STBTT__COMPARE(&p[0], &p[j])) break;+ }+ /* make sure we haven't crossed */+ if (i >= j) break;+ t = p[i];+ p[i] = p[j];+ p[j] = t;++ ++i;+ --j;+ }+ /* recurse on smaller side, iterate on larger */+ if (j < (n-i)) {+ stbtt__sort_edges_quicksort(p,j);+ p = p+i;+ n = n-i;+ } else {+ stbtt__sort_edges_quicksort(p+i, n-i);+ n = j;+ }+ }+}++static void stbtt__sort_edges(stbtt__edge *p, int n)+{+ stbtt__sort_edges_quicksort(p, n);+ stbtt__sort_edges_ins_sort(p, n);+}++typedef struct+{+ float x,y;+} stbtt__point;++static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata)+{+ float y_scale_inv = invert ? -scale_y : scale_y;+ stbtt__edge *e;+ int n,i,j,k,m;+#if STBTT_RASTERIZER_VERSION == 1+ int vsubsample = result->h < 8 ? 15 : 5;+#elif STBTT_RASTERIZER_VERSION == 2+ int vsubsample = 1;+#else+ #error "Unrecognized value of STBTT_RASTERIZER_VERSION"+#endif+ // vsubsample should divide 255 evenly; otherwise we won't reach full opacity++ // now we have to blow out the windings into explicit edge lists+ n = 0;+ for (i=0; i < windings; ++i)+ n += wcount[i];++ e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel+ if (e == 0) return;+ n = 0;++ m=0;+ for (i=0; i < windings; ++i) {+ stbtt__point *p = pts + m;+ m += wcount[i];+ j = wcount[i]-1;+ for (k=0; k < wcount[i]; j=k++) {+ int a=k,b=j;+ // skip the edge if horizontal+ if (p[j].y == p[k].y)+ continue;+ // add edge from j to k to the list+ e[n].invert = 0;+ if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {+ e[n].invert = 1;+ a=j,b=k;+ }+ e[n].x0 = p[a].x * scale_x + shift_x;+ e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;+ e[n].x1 = p[b].x * scale_x + shift_x;+ e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;+ ++n;+ }+ }++ // now sort the edges by their highest point (should snap to integer, and then by x)+ //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);+ stbtt__sort_edges(e, n);++ // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule+ stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);++ STBTT_free(e, userdata);+}++static void stbtt__add_point(stbtt__point *points, int n, float x, float y)+{+ if (!points) return; // during first pass, it's unallocated+ points[n].x = x;+ points[n].y = y;+}++// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching+static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)+{+ // midpoint+ float mx = (x0 + 2*x1 + x2)/4;+ float my = (y0 + 2*y1 + y2)/4;+ // versus directly drawn line+ float dx = (x0+x2)/2 - mx;+ float dy = (y0+y2)/2 - my;+ if (n > 16) // 65536 segments on one curve better be enough!+ return 1;+ if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA+ stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);+ stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);+ } else {+ stbtt__add_point(points, *num_points,x2,y2);+ *num_points = *num_points+1;+ }+ return 1;+}++static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)+{+ // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough+ float dx0 = x1-x0;+ float dy0 = y1-y0;+ float dx1 = x2-x1;+ float dy1 = y2-y1;+ float dx2 = x3-x2;+ float dy2 = y3-y2;+ float dx = x3-x0;+ float dy = y3-y0;+ float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));+ float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);+ float flatness_squared = longlen*longlen-shortlen*shortlen;++ if (n > 16) // 65536 segments on one curve better be enough!+ return;++ if (flatness_squared > objspace_flatness_squared) {+ float x01 = (x0+x1)/2;+ float y01 = (y0+y1)/2;+ float x12 = (x1+x2)/2;+ float y12 = (y1+y2)/2;+ float x23 = (x2+x3)/2;+ float y23 = (y2+y3)/2;++ float xa = (x01+x12)/2;+ float ya = (y01+y12)/2;+ float xb = (x12+x23)/2;+ float yb = (y12+y23)/2;++ float mx = (xa+xb)/2;+ float my = (ya+yb)/2;++ stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);+ stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);+ } else {+ stbtt__add_point(points, *num_points,x3,y3);+ *num_points = *num_points+1;+ }+}++// returns number of contours+static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)+{+ stbtt__point *points=0;+ int num_points=0;++ float objspace_flatness_squared = objspace_flatness * objspace_flatness;+ int i,n=0,start=0, pass;++ // count how many "moves" there are to get the contour count+ for (i=0; i < num_verts; ++i)+ if (vertices[i].type == STBTT_vmove)+ ++n;++ *num_contours = n;+ if (n == 0) return 0;++ *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);++ if (*contour_lengths == 0) {+ *num_contours = 0;+ return 0;+ }++ // make two passes through the points so we don't need to realloc+ for (pass=0; pass < 2; ++pass) {+ float x=0,y=0;+ if (pass == 1) {+ points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);+ if (points == NULL) goto error;+ }+ num_points = 0;+ n= -1;+ for (i=0; i < num_verts; ++i) {+ switch (vertices[i].type) {+ case STBTT_vmove:+ // start the next contour+ if (n >= 0)+ (*contour_lengths)[n] = num_points - start;+ ++n;+ start = num_points;++ x = vertices[i].x, y = vertices[i].y;+ stbtt__add_point(points, num_points++, x,y);+ break;+ case STBTT_vline:+ x = vertices[i].x, y = vertices[i].y;+ stbtt__add_point(points, num_points++, x, y);+ break;+ case STBTT_vcurve:+ stbtt__tesselate_curve(points, &num_points, x,y,+ vertices[i].cx, vertices[i].cy,+ vertices[i].x, vertices[i].y,+ objspace_flatness_squared, 0);+ x = vertices[i].x, y = vertices[i].y;+ break;+ case STBTT_vcubic:+ stbtt__tesselate_cubic(points, &num_points, x,y,+ vertices[i].cx, vertices[i].cy,+ vertices[i].cx1, vertices[i].cy1,+ vertices[i].x, vertices[i].y,+ objspace_flatness_squared, 0);+ x = vertices[i].x, y = vertices[i].y;+ break;+ }+ }+ (*contour_lengths)[n] = num_points - start;+ }++ return points;+error:+ STBTT_free(points, userdata);+ STBTT_free(*contour_lengths, userdata);+ *contour_lengths = 0;+ *num_contours = 0;+ return NULL;+}++STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)+{+ float scale = scale_x > scale_y ? scale_y : scale_x;+ int winding_count = 0;+ int *winding_lengths = NULL;+ stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);+ if (windings) {+ stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);+ STBTT_free(winding_lengths, userdata);+ STBTT_free(windings, userdata);+ }+}++STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)+{+ STBTT_free(bitmap, userdata);+}++STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)+{+ int ix0,iy0,ix1,iy1;+ stbtt__bitmap gbm;+ stbtt_vertex *vertices;+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);++ if (scale_x == 0) scale_x = scale_y;+ if (scale_y == 0) {+ if (scale_x == 0) {+ STBTT_free(vertices, info->userdata);+ return NULL;+ }+ scale_y = scale_x;+ }++ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);++ // now we get the size+ gbm.w = (ix1 - ix0);+ gbm.h = (iy1 - iy0);+ gbm.pixels = NULL; // in case we error++ if (width ) *width = gbm.w;+ if (height) *height = gbm.h;+ if (xoff ) *xoff = ix0;+ if (yoff ) *yoff = iy0;++ if (gbm.w && gbm.h) {+ gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);+ if (gbm.pixels) {+ gbm.stride = gbm.w;++ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);+ }+ }+ STBTT_free(vertices, info->userdata);+ return gbm.pixels;+}++STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)+{+ return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);+}++STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)+{+ int ix0,iy0;+ stbtt_vertex *vertices;+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);+ stbtt__bitmap gbm;++ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);+ gbm.pixels = output;+ gbm.w = out_w;+ gbm.h = out_h;+ gbm.stride = out_stride;++ if (gbm.w && gbm.h)+ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);++ STBTT_free(vertices, info->userdata);+}++STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)+{+ stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);+}++STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)+{+ return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);+}++STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)+{+ stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));+}++STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)+{+ stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));+}++STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)+{+ return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);+}++STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)+{+ stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);+}++//////////////////////////////////////////////////////////////////////////////+//+// bitmap baking+//+// This is SUPER-CRAPPY packing to keep source code small++static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)+ float pixel_height, // height of font in pixels+ unsigned char *pixels, int pw, int ph, // bitmap to be filled in+ int first_char, int num_chars, // characters to bake+ stbtt_bakedchar *chardata)+{+ float scale;+ int x,y,bottom_y, i;+ stbtt_fontinfo f;+ f.userdata = NULL;+ if (!stbtt_InitFont(&f, data, offset))+ return -1;+ STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels+ x=y=1;+ bottom_y = 1;++ scale = stbtt_ScaleForPixelHeight(&f, pixel_height);++ for (i=0; i < num_chars; ++i) {+ int advance, lsb, x0,y0,x1,y1,gw,gh;+ int g = stbtt_FindGlyphIndex(&f, first_char + i);+ stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);+ stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);+ gw = x1-x0;+ gh = y1-y0;+ if (x + gw + 1 >= pw)+ y = bottom_y, x = 1; // advance to next row+ if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row+ return -i;+ STBTT_assert(x+gw < pw);+ STBTT_assert(y+gh < ph);+ stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);+ chardata[i].x0 = (stbtt_int16) x;+ chardata[i].y0 = (stbtt_int16) y;+ chardata[i].x1 = (stbtt_int16) (x + gw);+ chardata[i].y1 = (stbtt_int16) (y + gh);+ chardata[i].xadvance = scale * advance;+ chardata[i].xoff = (float) x0;+ chardata[i].yoff = (float) y0;+ x = x + gw + 1;+ if (y+gh+1 > bottom_y)+ bottom_y = y+gh+1;+ }+ return bottom_y;+}++STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)+{+ float d3d_bias = opengl_fillrule ? 0 : -0.5f;+ float ipw = 1.0f / pw, iph = 1.0f / ph;+ const stbtt_bakedchar *b = chardata + char_index;+ int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);+ int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);++ q->x0 = round_x + d3d_bias;+ q->y0 = round_y + d3d_bias;+ q->x1 = round_x + b->x1 - b->x0 + d3d_bias;+ q->y1 = round_y + b->y1 - b->y0 + d3d_bias;++ q->s0 = b->x0 * ipw;+ q->t0 = b->y0 * iph;+ q->s1 = b->x1 * ipw;+ q->t1 = b->y1 * iph;++ *xpos += b->xadvance;+}++//////////////////////////////////////////////////////////////////////////////+//+// rectangle packing replacement routines if you don't have stb_rect_pack.h+//++#ifndef STB_RECT_PACK_VERSION++typedef int stbrp_coord;++////////////////////////////////////////////////////////////////////////////////////+// //+// //+// COMPILER WARNING ?!?!? //+// //+// //+// if you get a compile warning due to these symbols being defined more than //+// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //+// //+////////////////////////////////////////////////////////////////////////////////////++typedef struct+{+ int width,height;+ int x,y,bottom_y;+} stbrp_context;++typedef struct+{+ unsigned char x;+} stbrp_node;++struct stbrp_rect+{+ stbrp_coord x,y;+ int id,w,h,was_packed;+};++static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)+{+ con->width = pw;+ con->height = ph;+ con->x = 0;+ con->y = 0;+ con->bottom_y = 0;+ STBTT__NOTUSED(nodes);+ STBTT__NOTUSED(num_nodes);+}++static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)+{+ int i;+ for (i=0; i < num_rects; ++i) {+ if (con->x + rects[i].w > con->width) {+ con->x = 0;+ con->y = con->bottom_y;+ }+ if (con->y + rects[i].h > con->height)+ break;+ rects[i].x = con->x;+ rects[i].y = con->y;+ rects[i].was_packed = 1;+ con->x += rects[i].w;+ if (con->y + rects[i].h > con->bottom_y)+ con->bottom_y = con->y + rects[i].h;+ }+ for ( ; i < num_rects; ++i)+ rects[i].was_packed = 0;+}+#endif++//////////////////////////////////////////////////////////////////////////////+//+// bitmap baking+//+// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If+// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.++STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)+{+ stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context);+ int num_nodes = pw - padding;+ stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context);++ if (context == NULL || nodes == NULL) {+ if (context != NULL) STBTT_free(context, alloc_context);+ if (nodes != NULL) STBTT_free(nodes , alloc_context);+ return 0;+ }++ spc->user_allocator_context = alloc_context;+ spc->width = pw;+ spc->height = ph;+ spc->pixels = pixels;+ spc->pack_info = context;+ spc->nodes = nodes;+ spc->padding = padding;+ spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;+ spc->h_oversample = 1;+ spc->v_oversample = 1;+ spc->skip_missing = 0;++ stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);++ if (pixels)+ STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels++ return 1;+}++STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc)+{+ STBTT_free(spc->nodes , spc->user_allocator_context);+ STBTT_free(spc->pack_info, spc->user_allocator_context);+}++STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)+{+ STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);+ STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);+ if (h_oversample <= STBTT_MAX_OVERSAMPLE)+ spc->h_oversample = h_oversample;+ if (v_oversample <= STBTT_MAX_OVERSAMPLE)+ spc->v_oversample = v_oversample;+}++STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip)+{+ spc->skip_missing = skip;+}++#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)++static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)+{+ unsigned char buffer[STBTT_MAX_OVERSAMPLE];+ int safe_w = w - kernel_width;+ int j;+ STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze+ for (j=0; j < h; ++j) {+ int i;+ unsigned int total;+ STBTT_memset(buffer, 0, kernel_width);++ total = 0;++ // make kernel_width a constant in common cases so compiler can optimize out the divide+ switch (kernel_width) {+ case 2:+ for (i=0; i <= safe_w; ++i) {+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];+ pixels[i] = (unsigned char) (total / 2);+ }+ break;+ case 3:+ for (i=0; i <= safe_w; ++i) {+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];+ pixels[i] = (unsigned char) (total / 3);+ }+ break;+ case 4:+ for (i=0; i <= safe_w; ++i) {+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];+ pixels[i] = (unsigned char) (total / 4);+ }+ break;+ case 5:+ for (i=0; i <= safe_w; ++i) {+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];+ pixels[i] = (unsigned char) (total / 5);+ }+ break;+ default:+ for (i=0; i <= safe_w; ++i) {+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];+ pixels[i] = (unsigned char) (total / kernel_width);+ }+ break;+ }++ for (; i < w; ++i) {+ STBTT_assert(pixels[i] == 0);+ total -= buffer[i & STBTT__OVER_MASK];+ pixels[i] = (unsigned char) (total / kernel_width);+ }++ pixels += stride_in_bytes;+ }+}++static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)+{+ unsigned char buffer[STBTT_MAX_OVERSAMPLE];+ int safe_h = h - kernel_width;+ int j;+ STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze+ for (j=0; j < w; ++j) {+ int i;+ unsigned int total;+ STBTT_memset(buffer, 0, kernel_width);++ total = 0;++ // make kernel_width a constant in common cases so compiler can optimize out the divide+ switch (kernel_width) {+ case 2:+ for (i=0; i <= safe_h; ++i) {+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];+ pixels[i*stride_in_bytes] = (unsigned char) (total / 2);+ }+ break;+ case 3:+ for (i=0; i <= safe_h; ++i) {+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];+ pixels[i*stride_in_bytes] = (unsigned char) (total / 3);+ }+ break;+ case 4:+ for (i=0; i <= safe_h; ++i) {+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];+ pixels[i*stride_in_bytes] = (unsigned char) (total / 4);+ }+ break;+ case 5:+ for (i=0; i <= safe_h; ++i) {+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];+ pixels[i*stride_in_bytes] = (unsigned char) (total / 5);+ }+ break;+ default:+ for (i=0; i <= safe_h; ++i) {+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];+ pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);+ }+ break;+ }++ for (; i < h; ++i) {+ STBTT_assert(pixels[i*stride_in_bytes] == 0);+ total -= buffer[i & STBTT__OVER_MASK];+ pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);+ }++ pixels += 1;+ }+}++static float stbtt__oversample_shift(int oversample)+{+ if (!oversample)+ return 0.0f;++ // The prefilter is a box filter of width "oversample",+ // which shifts phase by (oversample - 1)/2 pixels in+ // oversampled space. We want to shift in the opposite+ // direction to counter this.+ return (float)-(oversample - 1) / (2.0f * (float)oversample);+}++// rects array must be big enough to accommodate all characters in the given ranges+STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)+{+ int i,j,k;+ int missing_glyph_added = 0;++ k=0;+ for (i=0; i < num_ranges; ++i) {+ float fh = ranges[i].font_size;+ float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);+ ranges[i].h_oversample = (unsigned char) spc->h_oversample;+ ranges[i].v_oversample = (unsigned char) spc->v_oversample;+ for (j=0; j < ranges[i].num_chars; ++j) {+ int x0,y0,x1,y1;+ int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];+ int glyph = stbtt_FindGlyphIndex(info, codepoint);+ if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) {+ rects[k].w = rects[k].h = 0;+ } else {+ stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,+ scale * spc->h_oversample,+ scale * spc->v_oversample,+ 0,0,+ &x0,&y0,&x1,&y1);+ rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);+ rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);+ if (glyph == 0)+ missing_glyph_added = 1;+ }+ ++k;+ }+ }++ return k;+}++STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)+{+ stbtt_MakeGlyphBitmapSubpixel(info,+ output,+ out_w - (prefilter_x - 1),+ out_h - (prefilter_y - 1),+ out_stride,+ scale_x,+ scale_y,+ shift_x,+ shift_y,+ glyph);++ if (prefilter_x > 1)+ stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);++ if (prefilter_y > 1)+ stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);++ *sub_x = stbtt__oversample_shift(prefilter_x);+ *sub_y = stbtt__oversample_shift(prefilter_y);+}++// rects array must be big enough to accommodate all characters in the given ranges+STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)+{+ int i,j,k, missing_glyph = -1, return_value = 1;++ // save current values+ int old_h_over = spc->h_oversample;+ int old_v_over = spc->v_oversample;++ k = 0;+ for (i=0; i < num_ranges; ++i) {+ float fh = ranges[i].font_size;+ float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);+ float recip_h,recip_v,sub_x,sub_y;+ spc->h_oversample = ranges[i].h_oversample;+ spc->v_oversample = ranges[i].v_oversample;+ recip_h = 1.0f / spc->h_oversample;+ recip_v = 1.0f / spc->v_oversample;+ sub_x = stbtt__oversample_shift(spc->h_oversample);+ sub_y = stbtt__oversample_shift(spc->v_oversample);+ for (j=0; j < ranges[i].num_chars; ++j) {+ stbrp_rect *r = &rects[k];+ if (r->was_packed && r->w != 0 && r->h != 0) {+ stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];+ int advance, lsb, x0,y0,x1,y1;+ int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];+ int glyph = stbtt_FindGlyphIndex(info, codepoint);+ stbrp_coord pad = (stbrp_coord) spc->padding;++ // pad on left and top+ r->x += pad;+ r->y += pad;+ r->w -= pad;+ r->h -= pad;+ stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);+ stbtt_GetGlyphBitmapBox(info, glyph,+ scale * spc->h_oversample,+ scale * spc->v_oversample,+ &x0,&y0,&x1,&y1);+ stbtt_MakeGlyphBitmapSubpixel(info,+ spc->pixels + r->x + r->y*spc->stride_in_bytes,+ r->w - spc->h_oversample+1,+ r->h - spc->v_oversample+1,+ spc->stride_in_bytes,+ scale * spc->h_oversample,+ scale * spc->v_oversample,+ 0,0,+ glyph);++ if (spc->h_oversample > 1)+ stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,+ r->w, r->h, spc->stride_in_bytes,+ spc->h_oversample);++ if (spc->v_oversample > 1)+ stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,+ r->w, r->h, spc->stride_in_bytes,+ spc->v_oversample);++ bc->x0 = (stbtt_int16) r->x;+ bc->y0 = (stbtt_int16) r->y;+ bc->x1 = (stbtt_int16) (r->x + r->w);+ bc->y1 = (stbtt_int16) (r->y + r->h);+ bc->xadvance = scale * advance;+ bc->xoff = (float) x0 * recip_h + sub_x;+ bc->yoff = (float) y0 * recip_v + sub_y;+ bc->xoff2 = (x0 + r->w) * recip_h + sub_x;+ bc->yoff2 = (y0 + r->h) * recip_v + sub_y;++ if (glyph == 0)+ missing_glyph = j;+ } else if (spc->skip_missing) {+ return_value = 0;+ } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) {+ ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph];+ } else {+ return_value = 0; // if any fail, report failure+ }++ ++k;+ }+ }++ // restore original values+ spc->h_oversample = old_h_over;+ spc->v_oversample = old_v_over;++ return return_value;+}++STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)+{+ stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);+}++STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)+{+ stbtt_fontinfo info;+ int i,j,n, return_value = 1;+ //stbrp_context *context = (stbrp_context *) spc->pack_info;+ stbrp_rect *rects;++ // flag all characters as NOT packed+ for (i=0; i < num_ranges; ++i)+ for (j=0; j < ranges[i].num_chars; ++j)+ ranges[i].chardata_for_range[j].x0 =+ ranges[i].chardata_for_range[j].y0 =+ ranges[i].chardata_for_range[j].x1 =+ ranges[i].chardata_for_range[j].y1 = 0;++ n = 0;+ for (i=0; i < num_ranges; ++i)+ n += ranges[i].num_chars;++ rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);+ if (rects == NULL)+ return 0;++ info.userdata = spc->user_allocator_context;+ stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));++ n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);++ stbtt_PackFontRangesPackRects(spc, rects, n);++ return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);++ STBTT_free(rects, spc->user_allocator_context);+ return return_value;+}++STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,+ int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)+{+ stbtt_pack_range range;+ range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;+ range.array_of_unicode_codepoints = NULL;+ range.num_chars = num_chars_in_range;+ range.chardata_for_range = chardata_for_range;+ range.font_size = font_size;+ return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);+}++STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap)+{+ int i_ascent, i_descent, i_lineGap;+ float scale;+ stbtt_fontinfo info;+ stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));+ scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);+ stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);+ *ascent = (float) i_ascent * scale;+ *descent = (float) i_descent * scale;+ *lineGap = (float) i_lineGap * scale;+}++STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)+{+ float ipw = 1.0f / pw, iph = 1.0f / ph;+ const stbtt_packedchar *b = chardata + char_index;++ if (align_to_integer) {+ float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);+ float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);+ q->x0 = x;+ q->y0 = y;+ q->x1 = x + b->xoff2 - b->xoff;+ q->y1 = y + b->yoff2 - b->yoff;+ } else {+ q->x0 = *xpos + b->xoff;+ q->y0 = *ypos + b->yoff;+ q->x1 = *xpos + b->xoff2;+ q->y1 = *ypos + b->yoff2;+ }++ q->s0 = b->x0 * ipw;+ q->t0 = b->y0 * iph;+ q->s1 = b->x1 * ipw;+ q->t1 = b->y1 * iph;++ *xpos += b->xadvance;+}++//////////////////////////////////////////////////////////////////////////////+//+// sdf computation+//++#define STBTT_min(a,b) ((a) < (b) ? (a) : (b))+#define STBTT_max(a,b) ((a) < (b) ? (b) : (a))++static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])+{+ float q0perp = q0[1]*ray[0] - q0[0]*ray[1];+ float q1perp = q1[1]*ray[0] - q1[0]*ray[1];+ float q2perp = q2[1]*ray[0] - q2[0]*ray[1];+ float roperp = orig[1]*ray[0] - orig[0]*ray[1];++ float a = q0perp - 2*q1perp + q2perp;+ float b = q1perp - q0perp;+ float c = q0perp - roperp;++ float s0 = 0., s1 = 0.;+ int num_s = 0;++ if (a != 0.0) {+ float discr = b*b - a*c;+ if (discr > 0.0) {+ float rcpna = -1 / a;+ float d = (float) STBTT_sqrt(discr);+ s0 = (b+d) * rcpna;+ s1 = (b-d) * rcpna;+ if (s0 >= 0.0 && s0 <= 1.0)+ num_s = 1;+ if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {+ if (num_s == 0) s0 = s1;+ ++num_s;+ }+ }+ } else {+ // 2*b*s + c = 0+ // s = -c / (2*b)+ s0 = c / (-2 * b);+ if (s0 >= 0.0 && s0 <= 1.0)+ num_s = 1;+ }++ if (num_s == 0)+ return 0;+ else {+ float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);+ float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;++ float q0d = q0[0]*rayn_x + q0[1]*rayn_y;+ float q1d = q1[0]*rayn_x + q1[1]*rayn_y;+ float q2d = q2[0]*rayn_x + q2[1]*rayn_y;+ float rod = orig[0]*rayn_x + orig[1]*rayn_y;++ float q10d = q1d - q0d;+ float q20d = q2d - q0d;+ float q0rd = q0d - rod;++ hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;+ hits[0][1] = a*s0+b;++ if (num_s > 1) {+ hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;+ hits[1][1] = a*s1+b;+ return 2;+ } else {+ return 1;+ }+ }+}++static int equal(float *a, float *b)+{+ return (a[0] == b[0] && a[1] == b[1]);+}++static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)+{+ int i;+ float orig[2], ray[2] = { 1, 0 };+ float y_frac;+ int winding = 0;++ // make sure y never passes through a vertex of the shape+ y_frac = (float) STBTT_fmod(y, 1.0f);+ if (y_frac < 0.01f)+ y += 0.01f;+ else if (y_frac > 0.99f)+ y -= 0.01f;++ orig[0] = x;+ orig[1] = y;++ // test a ray from (-infinity,y) to (x,y)+ for (i=0; i < nverts; ++i) {+ if (verts[i].type == STBTT_vline) {+ int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;+ int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y;+ if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {+ float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;+ if (x_inter < x)+ winding += (y0 < y1) ? 1 : -1;+ }+ }+ if (verts[i].type == STBTT_vcurve) {+ int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;+ int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy;+ int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ;+ int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));+ int by = STBTT_max(y0,STBTT_max(y1,y2));+ if (y > ay && y < by && x > ax) {+ float q0[2],q1[2],q2[2];+ float hits[2][2];+ q0[0] = (float)x0;+ q0[1] = (float)y0;+ q1[0] = (float)x1;+ q1[1] = (float)y1;+ q2[0] = (float)x2;+ q2[1] = (float)y2;+ if (equal(q0,q1) || equal(q1,q2)) {+ x0 = (int)verts[i-1].x;+ y0 = (int)verts[i-1].y;+ x1 = (int)verts[i ].x;+ y1 = (int)verts[i ].y;+ if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {+ float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;+ if (x_inter < x)+ winding += (y0 < y1) ? 1 : -1;+ }+ } else {+ int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);+ if (num_hits >= 1)+ if (hits[0][0] < 0)+ winding += (hits[0][1] < 0 ? -1 : 1);+ if (num_hits >= 2)+ if (hits[1][0] < 0)+ winding += (hits[1][1] < 0 ? -1 : 1);+ }+ }+ }+ }+ return winding;+}++static float stbtt__cuberoot( float x )+{+ if (x<0)+ return -(float) STBTT_pow(-x,1.0f/3.0f);+ else+ return (float) STBTT_pow( x,1.0f/3.0f);+}++// x^3 + a*x^2 + b*x + c = 0+static int stbtt__solve_cubic(float a, float b, float c, float* r)+{+ float s = -a / 3;+ float p = b - a*a / 3;+ float q = a * (2*a*a - 9*b) / 27 + c;+ float p3 = p*p*p;+ float d = q*q + 4*p3 / 27;+ if (d >= 0) {+ float z = (float) STBTT_sqrt(d);+ float u = (-q + z) / 2;+ float v = (-q - z) / 2;+ u = stbtt__cuberoot(u);+ v = stbtt__cuberoot(v);+ r[0] = s + u + v;+ return 1;+ } else {+ float u = (float) STBTT_sqrt(-p/3);+ float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative+ float m = (float) STBTT_cos(v);+ float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;+ r[0] = s + u * 2 * m;+ r[1] = s - u * (m + n);+ r[2] = s - u * (m - n);++ //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?+ //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);+ //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);+ return 3;+ }+}++STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)+{+ float scale_x = scale, scale_y = scale;+ int ix0,iy0,ix1,iy1;+ int w,h;+ unsigned char *data;++ if (scale == 0) return NULL;++ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);++ // if empty, return NULL+ if (ix0 == ix1 || iy0 == iy1)+ return NULL;++ ix0 -= padding;+ iy0 -= padding;+ ix1 += padding;+ iy1 += padding;++ w = (ix1 - ix0);+ h = (iy1 - iy0);++ if (width ) *width = w;+ if (height) *height = h;+ if (xoff ) *xoff = ix0;+ if (yoff ) *yoff = iy0;++ // invert for y-downwards bitmaps+ scale_y = -scale_y;++ {+ // distance from singular values (in the same units as the pixel grid)+ const float eps = 1./1024, eps2 = eps*eps;+ int x,y,i,j;+ float *precompute;+ stbtt_vertex *verts;+ int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);+ data = (unsigned char *) STBTT_malloc(w * h, info->userdata);+ precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);++ for (i=0,j=num_verts-1; i < num_verts; j=i++) {+ if (verts[i].type == STBTT_vline) {+ float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;+ float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;+ float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));+ precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist;+ } else if (verts[i].type == STBTT_vcurve) {+ float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;+ float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;+ float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;+ float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;+ float len2 = bx*bx + by*by;+ if (len2 >= eps2)+ precompute[i] = 1.0f / len2;+ else+ precompute[i] = 0.0f;+ } else+ precompute[i] = 0.0f;+ }++ for (y=iy0; y < iy1; ++y) {+ for (x=ix0; x < ix1; ++x) {+ float val;+ float min_dist = 999999.0f;+ float sx = (float) x + 0.5f;+ float sy = (float) y + 0.5f;+ float x_gspace = (sx / scale_x);+ float y_gspace = (sy / scale_y);++ int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path++ for (i=0; i < num_verts; ++i) {+ float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;++ if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) {+ float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;++ float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);+ if (dist2 < min_dist*min_dist)+ min_dist = (float) STBTT_sqrt(dist2);++ // coarse culling against bbox+ //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&+ // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)+ dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];+ STBTT_assert(i != 0);+ if (dist < min_dist) {+ // check position along line+ // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)+ // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)+ float dx = x1-x0, dy = y1-y0;+ float px = x0-sx, py = y0-sy;+ // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy+ // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve+ float t = -(px*dx + py*dy) / (dx*dx + dy*dy);+ if (t >= 0.0f && t <= 1.0f)+ min_dist = dist;+ }+ } else if (verts[i].type == STBTT_vcurve) {+ float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;+ float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y;+ float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);+ float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);+ float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);+ float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);+ // coarse culling against bbox to avoid computing cubic unnecessarily+ if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {+ int num=0;+ float ax = x1-x0, ay = y1-y0;+ float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;+ float mx = x0 - sx, my = y0 - sy;+ float res[3] = {0.f,0.f,0.f};+ float px,py,t,it,dist2;+ float a_inv = precompute[i];+ if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula+ float a = 3*(ax*bx + ay*by);+ float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);+ float c = mx*ax+my*ay;+ if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear+ if (STBTT_fabs(b) >= eps2) {+ res[num++] = -c/b;+ }+ } else {+ float discriminant = b*b - 4*a*c;+ if (discriminant < 0)+ num = 0;+ else {+ float root = (float) STBTT_sqrt(discriminant);+ res[0] = (-b - root)/(2*a);+ res[1] = (-b + root)/(2*a);+ num = 2; // don't bother distinguishing 1-solution case, as code below will still work+ }+ }+ } else {+ float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point+ float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;+ float d = (mx*ax+my*ay) * a_inv;+ num = stbtt__solve_cubic(b, c, d, res);+ }+ dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);+ if (dist2 < min_dist*min_dist)+ min_dist = (float) STBTT_sqrt(dist2);++ if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {+ t = res[0], it = 1.0f - t;+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);+ if (dist2 < min_dist * min_dist)+ min_dist = (float) STBTT_sqrt(dist2);+ }+ if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {+ t = res[1], it = 1.0f - t;+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);+ if (dist2 < min_dist * min_dist)+ min_dist = (float) STBTT_sqrt(dist2);+ }+ if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {+ t = res[2], it = 1.0f - t;+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);+ if (dist2 < min_dist * min_dist)+ min_dist = (float) STBTT_sqrt(dist2);+ }+ }+ }+ }+ if (winding == 0)+ min_dist = -min_dist; // if outside the shape, value is negative+ val = onedge_value + pixel_dist_scale * min_dist;+ if (val < 0)+ val = 0;+ else if (val > 255)+ val = 255;+ data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;+ }+ }+ STBTT_free(precompute, info->userdata);+ STBTT_free(verts, info->userdata);+ }+ return data;+}++STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)+{+ return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);+}++STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)+{+ STBTT_free(bitmap, userdata);+}++//////////////////////////////////////////////////////////////////////////////+//+// font name matching -- recommended not to use this+//++// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string+static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)+{+ stbtt_int32 i=0;++ // convert utf16 to utf8 and compare the results while converting+ while (len2) {+ stbtt_uint16 ch = s2[0]*256 + s2[1];+ if (ch < 0x80) {+ if (i >= len1) return -1;+ if (s1[i++] != ch) return -1;+ } else if (ch < 0x800) {+ if (i+1 >= len1) return -1;+ if (s1[i++] != 0xc0 + (ch >> 6)) return -1;+ if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;+ } else if (ch >= 0xd800 && ch < 0xdc00) {+ stbtt_uint32 c;+ stbtt_uint16 ch2 = s2[2]*256 + s2[3];+ if (i+3 >= len1) return -1;+ c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;+ if (s1[i++] != 0xf0 + (c >> 18)) return -1;+ if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;+ if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;+ if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;+ s2 += 2; // plus another 2 below+ len2 -= 2;+ } else if (ch >= 0xdc00 && ch < 0xe000) {+ return -1;+ } else {+ if (i+2 >= len1) return -1;+ if (s1[i++] != 0xe0 + (ch >> 12)) return -1;+ if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;+ if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;+ }+ s2 += 2;+ len2 -= 2;+ }+ return i;+}++static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)+{+ return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);+}++// returns results in whatever encoding you request... but note that 2-byte encodings+// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare+STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)+{+ stbtt_int32 i,count,stringOffset;+ stbtt_uint8 *fc = font->data;+ stbtt_uint32 offset = font->fontstart;+ stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");+ if (!nm) return NULL;++ count = ttUSHORT(fc+nm+2);+ stringOffset = nm + ttUSHORT(fc+nm+4);+ for (i=0; i < count; ++i) {+ stbtt_uint32 loc = nm + 6 + 12 * i;+ if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)+ && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {+ *length = ttUSHORT(fc+loc+8);+ return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));+ }+ }+ return NULL;+}++static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)+{+ stbtt_int32 i;+ stbtt_int32 count = ttUSHORT(fc+nm+2);+ stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);++ for (i=0; i < count; ++i) {+ stbtt_uint32 loc = nm + 6 + 12 * i;+ stbtt_int32 id = ttUSHORT(fc+loc+6);+ if (id == target_id) {+ // find the encoding+ stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);++ // is this a Unicode encoding?+ if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {+ stbtt_int32 slen = ttUSHORT(fc+loc+8);+ stbtt_int32 off = ttUSHORT(fc+loc+10);++ // check if there's a prefix match+ stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);+ if (matchlen >= 0) {+ // check for target_id+1 immediately following, with same encoding & language+ if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {+ slen = ttUSHORT(fc+loc+12+8);+ off = ttUSHORT(fc+loc+12+10);+ if (slen == 0) {+ if (matchlen == nlen)+ return 1;+ } else if (matchlen < nlen && name[matchlen] == ' ') {+ ++matchlen;+ if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))+ return 1;+ }+ } else {+ // if nothing immediately following+ if (matchlen == nlen)+ return 1;+ }+ }+ }++ // @TODO handle other encodings+ }+ }+ return 0;+}++static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)+{+ stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);+ stbtt_uint32 nm,hd;+ if (!stbtt__isfont(fc+offset)) return 0;++ // check italics/bold/underline flags in macStyle...+ if (flags) {+ hd = stbtt__find_table(fc, offset, "head");+ if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;+ }++ nm = stbtt__find_table(fc, offset, "name");+ if (!nm) return 0;++ if (flags) {+ // if we checked the macStyle flags, then just check the family and ignore the subfamily+ if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;+ if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;+ } else {+ if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;+ if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;+ }++ return 0;+}++static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)+{+ stbtt_int32 i;+ for (i=0;;++i) {+ stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);+ if (off < 0) return off;+ if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))+ return off;+ }+}++#if defined(__GNUC__) || defined(__clang__)+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wcast-qual"+#endif++STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,+ float pixel_height, unsigned char *pixels, int pw, int ph,+ int first_char, int num_chars, stbtt_bakedchar *chardata)+{+ return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);+}++STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)+{+ return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);+}++STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)+{+ return stbtt_GetNumberOfFonts_internal((unsigned char *) data);+}++STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)+{+ return stbtt_InitFont_internal(info, (unsigned char *) data, offset);+}++STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)+{+ return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);+}++STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)+{+ return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);+}++#if defined(__GNUC__) || defined(__clang__)+#pragma GCC diagnostic pop+#endif++#endif // STB_TRUETYPE_IMPLEMENTATION+++// FULL VERSION HISTORY+//+// 1.25 (2021-07-11) many fixes+// 1.24 (2020-02-05) fix warning+// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)+// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined+// 1.21 (2019-02-25) fix warning+// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()+// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod+// 1.18 (2018-01-29) add missing function+// 1.17 (2017-07-23) make more arguments const; doc fix+// 1.16 (2017-07-12) SDF support+// 1.15 (2017-03-03) make more arguments const+// 1.14 (2017-01-16) num-fonts-in-TTC function+// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts+// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual+// 1.11 (2016-04-02) fix unused-variable warning+// 1.10 (2016-04-02) allow user-defined fabs() replacement+// fix memory leak if fontsize=0.0+// fix warning from duplicate typedef+// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges+// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges+// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;+// allow PackFontRanges to pack and render in separate phases;+// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);+// fixed an assert() bug in the new rasterizer+// replace assert() with STBTT_assert() in new rasterizer+// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)+// also more precise AA rasterizer, except if shapes overlap+// remove need for STBTT_sort+// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC+// 1.04 (2015-04-15) typo in example+// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes+// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C+++// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match+// non-oversampled; STBTT_POINT_SIZE for packed case only+// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling+// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)+// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID+// 0.8b (2014-07-07) fix a warning+// 0.8 (2014-05-25) fix a few more warnings+// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back+// 0.6c (2012-07-24) improve documentation+// 0.6b (2012-07-20) fix a few more warnings+// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,+// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty+// 0.5 (2011-12-09) bugfixes:+// subpixel glyph renderer computed wrong bounding box+// first vertex of shape can be off-curve (FreeSans)+// 0.4b (2011-12-03) fixed an error in the font baking example+// 0.4 (2011-12-01) kerning, subpixel rendering (tor)+// bugfixes for:+// codepoint-to-glyph conversion using table fmt=12+// codepoint-to-glyph conversion using table fmt=4+// stbtt_GetBakedQuad with non-square texture (Zer)+// updated Hello World! sample to use kerning and subpixel+// fixed some warnings+// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)+// userdata, malloc-from-userdata, non-zero fill (stb)+// 0.2 (2009-03-11) Fix unsigned/signed char warnings+// 0.1 (2009-03-09) First public release+//++/*+------------------------------------------------------------------------------+This software is available under 2 licenses -- choose whichever you prefer.+------------------------------------------------------------------------------+ALTERNATIVE A - MIT License+Copyright (c) 2017 Sean Barrett+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.+------------------------------------------------------------------------------+ALTERNATIVE B - Public Domain (www.unlicense.org)+This is free and unencumbered software released into the public domain.+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this+software, either in source code form or as a compiled binary, for any purpose,+commercial or non-commercial, and by any means.+In jurisdictions that recognize copyright laws, the author or authors of this+software dedicate any and all copyright interest in the software to the public+domain. We make this dedication for the benefit of the public at large and to+the detriment of our heirs and successors. We intend this dedication to be an+overt act of relinquishment in perpetuity of all present and future rights to+this software under copyright law.+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 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.+------------------------------------------------------------------------------+*/diff --git a/gpu/include/GPU_raster.h b/gpu/include/GPU_raster.hindex fbbb0e4..38799c5 100644--- a/gpu/include/GPU_raster.h+++ b/gpu/include/GPU_raster.h@@ -190,6 +190,28 @@ const BuiTextRun *BUI_text_prepare(const char *family, int flags, float size, const char *utf8, int len, float *r_width);unsigned BUI_text_generation(void);void BUI_raster_text_run(BuiRaster *r, float x, float y, const BuiTextRun *run, const float rgba[4]);+/* A prepared run's 8-bit coverage mask (row-major, `*r_w` x `*r_h`): the+ * pen origin is at (`*r_ox`, `*r_ascent`) inside it. For GPU renderers. */+const uint8_t *BUI_text_run_mask(const BuiTextRun *run, int *r_w, int *r_h, int *r_ox, int *r_ascent);+/* Registers a TrueType/OpenType font (copied) under `family` with style+ * `flags` (BUI_FONT_BOLD | BUI_FONT_ITALIC). Needed where the platform has no+ * font folders (wasm); elsewhere it adds to them. Returns 0 on bad data. */+int BUI_text_add_font(const char *family, int flags, const void *data, int len);++/* GPU rendering (Direct3D 11 on Windows). A raster in GPU mode records its+ * primitives as instances and draws them on the GPU at present; it keeps the+ * same API, clip and damage semantics. attach() creates the device on a+ * worker thread (frames keep using the software raster meanwhile) unless+ * `wait`; poll() switches over once it is ready and returns 1 when the+ * renderer changed, so the caller must redraw the whole frame. A NULL window+ * renders offscreen (BUI_raster_pixels reads the frame back). */+int BUI_raster_gpu_attach(BuiRaster *r, void *window_handle, int wait);+int BUI_raster_gpu_poll(BuiRaster *r);+int BUI_raster_is_gpu(const BuiRaster *r);+/* Whether new windows use the GPU: BUI_gpu_set_default(), overridden by the+ * BUI_GPU environment variable (1/0). Off by default. */+void BUI_gpu_set_default(int on);+int BUI_gpu_default(void);/* A BuiGpuSink that renders into `r` (user pointer is the raster). */const BuiGpuSink *BUI_raster_sink(BuiRaster *r);diff --git a/gpu/intern/gpu_d3d11.c b/gpu/intern/gpu_d3d11.cnew file mode 100644index 0000000..ce83de0--- /dev/null+++ b/gpu/intern/gpu_d3d11.c@@ -0,0 +1,968 @@+/* BUI GPU renderer: Direct3D 11 backend — see gpu_d3d11.h.+ *+ * Like Blender's widget drawing (interface_widgets.cc batches widget bases+ * into GPU_SHADER_2D_WIDGET_BASE_INST draws), every primitive becomes one+ * instance of a single uber-shader, so a frame of thousands of widgets and+ * text runs is a handful of DrawInstanced calls. Differences from Blender,+ * for a retained UI:+ * - frames render into a persistent target: only damaged regions are+ * redrawn (the kit's damage tracking) and the swap chain gets dirty rects,+ * so the compositor only recomposes what changed;+ * - text is pre-shaped glyph runs (the same masks the software raster draws)+ * packed into one R8 atlas, images into one BGRA atlas;+ * - the device is created on a worker thread so the first frame never waits+ * for the driver (the software raster draws until it is ready).+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#ifdef _WIN32++# ifndef WIN32_LEAN_AND_MEAN+# define WIN32_LEAN_AND_MEAN+# endif+# define COBJMACROS+# include <windows.h>+# include <d3d11.h>+# include <dxgi1_2.h>++# include <stdio.h>+# include <stdlib.h>+# include <string.h>++# include "gpu_d3d11.h"+# include "gpu_d3d11_shaders.h"++static const GUID k_IID_IDXGIDevice = {+ 0x54ec77fa, 0x1377, 0x44e6, {0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}};+static const GUID k_IID_IDXGIFactory2 = {+ 0x50c83a1c, 0xe072, 0x4c48, {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0}};+static const GUID k_IID_ID3D11Texture2D = {+ 0x6f15aaf2, 0xd208, 0x4e89, {0x9a, 0xb4, 0x48, 0x95, 0x35, 0xd3, 0x4f, 0x9c}};++# define REL(p) \+ do { \+ if (p) { \+ IUnknown_Release((IUnknown *)(p)); \+ (p) = NULL; \+ } \+ } while (0)++/* -------------------------------------------------------------------- */+/** \name Atlases (shelf packing)+ * \{ */++# define SHELVES 128++typedef struct Atlas {+ int size;+ int bpp; /* 1 (R8) or 4 (BGRA8) */+ ID3D11Texture2D *tex;+ ID3D11ShaderResourceView *srv;+ int shelf_y[SHELVES], shelf_h[SHELVES], shelf_x[SHELVES];+ int nshelves, next_y;+} Atlas;++/* cache entry: key -> placement */+typedef struct Slot {+ uint64_t k1, k2; /* 0 = empty */+ int x, y;+} Slot;++# define MASK_MAP 16384 /* power of two */+# define MASK_MAP_FILL 12000+# define IMG_MAP 1024+# define IMG_MAP_FILL 700++typedef struct Batch {+ int tri; /* 0: quad instances, 1: triangles */+ int first, count;+} Batch;++typedef struct TriV {+ float x, y;+ float c[4];+ float clip[4];+} TriV;++struct BuiGpu {+ HWND hwnd;+ volatile LONG state; /* 0 pending, 1 ready, -1 failed */+ HANDLE thread;++ ID3D11Device *dev;+ ID3D11DeviceContext *ctx;+ IDXGIFactory2 *factory;+ IDXGISwapChain1 *swap;+ int sw, sh; /* swap chain size */+ int swap_fresh;++ ID3D11VertexShader *vs_quad, *vs_tri;+ ID3D11PixelShader *ps_quad, *ps_tri;+ ID3D11InputLayout *il_quad, *il_tri;+ ID3D11Buffer *cb, *ib, *tb;+ UINT ib_cap, tb_cap; /* in elements */+ ID3D11BlendState *blend;+ ID3D11RasterizerState *rs;++ ID3D11Texture2D *target;+ ID3D11RenderTargetView *rtv;+ int tw, th;+ int w, h; /* frame size */++ Atlas mask, rgba;+ Slot *mask_map, *img_map;+ int mask_n, img_n;+ unsigned mask_gen;++ BuiGpuInst *inst;+ int n_inst, cap_inst;+ TriV *tv;+ int n_tv, cap_tv;+ Batch *b;+ int n_b, cap_b;++ RECT dmg[16];+ int n_dmg, dmg_full;+};++static int atlas_create(BuiGpu *g, Atlas *a, int size, int bpp)+{+ memset(a, 0, sizeof(*a));+ a->size = size;+ a->bpp = bpp;+ D3D11_TEXTURE2D_DESC td = {0};+ td.Width = td.Height = (UINT)size;+ td.MipLevels = td.ArraySize = 1;+ td.Format = bpp == 1 ? DXGI_FORMAT_R8_UNORM : DXGI_FORMAT_B8G8R8A8_UNORM;+ td.SampleDesc.Count = 1;+ td.Usage = D3D11_USAGE_DEFAULT;+ td.BindFlags = D3D11_BIND_SHADER_RESOURCE;+ if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, NULL, &a->tex))) {+ return 0;+ }+ if (FAILED(ID3D11Device_CreateShaderResourceView(g->dev, (ID3D11Resource *)a->tex, NULL,+ &a->srv)))+ {+ REL(a->tex);+ return 0;+ }+ return 1;+}++static void atlas_clear(Atlas *a)+{+ a->nshelves = 0;+ a->next_y = 0;+}++/* Finds room for w x h (+1 px gutter). 0 when full. */+static int atlas_place(Atlas *a, int w, int h, int *r_x, int *r_y)+{+ const int pw = w + 1, ph = h + 1;+ if (pw > a->size || ph > a->size) {+ return 0;+ }+ int best = -1;+ for (int i = 0; i < a->nshelves; i++) {+ if (a->shelf_h[i] >= ph && a->shelf_h[i] <= ph + ph / 4 + 2 && a->shelf_x[i] + pw <= a->size &&+ (best < 0 || a->shelf_h[i] < a->shelf_h[best]))+ {+ best = i;+ }+ }+ if (best < 0) {+ const int sh = (ph + 3) & ~3; /* round up: more strings share a shelf */+ if (a->nshelves == SHELVES || a->next_y + sh > a->size) {+ return 0;+ }+ best = a->nshelves++;+ a->shelf_y[best] = a->next_y;+ a->shelf_h[best] = sh;+ a->shelf_x[best] = 0;+ a->next_y += sh;+ }+ *r_x = a->shelf_x[best];+ *r_y = a->shelf_y[best];+ a->shelf_x[best] += pw;+ return 1;+}++static void atlas_upload(BuiGpu *g, Atlas *a, int x, int y, int w, int h, const void *data,+ int pitch)+{+ D3D11_BOX box = {(UINT)x, (UINT)y, 0, (UINT)(x + w), (UINT)(y + h), 1};+ ID3D11DeviceContext_UpdateSubresource(g->ctx, (ID3D11Resource *)a->tex, 0, &box, data,+ (UINT)pitch, 0);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Device (worker thread)+ * \{ */++typedef HRESULT(WINAPI *CreateDeviceFn)(IDXGIAdapter *, D3D_DRIVER_TYPE, HMODULE, UINT,+ const D3D_FEATURE_LEVEL *, UINT, UINT, ID3D11Device **,+ D3D_FEATURE_LEVEL *, ID3D11DeviceContext **);++/* BUI_GPU_DEBUG=1: why the GPU path wasn't taken */+static int fail(const char *what, HRESULT hr)+{+ const char *dbg = getenv("BUI_GPU_DEBUG");+ if (dbg && dbg[0] == '1') {+ fprintf(stderr, "bui gpu: %s failed (0x%08lx)\n", what, (unsigned long)hr);+ }+ return 0;+}++static int device_init(BuiGpu *g)+{+ HMODULE dll = LoadLibraryW(L"d3d11.dll");+ if (!dll) {+ return fail("loading d3d11.dll", 0);+ }+ CreateDeviceFn create = (CreateDeviceFn)(void *)GetProcAddress(dll, "D3D11CreateDevice");+ if (!create) {+ return 0;+ }+ const D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0,+ D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};+ const char *warp = getenv("BUI_GPU_WARP");+ const D3D_DRIVER_TYPE type = (warp && warp[0] == '1') ? D3D_DRIVER_TYPE_WARP :+ D3D_DRIVER_TYPE_HARDWARE;+ D3D_FEATURE_LEVEL got;+ HRESULT hr = create(NULL, type, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT, levels, 4,+ D3D11_SDK_VERSION, &g->dev, &got, &g->ctx);+ if (FAILED(hr)) { /* 11_1 unknown to the runtime: retry without it */+ hr = create(NULL, type, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT, levels + 1, 3,+ D3D11_SDK_VERSION, &g->dev, &got, &g->ctx);+ }+ if (FAILED(hr)) {+ return fail("D3D11CreateDevice", hr);+ }+ IDXGIDevice *xd = NULL;+ IDXGIAdapter *ad = NULL;+ if (FAILED(ID3D11Device_QueryInterface(g->dev, &k_IID_IDXGIDevice, (void **)&xd)) ||+ FAILED(IDXGIDevice_GetAdapter(xd, &ad)) ||+ FAILED(IDXGIAdapter_GetParent(ad, &k_IID_IDXGIFactory2, (void **)&g->factory)))+ {+ REL(ad);+ REL(xd);+ return fail("DXGI factory", 0);+ }+ REL(ad);+ REL(xd);++ ID3D11Device *d = g->dev;+ if (FAILED(ID3D11Device_CreateVertexShader(d, g_vs_quad, sizeof(g_vs_quad), NULL, &g->vs_quad)) ||+ FAILED(ID3D11Device_CreatePixelShader(d, g_ps_quad, sizeof(g_ps_quad), NULL, &g->ps_quad)) ||+ FAILED(ID3D11Device_CreateVertexShader(d, g_vs_tri, sizeof(g_vs_tri), NULL, &g->vs_tri)) ||+ FAILED(ID3D11Device_CreatePixelShader(d, g_ps_tri, sizeof(g_ps_tri), NULL, &g->ps_tri)))+ {+ return fail("shaders", 0);+ }+# define INST(name, idx, off) \+ {name, idx, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, off, D3D11_INPUT_PER_INSTANCE_DATA, 1}+ const D3D11_INPUT_ELEMENT_DESC il_quad[] = {+ INST("RECT", 0, 0), INST("BOUNDS", 0, 16), INST("COLOR", 0, 32), INST("COLOR", 1, 48),+ INST("COLOR", 2, 64), INST("COLOR", 3, 80), INST("PARAMS", 0, 96), INST("EXTRA", 0, 112),+ };+# undef INST+ const D3D11_INPUT_ELEMENT_DESC il_tri[] = {+ {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},+ {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0},+ {"CLIP", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},+ };+ if (FAILED(ID3D11Device_CreateInputLayout(d, il_quad, 8, g_vs_quad, sizeof(g_vs_quad),+ &g->il_quad)) ||+ FAILED(ID3D11Device_CreateInputLayout(d, il_tri, 3, g_vs_tri, sizeof(g_vs_tri), &g->il_tri)))+ {+ return fail("input layouts", 0);+ }+ D3D11_BUFFER_DESC bd = {0};+ bd.ByteWidth = 16;+ bd.Usage = D3D11_USAGE_DYNAMIC;+ bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;+ bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;+ if (FAILED(ID3D11Device_CreateBuffer(d, &bd, NULL, &g->cb))) {+ return fail("constant buffer", 0);+ }+ D3D11_BLEND_DESC bl = {0};+ bl.RenderTarget[0].BlendEnable = TRUE;+ bl.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;+ bl.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;+ bl.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;+ bl.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;+ bl.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;+ bl.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;+ bl.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;+ if (FAILED(ID3D11Device_CreateBlendState(d, &bl, &g->blend))) {+ return fail("blend state", 0);+ }+ D3D11_RASTERIZER_DESC rd = {0};+ rd.FillMode = D3D11_FILL_SOLID;+ rd.CullMode = D3D11_CULL_NONE;+ rd.DepthClipEnable = TRUE;+ if (FAILED(ID3D11Device_CreateRasterizerState(d, &rd, &g->rs))) {+ return fail("rasterizer state", 0);+ }+ if (!atlas_create(g, &g->mask, 2048, 1)) {+ return fail("atlas", 0);+ }+ return 1;+}++static DWORD WINAPI device_thread(void *arg)+{+ BuiGpu *g = (BuiGpu *)arg;+ const int ok = device_init(g);+ InterlockedExchange(&g->state, ok ? 1 : -1);+ return 0;+}++BuiGpu *bui_gpu_create(void *hwnd)+{+ BuiGpu *g = (BuiGpu *)calloc(1, sizeof(BuiGpu));+ if (!g) {+ return NULL;+ }+ g->hwnd = (HWND)hwnd;+ g->mask_map = (Slot *)calloc(MASK_MAP, sizeof(Slot));+ g->img_map = (Slot *)calloc(IMG_MAP, sizeof(Slot));+ g->thread = CreateThread(NULL, 0, device_thread, g, 0, NULL);+ if (!g->thread || !g->mask_map || !g->img_map) {+ if (g->thread) {+ WaitForSingleObject(g->thread, INFINITE);+ CloseHandle(g->thread);+ g->thread = NULL;+ }+ bui_gpu_free(g);+ return NULL;+ }+ return g;+}++int bui_gpu_state(BuiGpu *g, int wait)+{+ if (wait && g->thread) {+ WaitForSingleObject(g->thread, INFINITE);+ }+ const LONG s = InterlockedCompareExchange(&g->state, 0, 0);+ if (s != 0 && g->thread) {+ WaitForSingleObject(g->thread, INFINITE);+ CloseHandle(g->thread);+ g->thread = NULL;+ }+ return (int)s;+}++void bui_gpu_free(BuiGpu *g)+{+ if (!g) {+ return;+ }+ if (g->thread) {+ WaitForSingleObject(g->thread, INFINITE);+ CloseHandle(g->thread);+ }+ if (g->ctx) {+ ID3D11DeviceContext_ClearState(g->ctx);+ }+ REL(g->mask.srv);+ REL(g->mask.tex);+ REL(g->rgba.srv);+ REL(g->rgba.tex);+ REL(g->rtv);+ REL(g->target);+ REL(g->rs);+ REL(g->blend);+ REL(g->cb);+ REL(g->ib);+ REL(g->tb);+ REL(g->il_quad);+ REL(g->il_tri);+ REL(g->vs_quad);+ REL(g->vs_tri);+ REL(g->ps_quad);+ REL(g->ps_tri);+ REL(g->swap);+ REL(g->factory);+ REL(g->ctx);+ REL(g->dev);+ free(g->inst);+ free(g->tv);+ free(g->b);+ free(g->mask_map);+ free(g->img_map);+ free(g);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Recording+ * \{ */++static void flush(BuiGpu *g);++void bui_gpu_begin(BuiGpu *g, int w, int h)+{+ g->w = w > 0 ? w : 1;+ g->h = h > 0 ? h : 1;+}++static Batch *batch_for(BuiGpu *g, int tri, int first)+{+ if (g->n_b > 0 && g->b[g->n_b - 1].tri == tri) {+ return &g->b[g->n_b - 1];+ }+ if (g->n_b == g->cap_b) {+ const int cap = g->cap_b ? g->cap_b * 2 : 64;+ Batch *nb = (Batch *)realloc(g->b, sizeof(Batch) * (size_t)cap);+ if (!nb) {+ return NULL;+ }+ g->b = nb;+ g->cap_b = cap;+ }+ Batch *b = &g->b[g->n_b++];+ b->tri = tri;+ b->first = first;+ b->count = 0;+ return b;+}++BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1)+{+ if (g->n_inst == g->cap_inst) {+ const int cap = g->cap_inst ? g->cap_inst * 2 : 1024;+ BuiGpuInst *ni = (BuiGpuInst *)realloc(g->inst, sizeof(BuiGpuInst) * (size_t)cap);+ if (!ni) {+ return NULL;+ }+ g->inst = ni;+ g->cap_inst = cap;+ }+ Batch *b = batch_for(g, 0, g->n_inst);+ if (!b) {+ return NULL;+ }+ b->count++;+ BuiGpuInst *in = &g->inst[g->n_inst++];+ memset(in, 0, sizeof(*in));+ in->bounds[0] = (float)x0;+ in->bounds[1] = (float)y0;+ in->bounds[2] = (float)x1;+ in->bounds[3] = (float)y1;+ in->p[0] = (float)kind;+ return in;+}++void bui_gpu_triangles(BuiGpu *g,+ const float (*co)[2],+ const float (*col)[4],+ int count,+ const int clip[4])+{+ count -= count % 3;+ if (count <= 0) {+ return;+ }+ if (g->n_tv + count > g->cap_tv) {+ int cap = g->cap_tv ? g->cap_tv : 1024;+ while (cap < g->n_tv + count) {+ cap *= 2;+ }+ TriV *nt = (TriV *)realloc(g->tv, sizeof(TriV) * (size_t)cap);+ if (!nt) {+ return;+ }+ g->tv = nt;+ g->cap_tv = cap;+ }+ Batch *b = batch_for(g, 1, g->n_tv);+ if (!b) {+ return;+ }+ for (int i = 0; i < count; i++) {+ TriV *v = &g->tv[g->n_tv++];+ v->x = co[i][0];+ v->y = co[i][1];+ memcpy(v->c, col[i], sizeof(v->c));+ for (int k = 0; k < 4; k++) {+ v->clip[k] = (float)clip[k];+ }+ }+ b->count += count;+}++static uint64_t mix64(uint64_t h)+{+ h ^= h >> 33;+ h *= 0xff51afd7ed558ccdull;+ h ^= h >> 33;+ return h;+}++static void mask_reset(BuiGpu *g)+{+ flush(g); /* recorded instances still point into the old layout */+ atlas_clear(&g->mask);+ memset(g->mask_map, 0, sizeof(Slot) * MASK_MAP);+ g->mask_n = 0;+}++int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h,+ int *r_x, int *r_y)+{+ if (w + 1 > g->mask.size || h + 1 > g->mask.size) {+ return 0;+ }+ if (gen != g->mask_gen) { /* text runs were freed: their keys may be reused */+ g->mask_gen = gen;+ mask_reset(g);+ }+ const uint64_t k1 = key ? (uint64_t)(uintptr_t)key : 0, k2 = ((uint64_t)w << 32) | (uint32_t)h;+ uint32_t idx = 0;+ if (key) {+ idx = (uint32_t)mix64(k1) & (MASK_MAP - 1);+ for (;;) {+ Slot *s = &g->mask_map[idx];+ if (s->k1 == 0) {+ break;+ }+ if (s->k1 == k1 && s->k2 == k2) {+ *r_x = s->x;+ *r_y = s->y;+ return 1;+ }+ idx = (idx + 1) & (MASK_MAP - 1);+ }+ if (g->mask_n >= MASK_MAP_FILL) {+ mask_reset(g);+ return bui_gpu_mask(g, key, gen, mask, w, h, r_x, r_y);+ }+ }+ int x, y;+ if (!atlas_place(&g->mask, w, h, &x, &y)) {+ mask_reset(g); /* empty now, and the map slot must be found again */+ return bui_gpu_mask(g, key, gen, mask, w, h, r_x, r_y);+ }+ atlas_upload(g, &g->mask, x, y, w, h, mask, w);+ if (key) {+ Slot *s = &g->mask_map[idx];+ s->k1 = k1;+ s->k2 = k2;+ s->x = x;+ s->y = y;+ g->mask_n++;+ }+ *r_x = x;+ *r_y = y;+ return 1;+}++static void img_reset(BuiGpu *g)+{+ flush(g);+ atlas_clear(&g->rgba);+ memset(g->img_map, 0, sizeof(Slot) * IMG_MAP);+ g->img_n = 0;+}++int bui_gpu_image(BuiGpu *g, const uint32_t *argb, int w, int h, int *r_x, int *r_y)+{+ if (!g->rgba.tex && !atlas_create(g, &g->rgba, 2048, 4)) {+ return 0;+ }+ if (w + 1 > g->rgba.size || h + 1 > g->rgba.size) {+ return 0; /* TODO: images larger than the atlas */+ }+ /* content hash: an image updated in place gets a new entry */+ uint64_t hsh = 1469598103934665603ull;+ const size_t n = (size_t)w * h;+ for (size_t i = 0; i < n; i++) {+ hsh = (hsh ^ argb[i]) * 1099511628211ull;+ }+ const uint64_t k1 = hsh | 1, k2 = ((uint64_t)w << 32) | (uint32_t)h;+ uint32_t idx = (uint32_t)mix64(k1) & (IMG_MAP - 1);+ for (;;) {+ Slot *s = &g->img_map[idx];+ if (s->k1 == 0) {+ break;+ }+ if (s->k1 == k1 && s->k2 == k2) {+ *r_x = s->x;+ *r_y = s->y;+ return 1;+ }+ idx = (idx + 1) & (IMG_MAP - 1);+ }+ int x, y;+ if (g->img_n >= IMG_MAP_FILL || !atlas_place(&g->rgba, w, h, &x, &y)) {+ img_reset(g);+ return bui_gpu_image(g, argb, w, h, r_x, r_y);+ }+ atlas_upload(g, &g->rgba, x, y, w, h, argb, w * 4);+ Slot *s = &g->img_map[idx];+ s->k1 = k1;+ s->k2 = k2;+ s->x = x;+ s->y = y;+ g->img_n++;+ *r_x = x;+ *r_y = y;+ return 1;+}++void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h)+{+ if (w <= 0 || h <= 0 || g->n_dmg == (int)(sizeof(g->dmg) / sizeof(g->dmg[0]))) {+ g->dmg_full = 1;+ return;+ }+ RECT *r = &g->dmg[g->n_dmg++];+ r->left = x;+ r->top = y;+ r->right = x + w;+ r->bottom = y + h;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Drawing + present+ * \{ */++static int ensure_target(BuiGpu *g)+{+ if (g->target && g->tw == g->w && g->th == g->h) {+ return 1;+ }+ REL(g->rtv);+ REL(g->target);+ D3D11_TEXTURE2D_DESC td = {0};+ td.Width = (UINT)g->w;+ td.Height = (UINT)g->h;+ td.MipLevels = td.ArraySize = 1;+ td.Format = DXGI_FORMAT_B8G8R8A8_UNORM;+ td.SampleDesc.Count = 1;+ td.Usage = D3D11_USAGE_DEFAULT;+ td.BindFlags = D3D11_BIND_RENDER_TARGET;+ if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, NULL, &g->target)) ||+ FAILED(ID3D11Device_CreateRenderTargetView(g->dev, (ID3D11Resource *)g->target, NULL,+ &g->rtv)))+ {+ REL(g->target);+ return 0;+ }+ g->tw = g->w;+ g->th = g->h;+ const float black[4] = {0, 0, 0, 1};+ ID3D11DeviceContext_ClearRenderTargetView(g->ctx, g->rtv, black);+ g->dmg_full = 1;+ return 1;+}++static int ensure_buffer(BuiGpu *g, ID3D11Buffer **buf, UINT *cap, UINT need, UINT stride)+{+ if (*buf && *cap >= need) {+ return 1;+ }+ REL(*buf);+ UINT c = *cap ? *cap : 4096;+ while (c < need) {+ c *= 2;+ }+ D3D11_BUFFER_DESC bd = {0};+ bd.ByteWidth = c * stride;+ bd.Usage = D3D11_USAGE_DYNAMIC;+ bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;+ bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;+ if (FAILED(ID3D11Device_CreateBuffer(g->dev, &bd, NULL, buf))) {+ *cap = 0;+ return 0;+ }+ *cap = c;+ return 1;+}++static void upload(BuiGpu *g, ID3D11Buffer *buf, const void *data, size_t bytes)+{+ D3D11_MAPPED_SUBRESOURCE m;+ if (SUCCEEDED(ID3D11DeviceContext_Map(g->ctx, (ID3D11Resource *)buf, 0, D3D11_MAP_WRITE_DISCARD,+ 0, &m)))+ {+ memcpy(m.pData, data, bytes);+ ID3D11DeviceContext_Unmap(g->ctx, (ID3D11Resource *)buf, 0);+ }+}++static void flush(BuiGpu *g)+{+ if (g->n_b == 0) {+ return;+ }+ if (!ensure_target(g)) {+ g->n_b = g->n_inst = g->n_tv = 0;+ return;+ }+ ID3D11DeviceContext *c = g->ctx;+ if (g->n_inst && ensure_buffer(g, &g->ib, &g->ib_cap, (UINT)g->n_inst, sizeof(BuiGpuInst))) {+ upload(g, g->ib, g->inst, sizeof(BuiGpuInst) * (size_t)g->n_inst);+ }+ if (g->n_tv && ensure_buffer(g, &g->tb, &g->tb_cap, (UINT)g->n_tv, sizeof(TriV))) {+ upload(g, g->tb, g->tv, sizeof(TriV) * (size_t)g->n_tv);+ }+ const float cbd[4] = {2.0f / (float)g->tw, 2.0f / (float)g->th, 0, 0};+ upload(g, g->cb, cbd, sizeof(cbd));++ ID3D11DeviceContext_OMSetRenderTargets(c, 1, &g->rtv, NULL);+ const float bf[4] = {0, 0, 0, 0};+ ID3D11DeviceContext_OMSetBlendState(c, g->blend, bf, 0xffffffffu);+ D3D11_VIEWPORT vp = {0, 0, (float)g->tw, (float)g->th, 0, 1};+ ID3D11DeviceContext_RSSetViewports(c, 1, &vp);+ ID3D11DeviceContext_RSSetState(c, g->rs);+ ID3D11DeviceContext_VSSetConstantBuffers(c, 0, 1, &g->cb);+ ID3D11ShaderResourceView *srv[2] = {g->mask.srv, g->rgba.srv};+ ID3D11DeviceContext_PSSetShaderResources(c, 0, 2, srv);++ int cur = -1;+ for (int i = 0; i < g->n_b; i++) {+ const Batch *b = &g->b[i];+ if (b->count == 0) {+ continue;+ }+ if (b->tri != cur) {+ cur = b->tri;+ UINT off = 0;+ if (!b->tri) {+ UINT stride = sizeof(BuiGpuInst);+ ID3D11DeviceContext_IASetInputLayout(c, g->il_quad);+ ID3D11DeviceContext_IASetVertexBuffers(c, 0, 1, &g->ib, &stride, &off);+ ID3D11DeviceContext_IASetPrimitiveTopology(c, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);+ ID3D11DeviceContext_VSSetShader(c, g->vs_quad, NULL, 0);+ ID3D11DeviceContext_PSSetShader(c, g->ps_quad, NULL, 0);+ }+ else {+ UINT stride = sizeof(TriV);+ ID3D11DeviceContext_IASetInputLayout(c, g->il_tri);+ ID3D11DeviceContext_IASetVertexBuffers(c, 0, 1, &g->tb, &stride, &off);+ ID3D11DeviceContext_IASetPrimitiveTopology(c, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);+ ID3D11DeviceContext_VSSetShader(c, g->vs_tri, NULL, 0);+ ID3D11DeviceContext_PSSetShader(c, g->ps_tri, NULL, 0);+ }+ }+ if (!b->tri) {+ ID3D11DeviceContext_DrawInstanced(c, 4, (UINT)b->count, 0, (UINT)b->first);+ }+ else {+ ID3D11DeviceContext_Draw(c, (UINT)b->count, (UINT)b->first);+ }+ }+ g->n_b = g->n_inst = g->n_tv = 0;+}++static int ensure_swap(BuiGpu *g)+{+ if (g->swap && g->sw == g->w && g->sh == g->h) {+ return 1;+ }+ if (g->swap) {+ ID3D11DeviceContext_OMSetRenderTargets(g->ctx, 0, NULL, NULL);+ if (FAILED(IDXGISwapChain1_ResizeBuffers(g->swap, 0, (UINT)g->w, (UINT)g->h,+ DXGI_FORMAT_UNKNOWN, 0)))+ {+ return 0;+ }+ }+ else {+ DXGI_SWAP_CHAIN_DESC1 sd = {0};+ sd.Width = (UINT)g->w;+ sd.Height = (UINT)g->h;+ sd.Format = DXGI_FORMAT_B8G8R8A8_UNORM;+ sd.SampleDesc.Count = 1;+ sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;+ sd.BufferCount = 2;+ sd.Scaling = DXGI_SCALING_NONE;+ sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;+ sd.AlphaMode = DXGI_ALPHA_MODE_IGNORE;+ if (FAILED(IDXGIFactory2_CreateSwapChainForHwnd(g->factory, (IUnknown *)g->dev, g->hwnd, &sd,+ NULL, NULL, &g->swap)))+ {+ return 0;+ }+ IDXGIFactory2_MakeWindowAssociation(g->factory, g->hwnd, DXGI_MWA_NO_ALT_ENTER);+ }+ g->sw = g->w;+ g->sh = g->h;+ g->swap_fresh = 1;+ return 1;+}++int bui_gpu_present(BuiGpu *g, int full)+{+ flush(g);+ if (!g->target || !ensure_swap(g)) {+ g->n_dmg = g->dmg_full = 0;+ return g->target != NULL;+ }+ ID3D11Texture2D *back = NULL;+ if (FAILED(IDXGISwapChain1_GetBuffer(g->swap, 0, &k_IID_ID3D11Texture2D, (void **)&back))) {+ return 0;+ }+ /* the flip model hands back an older buffer: copy the whole frame */+ ID3D11DeviceContext_CopyResource(g->ctx, (ID3D11Resource *)back, (ID3D11Resource *)g->target);+ REL(back);+ DXGI_PRESENT_PARAMETERS pp = {0};+ if (!(full || g->dmg_full || g->swap_fresh) && g->n_dmg > 0) {+ for (int i = 0; i < g->n_dmg; i++) { /* clamp: DXGI rejects rects outside the buffer */+ RECT *r = &g->dmg[i];+ r->left = r->left < 0 ? 0 : r->left;+ r->top = r->top < 0 ? 0 : r->top;+ r->right = r->right > g->w ? g->w : r->right;+ r->bottom = r->bottom > g->h ? g->h : r->bottom;+ if (r->right <= r->left || r->bottom <= r->top) {+ *r = g->dmg[--g->n_dmg];+ i--;+ }+ }+ pp.DirtyRectsCount = (UINT)g->n_dmg;+ pp.pDirtyRects = g->n_dmg ? g->dmg : NULL;+ }+ const HRESULT hr = IDXGISwapChain1_Present1(g->swap, 0, 0, &pp);+ g->swap_fresh = 0;+ g->n_dmg = g->dmg_full = 0;+ return !(hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET);+}++int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h)+{+ flush(g);+ if (!g->target || g->tw != w || g->th != h) {+ return 0;+ }+ D3D11_TEXTURE2D_DESC td = {0};+ td.Width = (UINT)w;+ td.Height = (UINT)h;+ td.MipLevels = td.ArraySize = 1;+ td.Format = DXGI_FORMAT_B8G8R8A8_UNORM;+ td.SampleDesc.Count = 1;+ td.Usage = D3D11_USAGE_STAGING;+ td.CPUAccessFlags = D3D11_CPU_ACCESS_READ;+ ID3D11Texture2D *st = NULL;+ if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, NULL, &st))) {+ return 0;+ }+ ID3D11DeviceContext_CopyResource(g->ctx, (ID3D11Resource *)st, (ID3D11Resource *)g->target);+ D3D11_MAPPED_SUBRESOURCE m;+ int ok = 0;+ if (SUCCEEDED(ID3D11DeviceContext_Map(g->ctx, (ID3D11Resource *)st, 0, D3D11_MAP_READ, 0, &m))) {+ for (int y = 0; y < h; y++) {+ const uint32_t *src = (const uint32_t *)((const uint8_t *)m.pData + (size_t)y * m.RowPitch);+ for (int x = 0; x < w; x++) {+ dst[(size_t)y * w + x] = src[x] & 0xFFFFFFu; /* 0x00RRGGBB like the raster */+ }+ }+ ID3D11DeviceContext_Unmap(g->ctx, (ID3D11Resource *)st, 0);+ ok = 1;+ }+ REL(st);+ return ok;+}++/** \} */++#else /* !_WIN32: no GPU backend yet; every raster stays in software */++# include <stddef.h>++# include "gpu_d3d11.h"++BuiGpu *bui_gpu_create(void *hwnd)+{+ (void)hwnd;+ return NULL;+}+void bui_gpu_free(BuiGpu *g)+{+ (void)g;+}+int bui_gpu_state(BuiGpu *g, int wait)+{+ (void)g;+ (void)wait;+ return -1;+}+void bui_gpu_begin(BuiGpu *g, int w, int h)+{+ (void)g;+ (void)w;+ (void)h;+}+BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1)+{+ (void)g;+ (void)kind;+ (void)x0;+ (void)y0;+ (void)x1;+ (void)y1;+ return NULL;+}+int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h,+ int *r_x, int *r_y)+{+ (void)g;+ (void)key;+ (void)gen;+ (void)mask;+ (void)w;+ (void)h;+ (void)r_x;+ (void)r_y;+ return 0;+}+int bui_gpu_image(BuiGpu *g, const uint32_t *argb, int w, int h, int *r_x, int *r_y)+{+ (void)g;+ (void)argb;+ (void)w;+ (void)h;+ (void)r_x;+ (void)r_y;+ return 0;+}+void bui_gpu_triangles(+ BuiGpu *g, const float (*co)[2], const float (*col)[4], int count, const int clip[4])+{+ (void)g;+ (void)co;+ (void)col;+ (void)count;+ (void)clip;+}+void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h)+{+ (void)g;+ (void)x;+ (void)y;+ (void)w;+ (void)h;+}+int bui_gpu_present(BuiGpu *g, int full)+{+ (void)g;+ (void)full;+ return 0;+}+int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h)+{+ (void)g;+ (void)dst;+ (void)w;+ (void)h;+ return 0;+}++#endif /* _WIN32 */diff --git a/gpu/intern/gpu_d3d11.h b/gpu/intern/gpu_d3d11.hnew file mode 100644index 0000000..4849219--- /dev/null+++ b/gpu/intern/gpu_d3d11.h@@ -0,0 +1,70 @@+/* BUI GPU renderer (Direct3D 11) — private interface for gpu_raster.c.+ *+ * A BuiRaster in GPU mode records its primitives as instances instead of+ * rasterizing them; this backend draws them into a persistent render target+ * (so damage-region redraws work exactly like the software raster) and+ * presents it with a flip-model swap chain plus dirty rects.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */+#pragma once++#include <stdint.h>++/* instance kinds: keep in sync with gpu/shaders/bui_ui.hlsl */+enum {+ BG_RECT = 0,+ BG_WIDGET = 1,+ BG_ELLIPSE = 2,+ BG_LINE = 3,+ BG_MASK = 4,+ BG_IMAGE = 5,+ BG_SHADOW = 6,+ BG_GRADIENT = 7,+ BG_HSV = 8,+ BG_SPHERE = 9,+};+enum {+ BG_W_SHADE_H = 1,+ BG_W_CHECKER = 2,+ BG_W_LEGACY = 4,+ BG_W_INNER = 8,+};++typedef struct BuiGpuInst {+ float rect[4];+ float bounds[4]; /* x0, y0, x1, y1: pixel box, already clipped */+ float c0[4], c1[4], c2[4], c3[4];+ float p[4]; /* p[0] = kind */+ float uv[4];+} BuiGpuInst;++typedef struct BuiGpu BuiGpu;++/* Starts creating the device on a worker thread (the first frames keep+ * using the software raster). NULL when D3D11 isn't available. */+BuiGpu *bui_gpu_create(void *hwnd);+void bui_gpu_free(BuiGpu *g);+/* 1 once the device is ready, -1 when creation failed, 0 while pending+ * (never 0 with `wait`). */+int bui_gpu_state(BuiGpu *g, int wait);++void bui_gpu_begin(BuiGpu *g, int w, int h);+/* Appends an instance (zeroed except kind and bounds). */+BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1);+/* Atlas placement of an 8-bit mask keyed by `key` (NULL key: not cached).+ * Returns 0 when it can't be placed. */+int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h,+ int *r_x, int *r_y);+/* Atlas placement of a 0xAARRGGBB image (cached by content). */+int bui_gpu_image(BuiGpu *g, const uint32_t *argb, int w, int h, int *r_x, int *r_y);+void bui_gpu_triangles(BuiGpu *g,+ const float (*co)[2],+ const float (*col)[4],+ int count,+ const int clip[4]);+/* Records damage for present (x, y, w, h); w <= 0 means the whole frame. */+void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h);+/* Draws everything recorded and presents. Returns 0 on device loss. */+int bui_gpu_present(BuiGpu *g, int full);+/* Reads the frame back as 0x00RRGGBB rows. 0 when there is none yet. */+int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h);diff --git a/gpu/intern/gpu_d3d11_shaders.h b/gpu/intern/gpu_d3d11_shaders.hnew file mode 100644index 0000000..3b392a5--- /dev/null+++ b/gpu/intern/gpu_d3d11_shaders.h@@ -0,0 +1,2098 @@+/* Generated by gpu/shaders/build.sh from bui_ui.hlsl. Do not edit. */+const BYTE g_vs_quad[] =+{+ 68, 88,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1, 0,+ 0, 0, 49, 0, 0, 7,+ 50, 0, 16, 0, 0, 0,+ 0, 0, 70, 16, 16, 0,+ 0, 0, 0, 0, 70, 16,+ 16, 0, 2, 0, 0, 0,+ 60, 0, 0, 7, 18, 0,+ 16, 0, 0, 0, 0, 0,+ 26, 0, 16, 0, 0, 0,+ 0, 0, 10, 0, 16, 0,+ 0, 0, 0, 0, 29, 0,+ 0, 7, 98, 0, 16, 0,+ 0, 0, 0, 0, 6, 17,+ 16, 0, 0, 0, 0, 0,+ 166, 27, 16, 0, 2, 0,+ 0, 0, 60, 0, 0, 7,+ 18, 0, 16, 0, 0, 0,+ 0, 0, 26, 0, 16, 0,+ 0, 0, 0, 0, 10, 0,+ 16, 0, 0, 0, 0, 0,+ 60, 0, 0, 7, 18, 0,+ 16, 0, 0, 0, 0, 0,+ 42, 0, 16, 0, 0, 0,+ 0, 0, 10, 0, 16, 0,+ 0, 0, 0, 0, 13, 0,+ 4, 3, 10, 0, 16, 0,+ 0, 0, 0, 0, 54, 32,+ 0, 5, 18, 0, 16, 0,+ 0, 0, 0, 0, 58, 16,+ 16, 0, 1, 0, 0, 0,+ 56, 0, 0, 7, 114, 32,+ 16, 0, 0, 0, 0, 0,+ 6, 0, 16, 0, 0, 0,+ 0, 0, 70, 18, 16, 0,+ 1, 0, 0, 0, 54, 0,+ 0, 5, 130, 32, 16, 0,+ 0, 0, 0, 0, 10, 0,+ 16, 0, 0, 0, 0, 0,+ 62, 0, 0, 1+};diff --git a/gpu/intern/gpu_raster.c b/gpu/intern/gpu_raster.cindex 84d1c62..7e1a405 100644--- a/gpu/intern/gpu_raster.c+++ b/gpu/intern/gpu_raster.c@@ -1,6 +1,7 @@/* BUI software raster backend — see GPU_raster.h.* SPDX-License-Identifier: GPL-2.0-or-later */#include "GPU_raster.h"+#include "gpu_d3d11.h"#include <math.h>#include <stdlib.h>@@ -25,6 +26,13 @@ struct BuiRaster {int font_flags;BuiGpuSink sink;++ /* GPU mode: primitives are recorded as instances (gpu_d3d11.c) and pix /+ * prev are not allocated (read back on demand by BUI_raster_pixels). */+ BuiGpu *gpu;+ BuiGpu *gpu_pending;+ int gpu_switched; /* the renderer changed: the next frame must be full */+ struct BuiRaster *scratch; /* CPU coverage for polygons in GPU mode */};/* -------------------------------------------------------------------- */@@ -120,6 +128,12 @@ static void raster_alloc(BuiRaster *r, int w, int h)free(r->prev);r->w = w > 0 ? w : 1;r->h = h > 0 ? h : 1;+ if (r->gpu) { /* the frame lives on the GPU */+ r->pix = r->prev = NULL;+ r->full_damage = 1;+ raster_reset_clip(r);+ return;+ }r->pix = (uint32_t *)calloc((size_t)r->w * r->h, sizeof(uint32_t));r->prev = (uint32_t *)calloc((size_t)r->w * r->h, sizeof(uint32_t));r->full_damage = 1;@@ -180,6 +194,9 @@ void BUI_raster_free(BuiRaster *r)if (!r) {return;}+ bui_gpu_free(r->gpu);+ bui_gpu_free(r->gpu_pending);+ BUI_raster_free(r->scratch);free(r->pix);free(r->prev);free(r->damage);@@ -197,8 +214,110 @@ void BUI_raster_begin_frame(BuiRaster *r, int width, int height)raster_alloc(r, width, height);}raster_reset_clip(r);+ if (r->gpu) {+ bui_gpu_begin(r->gpu, r->w, r->h);+ }+}++/* -------------------------------------------------------------------- */+/** \name GPU mode+ * \{ */++static int g_gpu_default = -1;++void BUI_gpu_set_default(int on)+{+ g_gpu_default = on ? 1 : 0;+}++int BUI_gpu_default(void)+{+ const char *env = getenv("BUI_GPU");+ if (env && env[0]) {+ return env[0] == '1' || env[0] == 'y' || env[0] == 'Y' || env[0] == 't' || env[0] == 'T';+ }+ return g_gpu_default > 0;+}++int BUI_raster_gpu_attach(BuiRaster *r, void *window_handle, int wait)+{+ if (r->gpu || r->gpu_pending) {+ return 1;+ }+ r->gpu_pending = bui_gpu_create(window_handle);+ if (!r->gpu_pending) {+ return 0;+ }+ if (wait) {+ bui_gpu_state(r->gpu_pending, 1);+ BUI_raster_gpu_poll(r);+ return r->gpu != NULL;+ }+ return 1;+}++int BUI_raster_gpu_poll(BuiRaster *r)+{+ if (r->gpu_pending) {+ const int st = bui_gpu_state(r->gpu_pending, 0);+ if (st == 0) {+ return 0;+ }+ if (st > 0) {+ r->gpu = r->gpu_pending;+ r->gpu_pending = NULL;+ raster_alloc(r, r->w, r->h); /* drops the CPU frame */+ bui_gpu_begin(r->gpu, r->w, r->h);+ r->gpu_switched = 1;+ }+ else {+ bui_gpu_free(r->gpu_pending);+ r->gpu_pending = NULL;+ }+ }+ const int sw = r->gpu_switched;+ r->gpu_switched = 0;+ return sw;+}++int BUI_raster_is_gpu(const BuiRaster *r)+{+ return r->gpu != NULL;+}++/* back to the software raster (device lost) */+static void gpu_drop(BuiRaster *r)+{+ bui_gpu_free(r->gpu);+ r->gpu = NULL;+ r->pix = r->prev = NULL;+ raster_alloc(r, r->w, r->h);+ r->gpu_switched = 1;+}++/* Instance over the clipped pixel box; NULL when nothing to draw. */+static BuiGpuInst *gpu_inst(BuiRaster *r, int kind, int x0, int y0, int x1, int y1)+{+ return bui_gpu_inst(r->gpu, kind, x0, y0, x1, y1);+}++static void v4(float d[4], float a, float b, float c, float e)+{+ d[0] = a;+ d[1] = b;+ d[2] = c;+ d[3] = e;+}++static void c4(float d[4], const float *s)+{+ if (s) {+ memcpy(d, s, sizeof(float[4]));+ }}+/** \} */+static void damage_push(BuiRaster *r, int x, int y, int w, int h){/* Merge with the previous rect when it is the same column span directly@@ -229,6 +348,12 @@ static void damage_push(BuiRaster *r, int x, int y, int w, int h)void BUI_raster_end_frame(BuiRaster *r){r->damage_len = 0;+ if (r->gpu) {+ bui_gpu_damage(r->gpu, 0, 0, 0, 0);+ damage_push(r, 0, 0, r->w, r->h);+ r->full_damage = 0;+ return;+ }const size_t total = (size_t)r->w * r->h;if (r->full_damage) {damage_push(r, 0, 0, r->w, r->h);@@ -280,6 +405,15 @@ int BUI_raster_height(const BuiRaster *r)}const uint32_t *BUI_raster_pixels(const BuiRaster *r){+ if (r->gpu) { /* read the GPU frame back (tests, screenshots) */+ BuiRaster *m = (BuiRaster *)r;+ if (!m->prev) {+ m->prev = (uint32_t *)malloc((size_t)r->w * r->h * sizeof(uint32_t));+ }+ if (m->prev && bui_gpu_read(r->gpu, m->prev, r->w, r->h)) {+ return m->prev;+ }+ }return r->pix;}@@ -332,6 +466,14 @@ void BUI_raster_fill_rect(BuiRaster *r, float x, float y, float w, float h, consif (!clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {return;}+ if (r->gpu) {+ BuiGpuInst *in = rgba[3] > 0.0f ? gpu_inst(r, BG_RECT, x0, y0, x1, y1) : NULL;+ if (in) {+ v4(in->rect, x, y, w, h);+ c4(in->c0, rgba);+ }+ return;+ }const Paint p = paint_from(rgba);if (p.a <= 0) {return;@@ -410,6 +552,17 @@ void BUI_raster_round_rect(if (!clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {return;}+ if (r->gpu) {+ BuiGpuInst *in = rgba[3] > 0.0f ? gpu_inst(r, BG_WIDGET, x0, y0, x1, y1) : NULL;+ if (in) {+ v4(in->rect, x, y, w, h);+ c4(in->c0, rgba);+ c4(in->c1, rgba);+ v4(in->p, BG_WIDGET, rad, rad, 0.0f);+ v4(in->uv, BUI_CORNER_ALL, BG_W_INNER, 0.0f, 0.0f);+ }+ return;+ }const Paint p = paint_from(rgba);if (p.a <= 0) {return;@@ -491,6 +644,15 @@ void BUI_raster_circle(if (!clip_box(r, cx - ext, cy - ext, cx + ext, cy + ext, &x0, &y0, &x1, &y1)) {return;}+ if (r->gpu) {+ BuiGpuInst *in = rgba[3] > 0.0f ? gpu_inst(r, BG_ELLIPSE, x0, y0, x1, y1) : NULL;+ if (in) {+ v4(in->rect, cx, cy, radius, radius);+ c4(in->c0, rgba);+ in->p[1] = line_width;+ }+ return;+ }const Paint p = paint_from(rgba);if (p.a <= 0) {return;@@ -541,6 +703,15 @@ void BUI_raster_line({return;}+ if (r->gpu) {+ BuiGpuInst *in = rgba[3] > 0.0f ? gpu_inst(r, BG_LINE, ix0, iy0, ix1, iy1) : NULL;+ if (in) {+ v4(in->rect, ax, ay, bx, by);+ c4(in->c0, rgba);+ in->p[1] = hw;+ }+ return;+ }const Paint p = paint_from(rgba);if (p.a <= 0) {return;@@ -584,6 +755,15 @@ void BUI_raster_ellipse(BuiRaster *r,{return;}+ if (r->gpu) {+ BuiGpuInst *in = rgba[3] > 0.0f ? gpu_inst(r, BG_ELLIPSE, x0, y0, x1, y1) : NULL;+ if (in) {+ v4(in->rect, cx, cy, rx, ry);+ c4(in->c0, rgba);+ in->p[1] = line_width;+ }+ return;+ }const Paint p = paint_from(rgba);if (p.a <= 0) {return;@@ -663,6 +843,23 @@ void BUI_raster_widget(BuiRaster *r,}const float *top = inner_top ? inner_top : inner_bottom;const float *bot = inner_bottom ? inner_bottom : inner_top;+ if (r->gpu) {+ BuiGpuInst *in = gpu_inst(r, BG_WIDGET, x0, y0, x1, y1);+ if (in) {+ v4(in->rect, x, y, w, h);+ c4(in->c0, top);+ c4(in->c1, bot);+ if (ow > 0.0f) {+ c4(in->c2, outline);+ }+ if (has_emboss) {+ c4(in->c3, emboss);+ }+ v4(in->p, BG_WIDGET, rad, rad, 1.0f);+ v4(in->uv, (float)corners, (float)(BG_W_LEGACY | (top ? BG_W_INNER : 0)), ow, 0.0f);+ }+ return;+ }const int gradient = top && bot && memcmp(top, bot, sizeof(float[4])) != 0;Paint p_inner = top ? paint_from(top) : (Paint){0, 0};const Paint p_out = outline ? paint_from(outline) : (Paint){0, 0};@@ -764,6 +961,25 @@ void BUI_raster_widget_base(BuiRaster *r, const BuiWidgetBase *p)if (!clip_box(r, x - 1.0f, y - 1.0f, x + w + 1.0f, y + h + px1 + 1.0f, &x0, &y0, &x1, &y1)) {return;}+ if (r->gpu) {+ BuiGpuInst *in = gpu_inst(r, BG_WIDGET, x0, y0, x1, y1);+ if (in) {+ v4(in->rect, x, y, w, h);+ c4(in->c0, p->inner1);+ c4(in->c1, p->inner2);+ if (has_outline) {+ c4(in->c2, p->outline);+ }+ if (has_emboss) {+ c4(in->c3, p->emboss);+ }+ v4(in->p, BG_WIDGET, rad, radi, px1);+ const int flags = (p->shade_horizontal ? BG_W_SHADE_H : 0) |+ (p->alpha_checker ? BG_W_CHECKER : 0) | (has_inner ? BG_W_INNER : 0);+ v4(in->uv, (float)p->corners, (float)flags, 0.0f, 0.0f);+ }+ return;+ }const int gradient = memcmp(p->inner1, p->inner2, sizeof(float[4])) != 0;const int per_pixel_inner = p->alpha_checker || (gradient && p->shade_horizontal);const Paint p_out = paint_from(p->outline);@@ -886,6 +1102,18 @@ void BUI_raster_image(BuiRaster *r,if (!argb || iw <= 0 || ih <= 0 || !clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {return;}+ if (r->gpu) {+ int ax, ay;+ BuiGpuInst *in = alpha > 0.0f && bui_gpu_image(r->gpu, argb, iw, ih, &ax, &ay) ?+ gpu_inst(r, BG_IMAGE, x0, y0, x1, y1) :+ NULL;+ if (in) {+ v4(in->rect, x, y, w, h);+ v4(in->uv, (float)ax, (float)ay, (float)iw, (float)ih);+ in->p[1] = clampf(alpha, 0.0f, 1.0f);+ }+ return;+ }const int ga = (int)(clampf(alpha, 0.0f, 1.0f) * 256.0f + 0.5f);for (int py = y0; py < y1; py++) {uint32_t *row = r->pix + (size_t)py * r->w;@@ -914,6 +1142,11 @@ void BUI_raster_end_frame_region(BuiRaster *r, int rx, int ry, int rw, int rh)return;}r->damage_len = 0;+ if (r->gpu) {+ bui_gpu_damage(r->gpu, rx, ry, rw, rh);+ damage_push(r, rx, ry, rw, rh);+ return;+ }const int tx0 = clampi(rx, 0, r->w) / TILE_W * TILE_W;const int ty0 = clampi(ry, 0, r->h) / TILE_H * TILE_H;const int tx1 = clampi(rx + rw, 0, r->w), ty1 = clampi(ry + rh, 0, r->h);@@ -962,6 +1195,14 @@ void BUI_raster_shadow(}const float hw = w * 0.5f, hh = h * 0.5f;const float rad = clampf(radius, 0.0f, fminf(hw, hh));+ if (r->gpu) {+ BuiGpuInst *in = gpu_inst(r, BG_SHADOW, x0, y0, x1, y1);+ if (in) {+ v4(in->rect, x, y, w, h);+ v4(in->p, BG_SHADOW, rad, size, alpha);+ }+ return;+ }/* Light comes from above: the shadow sits slightly lower. */const float cx = x + hw, cy = y + hh + size * 0.25f;const Paint black = {0x000000u, 256};@@ -1007,6 +1248,54 @@ void BUI_raster_polygon(BuiRaster *r, const float (*pts)[2], int n, const floatif (!clip_box(r, minx, miny, maxx, maxy, &x0, &y0, &x1, &y1)) {return;}+ if (r->gpu) {+ if (rgba[3] <= 0.0f) {+ return;+ }+ /* Exact software coverage (even-odd, anti-aliased) as a mask: white on+ * black in a scratch raster, green channel = coverage. */+ const int mw = x1 - x0, mh = y1 - y0;+ if (!r->scratch) {+ r->scratch = BUI_raster_create(mw, mh);+ }+ BuiRaster *s = r->scratch;+ if (!s) {+ return;+ }+ BUI_raster_begin_frame(s, mw > s->w ? mw : s->w, mh > s->h ? mh : s->h);+ BUI_raster_set_clip(s, 0, 0, mw, mh);+ for (int yy = 0; yy < mh; yy++) {+ memset(s->pix + (size_t)yy * s->w, 0, (size_t)mw * sizeof(uint32_t));+ }+ float(*tp)[2] = (float(*)[2])malloc(sizeof(float[2]) * (size_t)n);+ uint8_t *mask = (uint8_t *)malloc((size_t)mw * mh);+ if (tp && mask) {+ for (int i = 0; i < n; i++) {+ tp[i][0] = pts[i][0] - (float)x0;+ tp[i][1] = pts[i][1] - (float)y0;+ }+ const float white[4] = {1, 1, 1, 1};+ BUI_raster_polygon(s, (const float(*)[2])tp, n, white);+ for (int yy = 0; yy < mh; yy++) {+ const uint32_t *row = s->pix + (size_t)yy * s->w;+ for (int xx = 0; xx < mw; xx++) {+ mask[(size_t)yy * mw + xx] = (uint8_t)((row[xx] >> 8) & 0xFF);+ }+ }+ int ax, ay;+ BuiGpuInst *in = bui_gpu_mask(r->gpu, NULL, 0, mask, mw, mh, &ax, &ay) ?+ gpu_inst(r, BG_MASK, x0, y0, x1, y1) :+ NULL;+ if (in) {+ v4(in->rect, (float)x0, (float)y0, (float)mw, (float)mh);+ v4(in->uv, (float)ax, (float)ay, 0.0f, 0.0f);+ c4(in->c0, rgba);+ }+ }+ free(tp);+ free(mask);+ return;+ }const Paint p = paint_from(rgba);if (p.a <= 0) {return;@@ -1086,6 +1375,11 @@ void BUI_raster_triangles(BuiRaster *r,const float (*col)[4],int count){+ if (r->gpu) {+ const int clip[4] = {r->cx0, r->cy0, r->cx1, r->cy1};+ bui_gpu_triangles(r->gpu, co, col, count, clip);+ return;+ }for (int i = 0; i + 2 < count; i += 3) {float v[3][2] = {{co[i][0], co[i][1]}, {co[i + 1][0], co[i + 1][1]}, {co[i + 2][0], co[i + 2][1]}};const float *c[3] = {col[i], col[i + 1], col[i + 2]};@@ -1184,6 +1478,13 @@ void BUI_raster_hsv_circle(BuiRaster *r, float cx, float cy, float radius, float{return;}+ if (r->gpu) {+ BuiGpuInst *in = gpu_inst(r, BG_HSV, x0, y0, x1, y1);+ if (in) {+ v4(in->rect, cx, cy, radius, value);+ }+ return;+ }const float inv_2pi = 0.15915494309189535f;for (int py = y0; py < y1; py++) {uint32_t *row = r->pix + (size_t)py * r->w;@@ -1219,6 +1520,17 @@ void BUI_raster_gradient(BuiRaster *r,if (!clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {return;}+ if (r->gpu) {+ BuiGpuInst *in = gpu_inst(r, BG_GRADIENT, x0, y0, x1, y1);+ if (in) {+ v4(in->rect, x, y, w, h);+ c4(in->c0, tl);+ c4(in->c1, tr);+ c4(in->c2, br);+ c4(in->c3, bl);+ }+ return;+ }for (int py = y0; py < y1; py++) {uint32_t *row = r->pix + (size_t)py * r->w;const float v = clampf(((float)py + 0.5f - y) / h, 0.0f, 1.0f);@@ -1266,6 +1578,16 @@ void BUI_raster_sphere(H[1] /= hl;H[2] /= hl;}+ if (r->gpu) {+ BuiGpuInst *in = gpu_inst(r, BG_SPHERE, x0, y0, x1, y1);+ if (in) {+ v4(in->rect, cx, cy, radius, 0.0f);+ c4(in->c0, rgba);+ v4(in->c1, L[0], L[1], L[2], 0.0f);+ v4(in->c2, H[0], H[1], H[2], 0.0f);+ }+ return;+ }for (int py = y0; py < y1; py++) {uint32_t *row = r->pix + (size_t)py * r->w;const float ny = -((float)py + 0.5f - cy) / radius; /* up is +y */@@ -1281,7 +1603,7 @@ void BUI_raster_sphere(float spec = fmaxf(0.0f, nx * H[0] + ny * H[1] + nz * H[2]);spec = spec * spec;spec = spec * spec;- spec = spec * spec * spec * spec; /* ^32 */+ spec = spec * spec * spec * spec; /* ^16 */float c[4];for (int k = 0; k < 3; k++) {c[k] = rgba[k] * (0.12f + 0.88f * diff) + 0.6f * spec;@@ -1307,7 +1629,15 @@ void BUI_raster_set_font(BuiRaster *r, const char *family, int flags)/** \} *//* -------------------------------------------------------------------- */-/** \name Native text + present (Win32 GDI)+/** \name Text: glyph-run cache over a font backend+ *+ * One cache for every platform: a run is a (font slot, UTF-8 string) pair+ * with its advance and, once drawn, an 8-bit coverage mask. Two backends+ * fill slots and masks:+ * - GDI (Windows default): the system's hinted ClearType-free grayscale AA.+ * - Portable (stb_truetype): Linux, macOS, wasm, and Windows when built+ * with BUI_TEXT_STB. Faces come from BUI_text_add_font(), the BUI_FONT /+ * BUI_FONT_DIR environment variables, or the platform's font folders.* \{ */#ifdef _WIN32@@ -1315,20 +1645,33 @@ void BUI_raster_set_font(BuiRaster *r, const char *family, int flags)# define WIN32_LEAN_AND_MEAN# endif# include <windows.h>+#endif++#if defined(_WIN32) && !defined(BUI_TEXT_STB)+# define TEXT_GDI 1+#else+# define TEXT_GDI 0+#endiftypedef struct FontSlot {char family[64];int px;int flags;- HFONT font;int ascent;int height;+#if TEXT_GDI+ HFONT font;+#else+ int face;+ float scale; /* font units -> pixels */+ int synth; /* BUI_FONT_BOLD / ITALIC flags the face lacks */+ float embolden; /* synthetic bold: extra pixels per glyph */+#endif} FontSlot;-# define MAX_FONTS 48+#define MAX_FONTS 48static FontSlot g_fonts[MAX_FONTS];static int g_font_count = 0;-static HDC g_dc = NULL;typedef struct TextRun {uint64_t hash;@@ -1342,12 +1685,19 @@ typedef struct TextRun {uint8_t *mask;} TextRun;-# define RUN_CAP 8192 /* power of two */-# define RUN_MAX_FILL 6000+#define RUN_CAP 8192 /* power of two */+#define RUN_MAX_FILL 6000static TextRun *g_runs = NULL;static int g_run_count = 0;static unsigned g_text_gen = 1; /* bumped whenever runs or fonts are freed */+/* backend */+static int be_font_open(FontSlot *s, const char *family, int flags, int px);+static void be_font_close(FontSlot *s);+static float be_measure(const FontSlot *s, const char *utf8, int len);+static void be_build(TextRun *e, const FontSlot *s);+static void be_flush_glyphs(void);+static void runs_flush(void){g_text_gen++;@@ -1366,26 +1716,17 @@ static void fonts_flush(void){g_text_gen++;for (int i = 0; i < g_font_count; i++) {- DeleteObject(g_fonts[i].font);+ be_font_close(&g_fonts[i]);}g_font_count = 0;+ be_flush_glyphs();runs_flush(); /* runs reference font slots */}-static HDC text_dc(void)-{- if (!g_dc) {- g_dc = CreateCompatibleDC(NULL);- SetBkMode(g_dc, TRANSPARENT);- SetTextAlign(g_dc, TA_LEFT | TA_TOP | TA_NOUPDATECP);- }- return g_dc;-}-static int font_get(const char *family, int flags, float size){if (!family || !family[0] || strcmp(family, "TkDefaultFont") == 0) {- family = "Segoe UI";+ family = "";}int px = (int)(size + 0.5f);if (px < 1) {@@ -1404,31 +1745,14 @@ static int font_get(const char *family, int flags, float size)if (g_font_count == MAX_FONTS) {fonts_flush();}- wchar_t wfam[64];- if (MultiByteToWideChar(CP_UTF8, 0, family, -1, wfam, 64) == 0) {- wcscpy(wfam, L"Segoe UI");- }- HFONT font = CreateFontW(-px, 0, 0, 0, (flags & BUI_FONT_BOLD) ? FW_BOLD : FW_NORMAL,- (flags & BUI_FONT_ITALIC) ? TRUE : FALSE,- (flags & BUI_FONT_UNDERLINE) ? TRUE : FALSE, FALSE, DEFAULT_CHARSET,- OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,- DEFAULT_PITCH | FF_DONTCARE, wfam);- if (!font) {- return -1;- }FontSlot *s = &g_fonts[g_font_count];+ memset(s, 0, sizeof(*s));strncpy(s->family, family, sizeof(s->family) - 1);- s->family[sizeof(s->family) - 1] = '\0';s->px = px;s->flags = flags;- s->font = font;- HDC dc = text_dc();- HGDIOBJ old = SelectObject(dc, font);- TEXTMETRICW tm;- GetTextMetricsW(dc, &tm);- SelectObject(dc, old);- s->ascent = tm.tmAscent;- s->height = tm.tmHeight;+ if (!be_font_open(s, family, flags, px)) {+ return -1;+ }return g_font_count++;}@@ -1442,20 +1766,6 @@ static uint64_t run_hash(int font, const char *s, int len)return h ? h : 1;}-static wchar_t *to_wide(const char *s, int len, int *r_n)-{- int n = MultiByteToWideChar(CP_UTF8, 0, s, len, NULL, 0);- wchar_t *w = (wchar_t *)malloc(sizeof(wchar_t) * (size_t)(n + 1));- if (!w) {- *r_n = 0;- return NULL;- }- MultiByteToWideChar(CP_UTF8, 0, s, len, w, n);- w[n] = 0;- *r_n = n;- return w;-}-static TextRun *run_get(int font, const char *s, int len){if (!g_runs) {@@ -1491,75 +1801,14 @@ static TextRun *run_get(int font, const char *s, int len)e->font = font;e->len = len;g_run_count++;-- int wn;- wchar_t *w = to_wide(s, len, &wn);- HDC dc = text_dc();- HGDIOBJ old = SelectObject(dc, g_fonts[font].font);- SIZE sz = {0, 0};- if (w && wn > 0) {- GetTextExtentPoint32W(dc, w, wn, &sz);- }- SelectObject(dc, old);- free(w);- e->advance = (float)sz.cx;+ e->advance = be_measure(&g_fonts[font], s, len);return e;}-static void run_build(TextRun *e)-{- e->built = 1;- const FontSlot *fs = &g_fonts[e->font];- int wn;- wchar_t *w = to_wide(e->text, e->len, &wn);- if (!w || wn == 0 || e->advance <= 0.0f) {- free(w);- return;- }- const int pad = 2 + fs->px / 4; /* bearings / italic overhang */- const int mw = (int)e->advance + pad * 2;- const int mh = fs->height + 1;- BITMAPINFO bmi;- memset(&bmi, 0, sizeof(bmi));- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);- bmi.bmiHeader.biWidth = mw;- bmi.bmiHeader.biHeight = -mh;- bmi.bmiHeader.biPlanes = 1;- bmi.bmiHeader.biBitCount = 32;- bmi.bmiHeader.biCompression = BI_RGB;- void *bits = NULL;- HDC dc = text_dc();- HBITMAP bmp = CreateDIBSection(dc, &bmi, DIB_RGB_COLORS, &bits, NULL, 0);- if (!bmp || !bits) {- free(w);- return;- }- memset(bits, 0, (size_t)mw * mh * 4);- HGDIOBJ old_bmp = SelectObject(dc, bmp);- HGDIOBJ old_font = SelectObject(dc, fs->font);- SetTextColor(dc, RGB(255, 255, 255));- TextOutW(dc, pad, 0, w, wn);- GdiFlush();- e->mask = (uint8_t *)malloc((size_t)mw * mh);- if (e->mask) {- const uint32_t *src = (const uint32_t *)bits;- for (int i = 0; i < mw * mh; i++) {- /* grayscale AA: channels match; take green (perceptual) */- e->mask[i] = (uint8_t)((src[i] >> 8) & 0xFF);- }- e->mw = mw;- e->mh = mh;- e->ox = pad;- }- SelectObject(dc, old_font);- SelectObject(dc, old_bmp);- DeleteObject(bmp);- free(w);-}-int BUI_text_native(void){- return 1;+ /* the portable engine reports 1 once a face can be found */+ return font_get("", 0, 12.0f) >= 0;}int BUI_text_measure(@@ -1607,7 +1856,10 @@ const BuiTextRun *BUI_text_prepare(*r_width = e->advance;}if (!e->built) {- run_build(e);+ e->built = 1;+ if (e->advance > 0.0f) {+ be_build(e, &g_fonts[e->font]);+ }}return e->mask ? (const BuiTextRun *)e : NULL; /* NULL: whitespace-only */}@@ -1644,6 +1896,19 @@ void BUI_raster_text_run(BuiRaster *r, float x, float y, const BuiTextRun *run,const int dy = (int)floorf(y + 0.5f) - g_fonts[e->font].ascent;const int x0 = clampi(dx, r->cx0, r->cx1), x1 = clampi(dx + e->mw, r->cx0, r->cx1);const int y0 = clampi(dy, r->cy0, r->cy1), y1 = clampi(dy + e->mh, r->cy0, r->cy1);+ if (r->gpu) {+ int ax, ay;+ BuiGpuInst *in = x1 > x0 && y1 > y0 &&+ bui_gpu_mask(r->gpu, e, g_text_gen, e->mask, e->mw, e->mh, &ax, &ay) ?+ gpu_inst(r, BG_MASK, x0, y0, x1, y1) :+ NULL;+ if (in) {+ v4(in->rect, (float)dx, (float)dy, (float)e->mw, (float)e->mh);+ v4(in->uv, (float)ax, (float)ay, 0.0f, 0.0f);+ c4(in->c0, rgba);+ }+ return;+ }for (int py = y0; py < y1; py++) {uint32_t *row = r->pix + (size_t)py * r->w;const uint8_t *m = e->mask + (size_t)(py - dy) * e->mw - dx;@@ -1663,29 +1928,833 @@ void BUI_raster_text_run(BuiRaster *r, float x, float y, const BuiTextRun *run,}}-int BUI_raster_present_native(BuiRaster *r, void *window_handle, int full)+/* Text runs for GPU renderers: mask size, left padding and ascent. */+const uint8_t *BUI_text_run_mask(const BuiTextRun *run, int *r_w, int *r_h, int *r_ox, int *r_ascent){- HWND hwnd = (HWND)window_handle;- if (!hwnd || !IsWindow(hwnd)) {- return 0;- }- HDC hdc = GetDC(hwnd);- if (!hdc) {- return 0;+ const TextRun *e = (const TextRun *)run;+ if (!e || !e->mask) {+ return NULL;}- BITMAPINFO bmi;- memset(&bmi, 0, sizeof(bmi));- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);- bmi.bmiHeader.biWidth = r->w;- bmi.bmiHeader.biPlanes = 1;- bmi.bmiHeader.biBitCount = 32;- bmi.bmiHeader.biCompression = BI_RGB;+ *r_w = e->mw;+ *r_h = e->mh;+ *r_ox = e->ox;+ *r_ascent = g_fonts[e->font].ascent;+ return e->mask;+}- int whole[1][4] = {{0, 0, r->w, r->h}};- const int(*rects)[4] = full ? (const int(*)[4])whole : (const int(*)[4])r->damage;- const int n = full ? 1 : r->damage_len;- /* Each rect is copied into its own tight top-down DIB and blitted whole- * (src origin 0,0, all scanlines). Sub-rect source offsets into a+/** \} */++#if TEXT_GDI+/* -------------------------------------------------------------------- */+/** \name Text backend: GDI+ * \{ */++static HDC g_dc = NULL;++static HDC text_dc(void)+{+ if (!g_dc) {+ g_dc = CreateCompatibleDC(NULL);+ SetBkMode(g_dc, TRANSPARENT);+ SetTextAlign(g_dc, TA_LEFT | TA_TOP | TA_NOUPDATECP);+ }+ return g_dc;+}++static int be_font_open(FontSlot *s, const char *family, int flags, int px)+{+ if (!family[0]) {+ family = "Segoe UI";+ }+ wchar_t wfam[64];+ if (MultiByteToWideChar(CP_UTF8, 0, family, -1, wfam, 64) == 0) {+ wcscpy(wfam, L"Segoe UI");+ }+ HFONT font = CreateFontW(-px, 0, 0, 0, (flags & BUI_FONT_BOLD) ? FW_BOLD : FW_NORMAL,+ (flags & BUI_FONT_ITALIC) ? TRUE : FALSE,+ (flags & BUI_FONT_UNDERLINE) ? TRUE : FALSE, FALSE, DEFAULT_CHARSET,+ OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,+ DEFAULT_PITCH | FF_DONTCARE, wfam);+ if (!font) {+ return 0;+ }+ s->font = font;+ HDC dc = text_dc();+ HGDIOBJ old = SelectObject(dc, font);+ TEXTMETRICW tm;+ GetTextMetricsW(dc, &tm);+ SelectObject(dc, old);+ s->ascent = tm.tmAscent;+ s->height = tm.tmHeight;+ return 1;+}++static void be_font_close(FontSlot *s)+{+ DeleteObject(s->font);+}++static void be_flush_glyphs(void) {}++static wchar_t *to_wide(const char *s, int len, int *r_n)+{+ int n = MultiByteToWideChar(CP_UTF8, 0, s, len, NULL, 0);+ wchar_t *w = (wchar_t *)malloc(sizeof(wchar_t) * (size_t)(n + 1));+ if (!w) {+ *r_n = 0;+ return NULL;+ }+ MultiByteToWideChar(CP_UTF8, 0, s, len, w, n);+ w[n] = 0;+ *r_n = n;+ return w;+}++static float be_measure(const FontSlot *s, const char *utf8, int len)+{+ int wn;+ wchar_t *w = to_wide(utf8, len, &wn);+ HDC dc = text_dc();+ HGDIOBJ old = SelectObject(dc, s->font);+ SIZE sz = {0, 0};+ if (w && wn > 0) {+ GetTextExtentPoint32W(dc, w, wn, &sz);+ }+ SelectObject(dc, old);+ free(w);+ return (float)sz.cx;+}++static void be_build(TextRun *e, const FontSlot *fs)+{+ int wn;+ wchar_t *w = to_wide(e->text, e->len, &wn);+ if (!w || wn == 0) {+ free(w);+ return;+ }+ const int pad = 2 + fs->px / 4; /* bearings / italic overhang */+ const int mw = (int)e->advance + pad * 2;+ const int mh = fs->height + 1;+ BITMAPINFO bmi;+ memset(&bmi, 0, sizeof(bmi));+ bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);+ bmi.bmiHeader.biWidth = mw;+ bmi.bmiHeader.biHeight = -mh;+ bmi.bmiHeader.biPlanes = 1;+ bmi.bmiHeader.biBitCount = 32;+ bmi.bmiHeader.biCompression = BI_RGB;+ void *bits = NULL;+ HDC dc = text_dc();+ HBITMAP bmp = CreateDIBSection(dc, &bmi, DIB_RGB_COLORS, &bits, NULL, 0);+ if (!bmp || !bits) {+ free(w);+ return;+ }+ memset(bits, 0, (size_t)mw * mh * 4);+ HGDIOBJ old_bmp = SelectObject(dc, bmp);+ HGDIOBJ old_font = SelectObject(dc, fs->font);+ SetTextColor(dc, RGB(255, 255, 255));+ TextOutW(dc, pad, 0, w, wn);+ GdiFlush();+ e->mask = (uint8_t *)malloc((size_t)mw * mh);+ if (e->mask) {+ const uint32_t *src = (const uint32_t *)bits;+ for (int i = 0; i < mw * mh; i++) {+ /* grayscale AA: channels match; take green (perceptual) */+ e->mask[i] = (uint8_t)((src[i] >> 8) & 0xFF);+ }+ e->mw = mw;+ e->mh = mh;+ e->ox = pad;+ }+ SelectObject(dc, old_font);+ SelectObject(dc, old_bmp);+ DeleteObject(bmp);+ free(w);+}++int BUI_text_add_font(const char *family, int flags, const void *data, int len)+{+ (void)flags;+ /* private to this process; addressable by the font's own family name */+ DWORD n = 0;+ HANDLE h = AddFontMemResourceEx((void *)data, (DWORD)len, NULL, &n);+ (void)family;+ if (h && n > 0) {+ fonts_flush();+ return 1;+ }+ return 0;+}++/** \} */++#else /* portable */+/* -------------------------------------------------------------------- */+/** \name Text backend: stb_truetype+ * \{ */++# if defined(__GNUC__) || defined(__clang__)+# pragma GCC diagnostic push+# pragma GCC diagnostic ignored "-Wunused-function"+# pragma GCC diagnostic ignored "-Wsign-compare"+# pragma GCC diagnostic ignored "-Wconversion"+# pragma GCC diagnostic ignored "-Wshadow"+# pragma GCC diagnostic ignored "-Wcast-qual"+# endif+# define STBTT_STATIC+# define STB_TRUETYPE_IMPLEMENTATION+# include "../extern/stb_truetype.h"+# if defined(__GNUC__) || defined(__clang__)+# pragma GCC diagnostic pop+# endif+# include <stdio.h>++typedef struct Face {+ char key[96]; /* file path, or "mem:<family>" */+ unsigned char *data;+ stbtt_fontinfo info;+ int ascent, descent, line_gap; /* font units */+} Face;++# define MAX_FACES 32+static Face g_faces[MAX_FACES];+static int g_face_count = 0;++/* registered (in-memory) fonts: family + style -> face */+typedef struct FaceReg {+ char family[64];+ int style; /* BUI_FONT_BOLD | BUI_FONT_ITALIC */+ int face;+} FaceReg;+static FaceReg g_regs[MAX_FACES];+static int g_reg_count = 0;++static int ieq(const char *a, const char *b)+{+ for (; *a && *b; a++, b++) {+ int ca = (unsigned char)*a, cb = (unsigned char)*b;+ if (ca >= 'A' && ca <= 'Z') {+ ca += 32;+ }+ if (cb >= 'A' && cb <= 'Z') {+ cb += 32;+ }+ if (ca != cb) {+ return 0;+ }+ }+ return *a == *b;+}++static int face_init(Face *f, unsigned char *data)+{+ const int off = stbtt_GetFontOffsetForIndex(data, 0);+ if (off < 0 || !stbtt_InitFont(&f->info, data, off)) {+ return 0;+ }+ f->data = data;+ /* GDI's metrics: the OS/2 table's Windows ascent/descent when present */+ int a, d, g;+ if (stbtt_GetFontVMetricsOS2(&f->info, &a, &d, &g)) {+ int wa = 0, wd = 0;+ const stbtt_uint32 os2 = stbtt__find_table(f->info.data, (stbtt_uint32)f->info.fontstart, "OS/2");+ if (os2) {+ wa = ttUSHORT(f->info.data + os2 + 74);+ wd = ttUSHORT(f->info.data + os2 + 76);+ }+ if (wa > 0 || wd > 0) {+ a = wa;+ d = -wd;+ }+ }+ else {+ stbtt_GetFontVMetrics(&f->info, &a, &d, &g);+ }+ f->ascent = a;+ f->descent = d;+ f->line_gap = g;+ return 1;+}++static int face_load_file(const char *path)+{+ for (int i = 0; i < g_face_count; i++) {+ if (strcmp(g_faces[i].key, path) == 0) {+ return i;+ }+ }+ if (g_face_count == MAX_FACES || strlen(path) >= sizeof(g_faces[0].key)) {+ return -1;+ }+ FILE *fp = fopen(path, "rb");+ if (!fp) {+ return -1;+ }+ fseek(fp, 0, SEEK_END);+ const long n = ftell(fp);+ fseek(fp, 0, SEEK_SET);+ unsigned char *data = n > 0 ? (unsigned char *)malloc((size_t)n) : NULL;+ if (!data || fread(data, 1, (size_t)n, fp) != (size_t)n) {+ free(data);+ fclose(fp);+ return -1;+ }+ fclose(fp);+ Face *f = &g_faces[g_face_count];+ memset(f, 0, sizeof(*f));+ if (!face_init(f, data)) {+ free(data);+ return -1;+ }+ strcpy(f->key, path);+ return g_face_count++;+}++int BUI_text_add_font(const char *family, int flags, const void *data, int len)+{+ if (!data || len <= 0 || g_face_count == MAX_FACES || g_reg_count == MAX_FACES) {+ return 0;+ }+ unsigned char *copy = (unsigned char *)malloc((size_t)len);+ if (!copy) {+ return 0;+ }+ memcpy(copy, data, (size_t)len);+ Face *f = &g_faces[g_face_count];+ memset(f, 0, sizeof(*f));+ if (!face_init(f, copy)) {+ free(copy);+ return 0;+ }+ snprintf(f->key, sizeof(f->key), "mem:%s", family ? family : "");+ FaceReg *r = &g_regs[g_reg_count++];+ strncpy(r->family, family ? family : "", sizeof(r->family) - 1);+ r->family[sizeof(r->family) - 1] = '\0';+ r->style = flags & (BUI_FONT_BOLD | BUI_FONT_ITALIC);+ r->face = g_face_count++;+ fonts_flush(); /* the new face may replace a fallback */+ return 1;+}++/* Font folders, most specific first. */+static int font_dirs(char dirs[][260], int max)+{+ int n = 0;+ const char *env = getenv("BUI_FONT_DIR");+ if (env && env[0] && n < max) {+ snprintf(dirs[n++], 260, "%s", env);+ }+# ifdef _WIN32+ const char *win = getenv("WINDIR");+ snprintf(dirs[n++], 260, "%s/Fonts", win ? win : "C:/Windows");+ const char *local = getenv("LOCALAPPDATA");+ if (local && n < max) {+ snprintf(dirs[n++], 260, "%s/Microsoft/Windows/Fonts", local);+ }+# elif defined(__APPLE__)+ static const char *mac[] = {"/System/Library/Fonts", "/System/Library/Fonts/Supplemental",+ "/Library/Fonts"};+ for (int i = 0; i < 3 && n < max; i++) {+ snprintf(dirs[n++], 260, "%s", mac[i]);+ }+ const char *home = getenv("HOME");+ if (home && n < max) {+ snprintf(dirs[n++], 260, "%s/Library/Fonts", home);+ }+# else+ static const char *nix[] = {+ "/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/dejavu",+ "/usr/share/fonts/TTF", "/usr/share/fonts/truetype/liberation",+ "/usr/share/fonts/liberation", "/usr/share/fonts/truetype/noto",+ "/usr/share/fonts/noto", "/usr/share/fonts/google-noto",+ "/usr/share/fonts/truetype", "/usr/local/share/fonts",+ "/usr/share/fonts"};+ for (int i = 0; i < (int)(sizeof(nix) / sizeof(nix[0])) && n < max; i++) {+ snprintf(dirs[n++], 260, "%s", nix[i]);+ }+ const char *home = getenv("HOME");+ if (home && n + 1 < max) {+ snprintf(dirs[n++], 260, "%s/.local/share/fonts", home);+ snprintf(dirs[n++], 260, "%s/.fonts", home);+ }+# endif+ return n;+}++/* File names per generic family and style (regular, bold, italic, both). */+typedef struct FamilyFiles {+ const char *names; /* '|'-separated aliases */+ const char *files[4];+} FamilyFiles;++static const FamilyFiles g_families[] = {+ {"|sans|sans-serif|segoe ui|system-ui|helvetica|arial|dejavu sans|liberation sans|noto "+ "sans|tkdefaultfont|tktextfont|tkheadingfont|tkcaptionfont|tkmenufont|",+ {"segoeui.ttf|DejaVuSans.ttf|LiberationSans-Regular.ttf|NotoSans-Regular.ttf|Arial.ttf|"+ "arial.ttf|Helvetica.ttc|SFNS.ttf",+ "segoeuib.ttf|DejaVuSans-Bold.ttf|LiberationSans-Bold.ttf|NotoSans-Bold.ttf|Arial "+ "Bold.ttf|arialbd.ttf",+ "segoeuii.ttf|DejaVuSans-Oblique.ttf|LiberationSans-Italic.ttf|NotoSans-Italic.ttf|Arial "+ "Italic.ttf|ariali.ttf",+ "segoeuiz.ttf|DejaVuSans-BoldOblique.ttf|LiberationSans-BoldItalic.ttf|NotoSans-"+ "BoldItalic.ttf|Arial Bold Italic.ttf|arialbi.ttf"}},+ {"|mono|monospace|courier|courier new|consolas|menlo|dejavu sans mono|liberation "+ "mono|tkfixedfont|",+ {"consola.ttf|DejaVuSansMono.ttf|LiberationMono-Regular.ttf|NotoSansMono-Regular.ttf|"+ "Menlo.ttc|cour.ttf",+ "consolab.ttf|DejaVuSansMono-Bold.ttf|LiberationMono-Bold.ttf|NotoSansMono-Bold.ttf|"+ "courbd.ttf",+ "consolai.ttf|DejaVuSansMono-Oblique.ttf|LiberationMono-Italic.ttf|couri.ttf",+ "consolaz.ttf|DejaVuSansMono-BoldOblique.ttf|LiberationMono-BoldItalic.ttf|courbi.ttf"}},+ {"|serif|times|times new roman|georgia|dejavu serif|liberation serif|",+ {"times.ttf|DejaVuSerif.ttf|LiberationSerif-Regular.ttf|NotoSerif-Regular.ttf|Times New "+ "Roman.ttf|Times.ttc",+ "timesbd.ttf|DejaVuSerif-Bold.ttf|LiberationSerif-Bold.ttf|NotoSerif-Bold.ttf|Times New "+ "Roman Bold.ttf",+ "timesi.ttf|DejaVuSerif-Italic.ttf|LiberationSerif-Italic.ttf|NotoSerif-Italic.ttf|Times "+ "New Roman Italic.ttf",+ "timesbi.ttf|DejaVuSerif-BoldItalic.ttf|LiberationSerif-BoldItalic.ttf|NotoSerif-"+ "BoldItalic.ttf|Times New Roman Bold Italic.ttf"}},+};++static int family_index(const char *family)+{+ if (!family[0]) {+ return 0;+ }+ char probe[72];+ snprintf(probe, sizeof(probe), "|%s|", family);+ for (int i = 0; probe[i]; i++) {+ if (probe[i] >= 'A' && probe[i] <= 'Z') {+ probe[i] = (char)(probe[i] + 32);+ }+ }+ for (int i = 0; i < (int)(sizeof(g_families) / sizeof(g_families[0])); i++) {+ if (strstr(g_families[i].names, probe)) {+ return i;+ }+ }+ return -1;+}++/* First '|'-separated file found in any font folder. */+static int face_from_files(const char *files, char dirs[][260], int ndirs)+{+ const char *p = files;+ while (*p) {+ const char *end = strchr(p, '|');+ const int n = end ? (int)(end - p) : (int)strlen(p);+ for (int d = 0; d < ndirs; d++) {+ char path[600];+ snprintf(path, sizeof(path), "%s/%.*s", dirs[d], n, p);+ const int f = face_load_file(path);+ if (f >= 0) {+ return f;+ }+ }+ p += n + (end ? 1 : 0);+ }+ return -1;+}++/* The face for family + style; *r_have gets the style bits it really has. */+static int face_find(const char *family, int style, int *r_have)+{+ /* 1. registered fonts: exact style, then any style of the family */+ for (int pass = 0; pass < 2; pass++) {+ for (int i = 0; i < g_reg_count; i++) {+ if ((ieq(g_regs[i].family, family) || (!family[0] && i == 0)) &&+ (pass == 1 || g_regs[i].style == style))+ {+ *r_have = g_regs[i].style;+ return g_regs[i].face;+ }+ }+ }+ /* 2. an explicit file */+ const size_t fl = strlen(family);+ if (fl > 4 && (ieq(family + fl - 4, ".ttf") || ieq(family + fl - 4, ".otf") ||+ ieq(family + fl - 4, ".ttc")))+ {+ const int f = face_load_file(family);+ if (f >= 0) {+ *r_have = 0;+ return f;+ }+ }+ char dirs[16][260];+ const int nd = font_dirs(dirs, 16);+ /* 3. BUI_FONT overrides the default face */+ const char *env = (!family[0] || family_index(family) == 0) ? getenv("BUI_FONT") : NULL;+ if (env && env[0]) {+ const int f = face_load_file(env);+ if (f >= 0) {+ *r_have = 0;+ return f;+ }+ }+ /* 4. a known generic family, then "<family>.ttf", then the default */+ int fam = family_index(family);+ if (fam < 0) {+ char files[200];+ char squashed[64];+ int k = 0;+ for (const char *c = family; *c && k < 63; c++) {+ if (*c != ' ') {+ squashed[k++] = *c;+ }+ }+ squashed[k] = 0;+ snprintf(files, sizeof(files), "%s.ttf|%s.ttf|%s.otf|%s-Regular.ttf", family, squashed,+ family, squashed);+ const int f = face_from_files(files, dirs, nd);+ if (f >= 0) {+ *r_have = 0;+ return f;+ }+ fam = 0;+ }+ const int want = (style & BUI_FONT_BOLD ? 1 : 0) | (style & BUI_FONT_ITALIC ? 2 : 0);+ int f = face_from_files(g_families[fam].files[want], dirs, nd);+ if (f >= 0) {+ *r_have = style;+ return f;+ }+ if (want) { /* synthesize the style from the regular face */+ f = face_from_files(g_families[fam].files[0], dirs, nd);+ if (f >= 0) {+ *r_have = 0;+ return f;+ }+ }+ if (fam != 0) {+ return face_find("", style, r_have);+ }+ if (g_reg_count > 0) {+ *r_have = g_regs[0].style;+ return g_regs[0].face;+ }+ return -1;+}++static int be_font_open(FontSlot *s, const char *family, int flags, int px)+{+ const int style = flags & (BUI_FONT_BOLD | BUI_FONT_ITALIC);+ int have = 0;+ const int face = face_find(family, style, &have);+ if (face < 0) {+ return 0;+ }+ const Face *f = &g_faces[face];+ s->face = face;+ s->scale = stbtt_ScaleForMappingEmToPixels(&f->info, (float)px); /* GDI: -px = em height */+ s->ascent = (int)ceilf((float)f->ascent * s->scale - 0.01f);+ s->height = s->ascent + (int)ceilf((float)-f->descent * s->scale - 0.01f);+ s->synth = style & ~have;+ s->embolden = (s->synth & BUI_FONT_BOLD) ? (px < 24 ? 1.0f : (float)px / 24.0f) : 0.0f;+ return 1;+}++static void be_font_close(FontSlot *s)+{+ (void)s;+}++/* UTF-8 decode; invalid bytes map to U+FFFD. */+static int utf8_next(const char *s, int len, int *i)+{+ const unsigned char c = (unsigned char)s[*i];+ int cp, n;+ if (c < 0x80) {+ cp = c;+ n = 1;+ }+ else if ((c & 0xE0) == 0xC0) {+ cp = c & 0x1F;+ n = 2;+ }+ else if ((c & 0xF0) == 0xE0) {+ cp = c & 0x0F;+ n = 3;+ }+ else if ((c & 0xF8) == 0xF0) {+ cp = c & 0x07;+ n = 4;+ }+ else {+ (*i)++;+ return 0xFFFD;+ }+ if (*i + n > len) {+ *i = len;+ return 0xFFFD;+ }+ for (int k = 1; k < n; k++) {+ const unsigned char cc = (unsigned char)s[*i + k];+ if ((cc & 0xC0) != 0x80) {+ *i += k;+ return 0xFFFD;+ }+ cp = (cp << 6) | (cc & 0x3F);+ }+ *i += n;+ return cp;+}++/* Glyph bitmaps by (slot, glyph, quarter-pixel phase). Rasterized once,+ * composited into every run that uses them. */+typedef struct GlyphBmp {+ uint32_t key; /* 0 = empty */+ int16_t w, h, xoff, yoff;+ uint8_t *bits;+} GlyphBmp;++# define GLYPH_CAP 4096 /* power of two */+# define GLYPH_MAX_FILL 3000+static GlyphBmp *g_glyphs = NULL;+static int g_glyph_count = 0;++static void be_flush_glyphs(void)+{+ if (!g_glyphs) {+ return;+ }+ for (int i = 0; i < GLYPH_CAP; i++) {+ free(g_glyphs[i].bits);+ }+ memset(g_glyphs, 0, sizeof(GlyphBmp) * GLYPH_CAP);+ g_glyph_count = 0;+}++static const GlyphBmp *glyph_get(int slot, const FontSlot *s, int glyph, int phase)+{+ if (!g_glyphs) {+ g_glyphs = (GlyphBmp *)calloc(GLYPH_CAP, sizeof(GlyphBmp));+ if (!g_glyphs) {+ return NULL;+ }+ }+ const uint32_t key = (((uint32_t)slot + 1) << 24) ^ ((uint32_t)glyph << 2) ^ (uint32_t)phase;+ uint32_t idx = (key * 2654435761u) >> 20 & (GLYPH_CAP - 1);+ for (;;) {+ GlyphBmp *g = &g_glyphs[idx];+ if (g->key == 0) {+ break;+ }+ if (g->key == key) {+ return g;+ }+ idx = (idx + 1) & (GLYPH_CAP - 1);+ }+ if (g_glyph_count >= GLYPH_MAX_FILL) {+ be_flush_glyphs();+ return glyph_get(slot, s, glyph, phase);+ }+ GlyphBmp *g = &g_glyphs[idx];+ const stbtt_fontinfo *info = &g_faces[s->face].info;+ int w = 0, h = 0, xo = 0, yo = 0;+ g->bits = stbtt_GetGlyphBitmapSubpixel(+ info, s->scale, s->scale, (float)phase * 0.25f, 0.0f, glyph, &w, &h, &xo, &yo);+ if (g->bits) {+ /* stb's coverage is linear; blending it in sRGB thins strokes. Lift it+ * (gamma 1/1.45, close to how GDI's grayscale AA reads). */+ static uint8_t lut[256];+ if (!lut[255]) {+ for (int i = 0; i < 256; i++) {+ lut[i] = (uint8_t)(255.0f * powf((float)i / 255.0f, 1.0f / 1.45f) + 0.5f);+ }+ }+ for (int i = 0; i < w * h; i++) {+ g->bits[i] = lut[g->bits[i]];+ }+ }+ g->key = key;+ g->w = (int16_t)w;+ g->h = (int16_t)h;+ g->xoff = (int16_t)xo;+ g->yoff = (int16_t)yo;+ g_glyph_count++;+ return g;+}++/* Walks the glyphs of a run: pen positions in pixels (unrounded). */+typedef void (*GlyphFn)(void *user, int glyph, float pen);++static float glyph_walk(const FontSlot *s, const char *utf8, int len, GlyphFn fn, void *user)+{+ const stbtt_fontinfo *info = &g_faces[s->face].info;+ float pen = 0.0f;+ int prev = 0;+ for (int i = 0; i < len;) {+ int cp = utf8_next(utf8, len, &i);+ if (cp == '\t') {+ cp = ' ';+ }+ const int glyph = stbtt_FindGlyphIndex(info, cp);+ if (prev) {+ pen += s->scale * (float)stbtt_GetGlyphKernAdvance(info, prev, glyph);+ }+ if (fn) {+ fn(user, glyph, pen);+ }+ int adv, lsb;+ stbtt_GetGlyphHMetrics(info, glyph, &adv, &lsb);+ pen += s->scale * (float)adv + s->embolden;+ prev = glyph;+ }+ return pen;+}++static float be_measure(const FontSlot *s, const char *utf8, int len)+{+ return floorf(glyph_walk(s, utf8, len, NULL, NULL) + 0.5f);+}++typedef struct BuildCtx {+ const FontSlot *s;+ int slot;+ uint8_t *mask;+ int mw, mh, ox, ascent;+ float shear; /* synthetic italic: pixels per pixel above the baseline */+} BuildCtx;++static void build_glyph(void *user, int glyph, float pen)+{+ BuildCtx *c = (BuildCtx *)user;+ const float px = floorf(pen * 4.0f + 0.5f) * 0.25f;+ const int whole = (int)floorf(px);+ const int phase = (int)((px - (float)whole) * 4.0f) & 3;+ const GlyphBmp *g = glyph_get(c->slot, c->s, glyph, phase);+ if (!g || !g->bits) {+ return;+ }+ const int gx = c->ox + whole + g->xoff;+ const int gy = c->ascent + g->yoff;+ for (int y = 0; y < g->h; y++) {+ const int my = gy + y;+ if (my < 0 || my >= c->mh) {+ continue;+ }+ uint8_t *row = c->mask + (size_t)my * c->mw;+ const uint8_t *src = g->bits + (size_t)y * g->w;+ if (c->shear == 0.0f) {+ for (int x = 0; x < g->w; x++) {+ const int mx = gx + x;+ if (mx >= 0 && mx < c->mw && src[x]) {+ const int v = row[mx] + src[x];+ row[mx] = (uint8_t)(v > 255 ? 255 : v);+ }+ }+ }+ else {+ /* shear about the baseline, splitting coverage between two pixels */+ const float sh = (float)(c->ascent - my) * c->shear;+ const int si = (int)floorf(sh);+ const int fr = (int)((sh - (float)si) * 256.0f);+ for (int x = 0; x < g->w; x++) {+ if (!src[x]) {+ continue;+ }+ const int mx = gx + x + si;+ const int hi = (src[x] * fr) >> 8, lo = src[x] - hi;+ if (mx >= 0 && mx < c->mw) {+ const int v = row[mx] + lo;+ row[mx] = (uint8_t)(v > 255 ? 255 : v);+ }+ if (mx + 1 >= 0 && mx + 1 < c->mw) {+ const int v = row[mx + 1] + hi;+ row[mx + 1] = (uint8_t)(v > 255 ? 255 : v);+ }+ }+ }+ }+}++static void be_build(TextRun *e, const FontSlot *fs)+{+ const int pad = 2 + fs->px / 4; /* bearings / italic overhang */+ const int mw = (int)e->advance + pad * 2;+ const int mh = fs->height + 1;+ uint8_t *mask = (uint8_t *)calloc((size_t)mw * mh, 1);+ if (!mask) {+ return;+ }+ BuildCtx c = {fs, (int)(fs - g_fonts), mask, mw, mh, pad, fs->ascent,+ (fs->synth & BUI_FONT_ITALIC) ? 0.2f : 0.0f};+ glyph_walk(fs, e->text, e->len, build_glyph, &c);+ if (fs->embolden > 0.0f) { /* synthetic bold: smear right */+ const int k = (int)(fs->embolden + 0.5f);+ for (int y = 0; y < mh; y++) {+ uint8_t *row = mask + (size_t)y * mw;+ for (int x = mw - 1; x >= k; x--) {+ int v = row[x];+ for (int j = 1; j <= k; j++) {+ v = row[x - j] > v ? row[x - j] : v;+ }+ row[x] = (uint8_t)v;+ }+ }+ }+ if (fs->flags & BUI_FONT_UNDERLINE) {+ const int t = fs->px / 14 > 1 ? fs->px / 14 : 1;+ const int y0 = fs->ascent + (fs->height - fs->ascent) / 2;+ for (int y = y0; y < y0 + t && y < mh; y++) {+ memset(mask + (size_t)y * mw + pad, 255, (size_t)e->advance);+ }+ }+ int any = 0;+ for (int i = 0; i < mw * mh && !any; i++) {+ any = mask[i] != 0;+ }+ if (!any) {+ free(mask);+ return;+ }+ e->mask = mask;+ e->mw = mw;+ e->mh = mh;+ e->ox = pad;+}++/** \} */+#endif /* text backends */++/* -------------------------------------------------------------------- */+/** \name Native present+ * \{ */++#ifdef _WIN32+int BUI_raster_present_native(BuiRaster *r, void *window_handle, int full)+{+ if (r->gpu) {+ if (!bui_gpu_present(r->gpu, full)) {+ gpu_drop(r); /* device lost: the software raster takes over */+ }+ return 1;+ }+ HWND hwnd = (HWND)window_handle;+ if (!hwnd || !IsWindow(hwnd)) {+ return 0;+ }+ HDC hdc = GetDC(hwnd);+ if (!hdc) {+ return 0;+ }+ BITMAPINFO bmi;+ memset(&bmi, 0, sizeof(bmi));+ bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);+ bmi.bmiHeader.biWidth = r->w;+ bmi.bmiHeader.biPlanes = 1;+ bmi.bmiHeader.biBitCount = 32;+ bmi.bmiHeader.biCompression = BI_RGB;++ int whole[1][4] = {{0, 0, r->w, r->h}};+ const int(*rects)[4] = full ? (const int(*)[4])whole : (const int(*)[4])r->damage;+ const int n = full ? 1 : r->damage_len;+ /* Each rect is copied into its own tight top-down DIB and blitted whole+ * (src origin 0,0, all scanlines). Sub-rect source offsets into a* top-down DIB are interpreted inconsistently by GDI, which left partial* updates on screen stale. */uint32_t *tmp = NULL;@@ -1725,80 +2794,19 @@ int BUI_raster_present_native(BuiRaster *r, void *window_handle, int full)ReleaseDC(hwnd, hdc);return 1;}--#else /* !_WIN32 */--int BUI_text_native(void)-{- return 0;-}--int BUI_text_measure(- const char *family, int flags, float size, const char *utf8, int len, float *r_width)-{- (void)family;- (void)flags;- (void)size;- (void)utf8;- (void)len;- *r_width = 0.0f;- return 0;-}--int BUI_raster_text(BuiRaster *r,- float x,- float y,- const char *utf8,- int len,- float size,- const float rgba[4])-{- (void)r;- (void)x;- (void)y;- (void)utf8;- (void)len;- (void)size;- (void)rgba;- return 0;-}-+#elseint BUI_raster_present_native(BuiRaster *r, void *window_handle, int full){- (void)r;+ if (r->gpu) {+ if (!bui_gpu_present(r->gpu, full)) {+ gpu_drop(r);+ }+ return 1;+ }(void)window_handle;(void)full;return 0;}--unsigned BUI_text_generation(void)-{- return 1;-}--const BuiTextRun *BUI_text_prepare(- const char *family, int flags, float size, const char *utf8, int len, float *r_width)-{- (void)family;- (void)flags;- (void)size;- (void)utf8;- (void)len;- if (r_width) {- *r_width = 0.0f;- }- return NULL;-}--void BUI_raster_text_run(BuiRaster *r, float x, float y, const BuiTextRun *run, const float rgba[4])-{- (void)r;- (void)x;- (void)y;- (void)run;- (void)rgba;-}-#endif/** \} */diff --git a/gpu/shaders/bui_ui.hlsl b/gpu/shaders/bui_ui.hlslnew file mode 100644index 0000000..d18fc19--- /dev/null+++ b/gpu/shaders/bui_ui.hlsl@@ -0,0 +1,269 @@+// BUI GPU renderer shaders (Direct3D 11, shader model 4.0).+//+// One instanced quad per primitive, like Blender's GPU_SHADER_2D_WIDGET_BASE_INST+// batches (interface_widgets.cc): the CPU appends 144-byte instances and every+// run of them is a single DrawInstanced. The pixel shader evaluates the same+// coverage formulas as the software raster (gpu_raster.c), so both renderers+// produce the same image. Output is premultiplied (blend ONE, INV_SRC_ALPHA);+// layers inside one primitive (emboss, fill, outline) are composited here,+// in the order the software raster blends them.+//+// Rebuild gpu_d3d11_shaders.h after editing (see gpu/shaders/build.sh).+//+// SPDX-License-Identifier: GPL-2.0-or-later++#define K_RECT 0+#define K_WIDGET 1+#define K_ELLIPSE 2+#define K_LINE 3+#define K_MASK 4+#define K_IMAGE 5+#define K_SHADOW 6+#define K_GRADIENT 7+#define K_HSV 8+#define K_SPHERE 9++#define W_SHADE_H 1+#define W_CHECKER 2+#define W_LEGACY 4+#define W_INNER 8++cbuffer Frame : register(b0)+{+ float2 to_ndc; // 2 / size+ float2 pad_;+};++Texture2D<float> mask_tex : register(t0);+Texture2D<float4> rgba_tex : register(t1);++struct Inst {+ float4 rect : RECT;+ float4 bounds : BOUNDS; // pixel box x0, y0, x1, y1, already clipped+ float4 c0 : COLOR0;+ float4 c1 : COLOR1;+ float4 c2 : COLOR2;+ float4 c3 : COLOR3;+ float4 p : PARAMS; // x = kind+ float4 uv : EXTRA;+};++struct VOut {+ float4 pos : SV_Position;+ nointerpolation float4 rect : RECT;+ nointerpolation float4 c0 : COLOR0;+ nointerpolation float4 c1 : COLOR1;+ nointerpolation float4 c2 : COLOR2;+ nointerpolation float4 c3 : COLOR3;+ nointerpolation float4 p : PARAMS;+ nointerpolation float4 uv : EXTRA;+};++VOut vs_quad(uint vid : SV_VertexID, Inst I)+{+ VOut o;+ const float2 t = float2(vid & 1, vid >> 1);+ const float2 xy = lerp(I.bounds.xy, I.bounds.zw, t);+ o.pos = float4(xy.x * to_ndc.x - 1.0, 1.0 - xy.y * to_ndc.y, 0.0, 1.0);+ o.rect = I.rect;+ o.c0 = I.c0;+ o.c1 = I.c1;+ o.c2 = I.c2;+ o.c3 = I.c3;+ o.p = I.p;+ o.uv = I.uv;+ return o;+}++// Rounded box with a per-corner radius mask (gpu_raster.c sd_widget_box).+float sd_box(float2 s, float2 c, float2 hb, float rad, uint corners)+{+ const float2 p = s - c;+ const uint bit = p.y < 0.0 ? (p.x < 0.0 ? 1u : 2u) : (p.x < 0.0 ? 8u : 4u);+ const float r = (corners & bit) ? rad : 0.0;+ const float2 q = abs(p) - (hb - r);+ if (q.x <= 0.0 || q.y <= 0.0) {+ return max(q.x, q.y) - r;+ }+ return length(q) - r;+}++// Source-over of a straight color into a premultiplied accumulator.+void over(inout float4 acc, float4 c, float cov)+{+ const float a = saturate(c.a * cov);+ acc.rgb = c.rgb * a + acc.rgb * (1.0 - a);+ acc.a = a + acc.a * (1.0 - a);+}++float4 premul(float4 c, float cov)+{+ const float a = saturate(c.a * cov);+ return float4(c.rgb * a, a);+}++float3 hsv_to_rgb(float h, float s, float v)+{+ h = h - floor(h);+ const float h6 = h * 6.0;+ const float3 rgb = saturate(float3(abs(h6 - 3.0) - 1.0, 2.0 - abs(h6 - 2.0), 2.0 - abs(h6 - 4.0)));+ return ((rgb - 1.0) * s + 1.0) * v;+}++float4 ps_quad(VOut v) : SV_Target+{+ const float2 s = v.pos.xy; // pixel center+ const int kind = (int)v.p.x;+ const float4 R = v.rect;++ if (kind == K_RECT) {+ const float2 px = s - 0.5;+ const float2 lo = max(R.xy, px), hi = min(R.xy + R.zw, px + 1.0);+ const float2 cv = saturate(hi - lo);+ return premul(v.c0, cv.x * cv.y);+ }+ if (kind == K_WIDGET) {+ const float x = R.x, y = R.y, w = R.z, h = R.w;+ const float2 hb = float2(w, h) * 0.5, c = R.xy + hb;+ const float rad = v.p.y, radi = v.p.z, px1 = v.p.w;+ const uint corners = (uint)v.uv.x, flags = (uint)v.uv.y;+ const float ow = v.uv.z;+ float4 acc = 0.0;+ const float d = sd_box(s, c, hb, rad, corners);+ const float co = saturate(0.5 - d);+ if (v.c3.a > 0.0 && s.y > c.y) {+ const float de = sd_box(s - float2(0.0, px1), c, hb, rad, corners);+ const float ec = saturate(0.5 - de) - co;+ if (ec > 0.0) {+ over(acc, v.c3, ec);+ }+ }+ if (co > 0.0) {+ float ci, band;+ float t;+ if (flags & W_LEGACY) {+ ci = co;+ band = ow > 0.0 ? co - saturate(0.5 - (d + ow)) : 0.0;+ t = saturate((s.y - y) / h);+ }+ else {+ const float di = sd_box(s, c, hb - px1, radi, corners);+ ci = min(co, saturate(0.5 - di));+ band = co - ci;+ t = (flags & W_SHADE_H) ? saturate((s.x - (x + px1)) / max(1.0, w - 2.0 * px1)) :+ saturate((s.y - (y + px1)) / max(1.0, h - 2.0 * px1));+ }+ if ((flags & W_INNER) && ci > 0.0) {+ if (flags & W_CHECKER) {+ const int cell = ((int)((s.x - x) / 8.0) + (int)((s.y - y) / 8.0)) & 1;+ const float g = cell ? 160.0 / 255.0 : 100.0 / 255.0;+ over(acc, float4(g, g, g, 1.0), ci);+ }+ over(acc, lerp(v.c0, v.c1, t), ci);+ }+ if (v.c2.a > 0.0 && band > 0.0) {+ over(acc, v.c2, band);+ }+ }+ return acc;+ }+ if (kind == K_ELLIPSE) {+ const float lw = v.p.y;+ const float2 dd = s - R.xy;+ float dist;+ if (abs(R.z - R.w) < 1e-3) {+ dist = length(dd) - R.z;+ }+ else {+ const float2 n = dd / R.zw;+ const float k = length(n);+ const float g = length(n / R.zw);+ dist = g > 0.0 ? (k - 1.0) * k / g : -min(R.z, R.w);+ }+ const float cov = lw > 0.0 ? saturate(lw * 0.5 - abs(dist) + 0.5) : saturate(0.5 - dist);+ return premul(v.c0, cov);+ }+ if (kind == K_LINE) {+ const float2 a = R.xy, vv = R.zw - R.xy;+ const float2 wv = s - a;+ const float t = saturate(dot(wv, vv) / dot(vv, vv));+ const float d = length(wv - vv * t) - v.p.y;+ return premul(v.c0, saturate(0.5 - d));+ }+ if (kind == K_MASK) {+ const int2 texel = (int2)v.uv.xy + (int2)(floor(s) - R.xy);+ const float cov = mask_tex.Load(int3(texel, 0));+ return premul(v.c0, cov);+ }+ if (kind == K_IMAGE) {+ const float2 isz = v.uv.zw;+ const int2 sp = clamp((int2)((s - R.xy) * isz / R.zw), int2(0, 0), (int2)isz - 1);+ const float4 c = rgba_tex.Load(int3((int2)v.uv.xy + sp, 0));+ return premul(c, v.p.y);+ }+ if (kind == K_SHADOW) {+ const float rad = v.p.y, size = v.p.z, alpha = v.p.w;+ const float2 hb = R.zw * 0.5;+ const float2 c = R.xy + hb;+ const float d = sd_box(s, c + float2(0.0, size * 0.25), hb, rad, 15u);+ const float dbox = sd_box(s, c, hb, rad, 15u);+ if (dbox <= -0.5 || d >= size) {+ return 0.0;+ }+ float t = 1.0 - saturate(d / size);+ t = t * t * (3.0 - 2.0 * t);+ return float4(0.0, 0.0, 0.0, saturate(t * alpha * saturate(0.5 + dbox)));+ }+ if (kind == K_GRADIENT) {+ const float2 uv = saturate((s - R.xy) / R.zw);+ const float4 left = lerp(v.c0, v.c3, uv.y), right = lerp(v.c1, v.c2, uv.y);+ return premul(lerp(left, right, uv.x), 1.0);+ }+ if (kind == K_HSV) {+ const float2 dd = s - R.xy;+ const float dist = length(dd);+ const float cov = saturate(R.z - dist + 0.5);+ const float hue = atan2(dd.x, -dd.y) * 0.15915494309189535 + 0.5;+ return premul(float4(hsv_to_rgb(hue, min(dist / R.z, 1.0), R.w), 1.0), cov);+ }+ if (kind == K_SPHERE) {+ const float2 n2 = float2(s.x - R.x, -(s.y - R.y)) / R.z;+ const float d2 = dot(n2, n2);+ const float cov = saturate((1.0 - sqrt(d2)) * R.z + 0.5);+ const float3 n = float3(n2, sqrt(max(0.0, 1.0 - d2)));+ const float diff = max(0.0, dot(n, v.c1.xyz));+ float spec = max(0.0, dot(n, v.c2.xyz));+ spec = pow(spec, 16.0); // the software raster squares 2x then takes ^4: ^16+ return premul(float4(v.c0.rgb * (0.12 + 0.88 * diff) + 0.6 * spec, v.c0.a), cov);+ }+ return 0.0;+}++// Per-vertex colored triangles (the BuiGpuSink seam), clipped per vertex.+struct TriIn {+ float2 pos : POSITION;+ float4 color : COLOR0;+ float4 clip : CLIP;+};+struct TriOut {+ float4 pos : SV_Position;+ float4 color : COLOR0;+ nointerpolation float4 clip : CLIP;+};++TriOut vs_tri(TriIn i)+{+ TriOut o;+ o.pos = float4(i.pos.x * to_ndc.x - 1.0, 1.0 - i.pos.y * to_ndc.y, 0.0, 1.0);+ o.color = i.color;+ o.clip = i.clip;+ return o;+}++float4 ps_tri(TriOut i) : SV_Target+{+ if (i.pos.x < i.clip.x || i.pos.y < i.clip.y || i.pos.x >= i.clip.z || i.pos.y >= i.clip.w) {+ discard;+ }+ return premul(i.color, 1.0);+}diff --git a/gpu/shaders/build.sh b/gpu/shaders/build.shnew file mode 100644index 0000000..7cad331--- /dev/null+++ b/gpu/shaders/build.sh@@ -0,0 +1,21 @@+#!/bin/sh+# Compiles bui_ui.hlsl into ../intern/gpu_d3d11_shaders.h (checked in, so+# builds need no shader compiler). FXC: path to fxc.exe (Windows SDK).+set -e+cd "$(dirname "$0")"+FXC=${FXC:-"C:/Program Files (x86)/Windows Kits/10/bin/10.0.19041.0/x64/fxc.exe"}+OUT=../intern/gpu_d3d11_shaders.h+TMP=$(mktemp -d)+for e in vs_quad:vs_4_0 ps_quad:ps_4_0 vs_tri:vs_4_0 ps_tri:ps_4_0; do+ name=${e%%:*}+ prof=${e##*:}+ "$FXC" //nologo //O3 //Qstrip_reflect //Qstrip_debug //T $prof //E $name //Vn g_$name //Fh "$TMP/$name.h" bui_ui.hlsl > /dev/null+done+{+ echo "/* Generated by gpu/shaders/build.sh from bui_ui.hlsl. Do not edit. */"+ cat "$TMP/vs_quad.h" "$TMP/ps_quad.h" "$TMP/vs_tri.h" "$TMP/ps_tri.h" |+ sed -e '/^#if 0/,/^#endif/d' -e '/^\/\//d' -e '/^$/d'+} > "$OUT.tmp"+rm -rf "$TMP"+mv "$OUT.tmp" "$OUT"+echo "wrote $OUT"diff --git a/gpu/tests/CMakeLists.txt b/gpu/tests/CMakeLists.txtnew file mode 100644index 0000000..ec1b5c9--- /dev/null+++ b/gpu/tests/CMakeLists.txt@@ -0,0 +1,9 @@+# bui_gpu tests+# SPDX-License-Identifier: GPL-2.0-or-later++add_executable(bui_gpu_parity test_gpu_parity.c)+target_link_libraries(bui_gpu_parity PRIVATE bui_gpu)+if(NOT MSVC)+ target_link_libraries(bui_gpu_parity PRIVATE m)+endif()+add_test(NAME gpu_parity COMMAND bui_gpu_parity)diff --git a/gpu/tests/test_gpu_parity.c b/gpu/tests/test_gpu_parity.cnew file mode 100644index 0000000..2d6d606--- /dev/null+++ b/gpu/tests/test_gpu_parity.c@@ -0,0 +1,148 @@+/* GPU renderer parity: every raster primitive drawn by the software raster and+ * by the GPU backend must give the same pixels (within rounding). Skips (exit+ * 0) where no GPU device can be created. BUI_PARITY_PPM=dir writes both+ * frames and the difference for inspection.+ * SPDX-License-Identifier: GPL-2.0-or-later */+#include "GPU_raster.h"++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#define W 480+#define H 360++static void scene(BuiRaster *r, int pass)+{+ BUI_raster_begin_frame(r, W, H);+ const float bg[4] = {0.16f, 0.16f, 0.17f, 1};+ BUI_raster_fill_rect(r, 0, 0, W, H, bg);+ const float red[4] = {0.9f, 0.2f, 0.2f, 1}, blue[4] = {0.2f, 0.4f, 0.9f, 0.6f};+ const float white[4] = {1, 1, 1, 1}, green[4] = {0.3f, 0.85f, 0.4f, 0.8f};+ BUI_raster_fill_rect(r, 10.25f, 10.5f, 60.5f, 20.75f, red);+ BUI_raster_frame_rect(r, 80, 10, 60, 30, 2, white);+ BUI_raster_round_rect(r, 150.5f, 10, 70, 30, 8, blue);+ BUI_raster_circle(r, 250, 25, 14, 0, green);+ BUI_raster_circle(r, 290, 25, 14, 2.5f, white);+ BUI_raster_ellipse(r, 340, 25, 30, 12, 0, red);+ BUI_raster_ellipse(r, 410, 25, 30, 12, 1.5f, white);+ BUI_raster_line(r, 10, 60, 120, 95, 1, white);+ BUI_raster_line(r, 10, 100, 120, 100, 2, green);+ BUI_raster_line(r, 130, 60, 140, 110, 3, red);+ const float tri[3][2] = {{160, 60}, {220, 110}, {150, 110}};+ const float tcol[3][4] = {{1, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}};+ BUI_raster_triangles(r, tri, tcol, 3);+ const float star[5][2] = {{270, 55}, {290, 110}, {240, 75}, {300, 75}, {250, 110}};+ BUI_raster_polygon(r, star, 5, blue);+ const float in1[4] = {0.35f, 0.35f, 0.35f, 1}, in2[4] = {0.25f, 0.25f, 0.25f, 1};+ const float out[4] = {0.1f, 0.1f, 0.1f, 1}, emb[4] = {1, 1, 1, 0.1f};+ BUI_raster_widget(r, 320, 60, 120, 24, 5, BUI_CORNER_ALL, in1, in2, out, 1, emb);+ BUI_raster_widget(r, 320, 90, 120, 24, 5, BUI_CORNER_TOP_LEFT | BUI_CORNER_BOTTOM_RIGHT, in1,+ NULL, out, 2, NULL);+ BuiWidgetBase wb;+ memset(&wb, 0, sizeof(wb));+ wb.rect[0] = 10;+ wb.rect[1] = 130;+ wb.rect[2] = 140;+ wb.rect[3] = 22;+ wb.rad = 4;+ wb.radi = 3;+ wb.corners = BUI_CORNER_ALL;+ memcpy(wb.inner1, in1, sizeof(in1));+ memcpy(wb.inner2, in2, sizeof(in2));+ memcpy(wb.outline, out, sizeof(out));+ memcpy(wb.emboss, emb, sizeof(emb));+ wb.pixelsize = 1;+ BUI_raster_widget_base(r, &wb);+ wb.rect[0] = 160;+ wb.shade_horizontal = 1;+ BUI_raster_widget_base(r, &wb);+ wb.rect[0] = 310;+ wb.shade_horizontal = 0;+ wb.alpha_checker = 1;+ wb.inner1[3] = wb.inner2[3] = 0.5f;+ BUI_raster_widget_base(r, &wb);+ BUI_raster_shadow(r, 30, 180, 120, 60, 6, 12, 0.5f);+ const float panel[4] = {0.3f, 0.3f, 0.32f, 1};+ BUI_raster_round_rect(r, 30, 180, 120, 60, 6, panel);+ const float c0[4] = {1, 0, 0, 1}, c1[4] = {0, 1, 0, 1}, c2[4] = {0, 0, 1, 1}, c3[4] = {1, 1, 0, 0.5f};+ BUI_raster_gradient(r, 170, 180, 100, 60, c0, c1, c2, c3);+ BUI_raster_hsv_circle(r, 320, 210, 30, 0.9f);+ const float light[3] = {-0.5f, 0.6f, 0.8f}, sph[4] = {0.6f, 0.4f, 0.2f, 1};+ BUI_raster_sphere(r, 400, 210, 30, light, sph);+ uint32_t img[16 * 12];+ for (int i = 0; i < 16 * 12; i++) {+ img[i] = ((i % 16 + i / 16) & 1) ? 0xFFFF8000u : 0x80202080u;+ }+ BUI_raster_image(r, 20, 260, 64, 48, img, 16, 12, 0.9f);+ /* clipped primitives */+ BUI_raster_set_clip(r, 100, 260, 120, 40);+ BUI_raster_round_rect(r, 90, 250, 80, 60, 10, red);+ BUI_raster_circle(r, 200, 280, 25, 0, green);+ BUI_raster_triangles(r, tri, tcol, 3);+ BUI_raster_set_clip(r, 0, 0, 0, 0);+ if (BUI_text_native()) {+ BUI_raster_set_font(r, "", 0);+ BUI_raster_text(r, 240, 300, "GPU parity: Hello", 17, 16, white);+ BUI_raster_set_font(r, "", BUI_FONT_BOLD);+ BUI_raster_text(r, 240, 330, "Bold text 123", 13, 20, green);+ }+ (void)pass;+ BUI_raster_end_frame(r);+}++static void ppm(const char *dir, const char *name, const uint32_t *px)+{+ char path[512];+ snprintf(path, sizeof(path), "%s/%s.ppm", dir, name);+ FILE *f = fopen(path, "wb");+ if (!f) {+ return;+ }+ fprintf(f, "P6\n%d %d\n255\n", W, H);+ for (int i = 0; i < W * H; i++) {+ const unsigned char c[3] = {(unsigned char)(px[i] >> 16), (unsigned char)(px[i] >> 8),+ (unsigned char)px[i]};+ fwrite(c, 1, 3, f);+ }+ fclose(f);+}++int main(void)+{+ BuiRaster *cpu = BUI_raster_create(W, H);+ BuiRaster *gpu = BUI_raster_create(W, H);+ if (!BUI_raster_gpu_attach(gpu, NULL, 1)) {+ printf("gpu parity: no GPU device, skipped\n");+ return 0;+ }+ scene(cpu, 0);+ scene(gpu, 1);+ const uint32_t *a = BUI_raster_pixels(cpu);+ static uint32_t b[W * H];+ memcpy(b, BUI_raster_pixels(gpu), sizeof(b));+ int bad = 0, maxd = 0;+ static uint32_t diff[W * H];+ for (int i = 0; i < W * H; i++) {+ int d = 0;+ for (int s = 0; s < 24; s += 8) {+ const int da = abs((int)((a[i] >> s) & 0xFF) - (int)((b[i] >> s) & 0xFF));+ d = da > d ? da : d;+ }+ maxd = d > maxd ? d : maxd;+ bad += d > 3;+ const unsigned v = d > 255 / 8 ? 255u : (unsigned)d * 8u;+ diff[i] = (v << 16) | (v << 8) | v;+ }+ const char *dir = getenv("BUI_PARITY_PPM");+ if (dir) {+ ppm(dir, "parity_cpu", a);+ ppm(dir, "parity_gpu", b);+ ppm(dir, "parity_diff", diff);+ }+ printf("gpu parity: %d of %d pixels differ by more than 3 (max %d)\n", bad, W * H, maxd);+ BUI_raster_free(cpu);+ BUI_raster_free(gpu);+ return bad > W * H / 500 ? 1 : 0; /* < 0.2% (edge rounding) */+}diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.hindex 1749a2a..f6419a1 100644--- a/kit/include/BUI_kit.h+++ b/kit/include/BUI_kit.h@@ -337,6 +337,13 @@ void BK_window_set_title(BKWindow *win, const char *title);void BK_window_set_size(BKWindow *win, int width, int height); /* logical pixels */void BK_window_get_size(BKWindow *win, int *r_width, int *r_height);BuiRaster *BK_window_raster(BKWindow *win);+/* GPU rendering (Direct3D 11): windows start on the GPU when+ * BUI_gpu_set_default(1) was called or BUI_GPU=1; this turns it on for one+ * window. The device is created in the background (the first frames use the+ * software raster) and the window falls back to software if it fails.+ * BK_window_gpu() is 1 once frames are drawn on the GPU. */+void BK_window_set_gpu(BKWindow *win, int on);+int BK_window_gpu(BKWindow *win);int BK_window_frames(BKWindow *win);void BK_window_render_now(BKWindow *win);int BK_window_timer(BKWindow *win, int ms); /* one-shot; returns its id */diff --git a/kit/intern/kit_frame.c b/kit/intern/kit_frame.cindex 12ac769..4a10854 100644--- a/kit/intern/kit_frame.c+++ b/kit/intern/kit_frame.c@@ -1549,7 +1549,10 @@ static void canvas_draw(BKNode *n)const int *clip = bk_draw.clip;const long region = (long)BK_MAX(0, clip[2] - clip[0]) * BK_MAX(0, clip[3] - clip[1]);const bool small = region * 4 < (long)n->w * n->h; /* a damage rectangle, not the canvas */- const int threads = (d->n >= PAR_MIN_ITEMS && !small) ? threads_wanted(par_threads()) : 1;+ /* on the GPU, drawing only records instances: one thread is fastest */+ const int threads = (d->n >= PAR_MIN_ITEMS && !small && !BUI_raster_is_gpu(bk_draw.r)) ?+ threads_wanted(par_threads()) :+ 1;if (bk_draw.clip[2] > bk_draw.clip[0] && bk_draw.clip[3] > bk_draw.clip[1] &&canvas_draw_parallel(d, ox, oy, threads)){diff --git a/kit/intern/kit_window.c b/kit/intern/kit_window.cindex f777542..02a28ad 100644--- a/kit/intern/kit_window.c+++ b/kit/intern/kit_window.c@@ -275,6 +275,9 @@ static void do_render(BKWindow *win)prof = getenv("BUI_PROFILE") != NULL;}QueryPerformanceCounter(&t0);+ if (BUI_raster_gpu_poll(win->raster)) {+ win->full = 1; /* the renderer changed: its frame starts empty */+ }const int regions = BK_render(win->ctx, win->raster, w, h, win->full);QueryPerformanceCounter(&t1);win->full = 0;@@ -612,6 +615,9 @@ BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height}SetWindowLongPtrW(win->hwnd, GWLP_USERDATA, (LONG_PTR)win);g_open++;+ if (BUI_gpu_default()) {+ BUI_raster_gpu_attach(win->raster, win->hwnd, 0);+ }BKHost host = {win, host_request, host_set_cursor, host_warp,host_clipboard_get, host_clipboard_set, host_schedule, host_emit};BK_context_set_host(ctx, &host);@@ -697,6 +703,19 @@ BuiRaster *BK_window_raster(BKWindow *win)return win->raster;}+void BK_window_set_gpu(BKWindow *win, int on)+{+ if (win && on) {+ BUI_raster_gpu_attach(win->raster, win->hwnd, 0);+ host_request(win);+ }+}++int BK_window_gpu(BKWindow *win)+{+ return win && BUI_raster_is_gpu(win->raster);+}+int BK_window_frames(BKWindow *win){return win->frames;@@ -908,6 +927,11 @@ BuiRaster *BK_window_raster(BKWindow *win){return NULL;}+void BK_window_set_gpu(BKWindow *win, int on) {}+int BK_window_gpu(BKWindow *win)+{+ return 0;+}int BK_window_frames(BKWindow *win){return 0;