Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

feat: macOS & linux gpu

Preetham Pemmasanie0259513c327
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index d4e46e7..b7ba08b 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -42,7 +42,7 @@ application code; everything it needs arrives through `types/`, `gpu/`, or
| `gpu/` | The draw surface used by the toolkit (`GPU_*`, `imm*`) behind seam headers + a null backend that *records and forwards*: with a sink installed it emits screen-space primitives (`GPU_backend_sink.h`); without one it discards them. Theme colors reach the GPU layer through function-pointer hooks. | **Builds + tested** |
| `compat/` | Seam headers carrying upstream API names (`RNA_access.hh`, `BLF_api.hh`, …) with BUI-owned opaque types and stub implementations (`intern/bui_stubs.cc`). | **Builds** |
| `ui/` | The toolkit sources from `editors/interface`: interface.cc family, widgets, handlers, regions, view2d, views, textbox. Option-gated (`-DBUI_BUILD_UI=ON`). | **Compiles + links** |
-| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; damage-driven rendering; native window hosts for Win32 and X11 (`kit_window_win32.c`, `kit_window_x11.c`; `kit_window_null.c` elsewhere). C API: `kit/include/BUI_kit.h`. | **Builds + tested** |
+| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; damage-driven rendering; native window hosts for Win32, X11 and Cocoa (`kit_window_win32.c`, `kit_window_x11.c`, `kit_window_cocoa.m`; `kit_window_null.c` elsewhere). C API: `kit/include/BUI_kit.h`. | **Builds + tested** |
| `api/` | `bui_c_api.h` — small stable C ABI: version info + sink/viewport plumbing for hosts and bindings. | **Builds + tested** |
| `bindings/python/` | `buipy` CPython extension (no third-party deps) + `bui` package: `bui.components` (Blender component library), `bui.qtsyntax` / `bui.tksyntax` (Qt / tkinter APIs as thin facades over the kit), `bui.host` (native or Tk windows), `SvgSink` headless renderer, `bui.qt.BuiCanvas` PySide6/PyQt6 widget. | **Builds + tested** |
| `backends/qt/` | C++ Qt backend: `BUI::QtSink` (BuiGpuSink → QPainter) + `BUI::BuiWidget` (QWidget host, no moc needed). Gate: `-DBUI_BUILD_QT_BACKEND=ON`. | **Shipped** (builds where Qt exists) |
@@ -72,9 +72,12 @@ The kit itself draws through `GPU_raster.h`:
quadratic curves with horizontal and vertical bands, and the pixel shader
integrates exact coverage. With `BUI_SLUG=0`, it uses glyph bitmaps from
the shared glyph cache in the mask atlas instead.
-- **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)`.
+- **GPU renderer**: Direct3D 11 on Windows (`gpu/intern/gpu_d3d11.c`,
+ `gpu/shaders/bui_ui.hlsl`) and OpenGL 3.3 core on Linux
+ (`gpu/intern/gpu_gl.c`: the same instances, atlases and Slug textures, the
+ uber-shader translated to GLSL, GLX on the X11 window or EGL offscreen,
+ libGL loaded at run time). 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
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f5f8843..0f8c376 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -15,6 +15,12 @@ file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/bindings/python/bui/_version.py" _bui_
REGEX "^__version__")
string(REGEX MATCH "[0-9]+[.][0-9]+[.][0-9]+" BUI_VERSION "${_bui_version_line}")
project(bui LANGUAGES C CXX VERSION ${BUI_VERSION})
+# macOS: the kit's native window host (kit/intern/kit_window_cocoa.m) is
+# Objective-C. Enabled here, in the top directory, so every target linking
+# bui_kit knows the language.
+if(APPLE)
+ enable_language(OBJC)
+endif()
# static libraries end up in shared modules (Python, Node) on Linux and macOS
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
diff --git a/INTEGRATION.md b/INTEGRATION.md
index 8623854..c4a5d55 100644
--- a/INTEGRATION.md
+++ b/INTEGRATION.md
@@ -121,7 +121,7 @@ shiboken build.
Two facades speak the syntax of established toolkits on top of the C kit
(`kit/`, exposed to Python as `buipy.KitNode` / `buipy.KitContext`): widgets
are kit nodes, layouts are the kit's C geometry managers, and windows come
-from `bui.host` (native Win32 / X11 on Windows and Linux, Tk on macOS or with
+from `bui.host` (native Win32 / X11 / Cocoa windows, or Tk with
`BUI_HOST=tk`):
### Qt syntax — `bui.qtsyntax`
diff --git a/README.md b/README.md
index 1b7b14d..ed44a51 100644
--- a/README.md
+++ b/README.md
@@ -281,7 +281,7 @@ Build from source with CMake (see [Building from source](#building-from-source))
### ⚡ Fast by design
- **Damage rendering**: an idle UI costs 0% CPU, and a hover redraws only the widget it touches.
-- **Opt-in GPU renderer** (Direct3D 11), modeled on Blender's instanced widget drawing. It draws the same pixels as the CPU raster.
+- **Opt-in GPU renderer** (Direct3D 11 on Windows, OpenGL 3.3 on Linux), modeled on Blender's instanced widget drawing. It draws the same pixels as the CPU raster.
- In the benchmark, **2–4× less CPU per frame than gpui-fast**, with **less RAM** and a **~5 ms first frame**.
- **Blender's text**: Inter (Blender's UI font) is embedded, so text looks the same on every platform. On the GPU, glyphs are drawn from their outlines with [Slug](https://github.com/EricLengyel/Slug), falling back to a per-glyph atlas like Blender's.
@@ -348,18 +348,25 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o
| | Windows | Linux | macOS |
| --------------------- | ----------------------------- | -------------------------------------------------- | --------------------------------------------- |
-| Window | Native (Win32) | Native (X11; Wayland through XWayland) | Python: the stdlib Tk window. Rust / JS: headless only (a native Cocoa host is in progress) |
-| Python (`pip install`) | ✅ wheels | ✅ wheels | ✅ wheels (Tk window) |
-| Rust | ✅ | ✅ (build from source) | headless (tests, screenshots) |
-| JavaScript / React | ✅ prebuilt on npm | ✅ build the addon from source (`npm run build`) | headless |
-| C | ✅ | ✅ | headless |
-| Renderer | CPU raster, or GPU (Direct3D 11) | CPU raster | CPU raster |
-| HiDPI | Per-monitor DPI | `Xft.dpi` | - |
-
-On Linux, libX11 is loaded when the first window opens, so BUI also imports
-and renders headless on servers and in containers without X11. Building from
-source needs the X11 headers (`libx11-dev` / `libX11-devel`); the C, Python
-and window tests pass on Linux.
+| Window | Native (Win32) | Native (X11; Wayland through XWayland) | Native (Cocoa) 🧪 |
+| Python (`pip install`) | ✅ wheels | ✅ wheels | ✅ wheels |
+| Rust | ✅ | ✅ (build from source) | ✅ 🧪 |
+| JavaScript / React | ✅ prebuilt on npm | ✅ build the addon from source (`npm run build`) | headless (see below) |
+| C | ✅ | ✅ | ✅ 🧪 |
+| Renderer | CPU raster, or GPU (Direct3D 11) | CPU raster, or GPU (OpenGL 3.3) | CPU raster |
+| HiDPI | Per-monitor DPI | `Xft.dpi` | Retina (backing scale) |
+
+🧪 The macOS window host is new: it's a port of Blender's Cocoa code (GHOST),
+written but not yet run on a Mac. Python can still use the stdlib Tk window
+there (`BUI_HOST=tk`). Node runs BUI on its own UI thread and macOS only allows
+windows on the main thread, so JavaScript stays headless on macOS for now.
+
+On Linux, libX11 and libGL are loaded when the first window opens, so BUI
+also imports and renders headless on servers and in containers without them,
+and falls back to the CPU raster where OpenGL is missing. Building from source
+needs the X11 headers (`libx11-dev` / `libX11-devel`); no GL headers are
+needed. The C, Python, window and GPU parity tests pass on Linux, on Mesa's
+software OpenGL and on an NVIDIA GPU.
## Status: what's done and what's not
@@ -372,7 +379,7 @@ and window tests pass on Linux.
| tkinter syntax | **Complete**: every public tkinter and ttk name (7,846 of 7,846) |
| Components | 45 Blender components, including the color ramp and curve editors |
| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 90/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`/`@container`/`@font-face`/`@property`, `@keyframes` animations and transitions, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, Blender components, browser-look form controls, filters / blend modes / masks / 2D transforms, headless testing |
-| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11), portable text engine |
+| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11 on Windows, OpenGL 3.3 on Linux), portable text engine |
| JavaScript / React | `@blender-ui/native`: a DOM-like API over napi-rs, with its own UI thread, only changes crossing the boundary, vsync-paced `requestAnimationFrame` and signals. `@blender-ui/react`: a React 19.3 renderer whose hooks (`useState`, `useMemo`, `useEffect` ...) hold signals that update nodes without re-renders. Both on Node.js and Bun, with headless testing. `bui build` makes standalone executables: about 5 MB with the embedded QuickJS runtime, or Bun's with `--bun` ([guide](docs/javascript.md)) |
| Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms; [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react) and [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native) on npm |
@@ -385,8 +392,7 @@ and window tests pass on Linux.
| Text | No text wrapping around floats; right-to-left text is reordered (bidi) but not shaped (Arabic joining), and no OpenType features |
| Rust components | No async resources (`use_resource`); no generic components |
| JavaScript / React packages | npm packages are prebuilt for Windows x64 only (on Linux, build the addon from source); events reach JavaScript after BUI handled them (no native `preventDefault`), and `event.target` is the deepest _listening_ element |
-| macOS | No native window host yet: Python apps run in the stdlib Tk window (which shows BUI's frame); Rust and JavaScript apps can only run headless there |
-| GPU renderer on Linux / macOS | The GPU renderer is Direct3D 11, so Windows only; Linux and macOS draw with the software raster |
+| macOS | The native Cocoa window host is written but not yet tested on a Mac; JavaScript is headless there (Node's UI thread isn't the main thread); no GPU renderer yet |
| crates.io | The crates are ready to publish but not published yet; use the git dependency for now |
### 🗺️ Planned
@@ -395,8 +401,8 @@ and window tests pass on Linux.
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit; `@blender-ui/react` and the DOM-like API on top, unchanged |
| **egui** | BUI panels inside egui, plus a Blender-styled theme |
-| **Native macOS windows** | A Cocoa host in C, like the Win32 and X11 ones (and a native Wayland host for Linux) |
-| **More GPU backends** | Vulkan / Metal / WebGPU drawing the same instance stream as Direct3D 11 |
+| **macOS GPU and JavaScript windows** | The GPU renderer on Metal (or the OpenGL backend), and Node windows on the main thread |
+| **More GPU backends** | Vulkan / WebGPU drawing the same instance stream as Direct3D 11 and OpenGL |
| **More languages** | C#, Go, Zig, Swift, Kotlin and Lua over the same C header; Dear ImGui; Godot, Unity and Bevy; Flutter |
## How it works
@@ -408,9 +414,9 @@ and window tests pass on Linux.
│ │
C kit (kit/): node tree · geometry · input & interaction · Blender widget drawing · undo · animation
│
- renderer: damage-driven software raster (parallel) or GPU (Direct3D 11, instanced, opt-in)
+ renderer: damage-driven software raster (parallel) or GPU (Direct3D 11 / OpenGL 3.3, instanced, opt-in)
│
- window: native Win32 / X11 window · stdlib Tk window (macOS) · headless (tests, screenshots)
+ window: native Win32 / X11 / Cocoa window · stdlib Tk window · headless (tests, screenshots)
```
- **Blender's real UI code.** Widget drawing is a C port of Blender's
@@ -467,7 +473,7 @@ time an app causes: the CPU it spends starting up, and the CPU it uses over 20
seconds while the window sits idle (what drains a battery while an app is
open). BUI redraws only when something changes and otherwise sleeps, so idle
use is near zero on either renderer. The GPU renderer starts a little slower
-and uses more memory (the Direct3D device), and pays off on large, animated
+and uses more memory (the GPU device), and pays off on large, animated
scenes (below). Node's event loop accounts for the JavaScript idle figure,
Python's times include starting the interpreter, and memory doesn't count GPU
memory. Run it yourself with `py -3 bench/run.py` (the script lists what to
@@ -698,7 +704,7 @@ cd bindings/rust && cargo test # Rust: CSS, Tailwind, rsx!, hooks,
| Path | Contents |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kit/` | The C runtime: nodes, input, widget drawing (the `interface_widgets.cc` port), menus, geometry managers, canvas, the Win32 and X11 window hosts. API: `kit/include/BUI_kit.h` |
-| `gpu/` | Software raster, Direct3D 11 renderer (`gpu_d3d11.c`, `shaders/`, Slug text), text engine (stb_truetype + embedded Inter, or GDI) |
+| `gpu/` | Software raster, GPU renderer on Direct3D 11 (`gpu_d3d11.c`, `shaders/`) and OpenGL 3.3 (`gpu_gl.c`), Slug text, text engine (stb_truetype + embedded Inter, or GDI) |
| `core/`, `types/` | Blender's `blenlib` subset 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 |
diff --git a/bindings/python/bui/host.py b/bindings/python/bui/host.py
index 1f56a61..28263bf 100644
--- a/bindings/python/bui/host.py
+++ b/bindings/python/bui/host.py
@@ -2,8 +2,9 @@
:class:`Window` shows a ``buipy.KitContext`` in a top-level window:
-* **native** (Windows): ``buipy.KitWindow`` — input, layout, rendering and
- presenting all stay in C; Python only runs callbacks.
+* **native** (Windows, Linux/X11, macOS/Cocoa): ``buipy.KitWindow`` — input,
+ layout, rendering and presenting all stay in C; Python only runs callbacks.
+ On macOS it needs the main thread (AppKit); elsewhere the Tk host is used.
* **tk** (elsewhere, or ``BUI_HOST=tk``): a stdlib Tk window with
:class:`bui._surface.TkSurface` blitting the raster.
@@ -17,6 +18,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
from __future__ import annotations
import os
+import sys
from typing import Callable, Optional
import buipy
@@ -81,6 +83,23 @@ def _tk():
return _tk_root
+def _tk_owns_nsapp() -> None:
+ """macOS: start the hidden Tk root before the first Cocoa window.
+
+ Tk makes NSApp an instance of its own NSApplication subclass and fails if
+ a plain NSApplication exists already, which the native host would create.
+ BUI still uses the real Tk on the side (file dialogs, fonts, PhotoImage),
+ so Tk goes first; the native host then reuses Tk's NSApp. Without tkinter
+ nothing is needed. ``BUI_MAC_TK=0`` skips it.
+ """
+ if _tk_root is not None or os.environ.get("BUI_MAC_TK", "1") == "0":
+ return
+ try:
+ _tk()
+ except Exception: # no tkinter / no Tcl: nothing can clash
+ pass
+
+
class Window:
def __init__(self, ctx, title: str = "BUI", size=(640, 480), native: bool = None,
gpu: bool = None):
@@ -92,6 +111,8 @@ class Window:
self._win = None
self._top = self._surface = None
if self.native:
+ if sys.platform == "darwin":
+ _tk_owns_nsapp()
self._win = buipy.KitWindow(ctx, title, *self._size)
self._win.on_close = self._close_requested
if gpu: # None: buipy.set_gpu() / BUI_GPU decide
diff --git a/bindings/rust/blenderui-node/src/lib.rs b/bindings/rust/blenderui-node/src/lib.rs
index a600a1a..101e680 100644
--- a/bindings/rust/blenderui-node/src/lib.rs
+++ b/bindings/rust/blenderui-node/src/lib.rs
@@ -154,7 +154,11 @@ impl NativeApp {
Some(o) => (o.gpu, o.slug, o.headless.unwrap_or(false)),
None => (None, None, false),
};
- let headless = headless || !blenderui::native_windows();
+ // macOS: AppKit only runs on the main thread, which here is the
+ // JavaScript thread (libuv's loop), while BUI runs on its own
+ // "bui-ui" thread; the Cocoa host refuses windows there, so stay
+ // headless instead of starting a native loop that would end at once.
+ let headless = headless || !blenderui::native_windows() || cfg!(target_os = "macos");
let (ltx, lrx) = mpsc::channel::<Link>();
std::thread::Builder::new().name("bui-ui".into()).spawn(move || {
let mut a = if headless { Application::headless() } else { Application::new().keep_alive(true) };
diff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rs
index 196b039..d13a1af 100644
--- a/bindings/rust/blenderui-sys/build.rs
+++ b/bindings/rust/blenderui-sys/build.rs
@@ -52,6 +52,14 @@ fn main() {
if target == "linux" || target.ends_with("bsd") {
println!("cargo:rustc-link-lib=X11"); // the native window host
}
+ if target == "macos" {
+ // the Cocoa window host (kit/intern/kit_window_cocoa.m): static
+ // libraries don't carry CMake's framework links to rustc
+ for fw in ["Cocoa", "CoreGraphics"] {
+ println!("cargo:rustc-link-lib=framework={fw}");
+ }
+ println!("cargo:rustc-link-lib=objc");
+ }
println!("cargo:rustc-link-lib=m");
println!("cargo:rustc-link-lib=pthread");
}
diff --git a/docs/components.md b/docs/components.md
index 5dd3f1d..79fb911 100644
--- a/docs/components.md
+++ b/docs/components.md
@@ -46,7 +46,7 @@ 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
+draw them on the GPU (Direct3D 11 on Windows, OpenGL on Linux). The pixels are the same and the CPU cost
is much lower. See [getting-started.md](getting-started.md#gpu-rendering).
## Common component API
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 2f3d2f7..f4cae43 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -79,9 +79,9 @@ shared (`bui.host`).
| Variable | Effect |
|---|---|
| `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, Linux) |
+| `BUI_HOST=tk` | Force the stdlib-Tk window host even where the native host exists |
| `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=1` | Draw native windows on the GPU (Direct3D 11 on Windows, OpenGL 3.3 on Linux). `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` | A font file to replace the embedded Inter UI font, and an extra font folder |
| `BUI_SLUG` | `0` draws GPU text from a per-glyph bitmap atlas instead of glyph outlines (Slug); `1` forces Slug. Overrides `bui.set_slug()` / `.slug()` / `BUI_gpu_set_slug()` |
@@ -96,14 +96,16 @@ shared (`bui.host`).
straight into the kit, and frames are presented by blitting only the
changed tiles. It follows the display's DPI (per-monitor on Windows,
`Xft.dpi` on X11) and paces animations to the display's refresh rate.
-- **Tk (macOS, or with `BUI_HOST=tk`).** A stdlib `tkinter` window that
+- **Native (macOS).** A Cocoa window (a port of Blender's GHOST code; new,
+ not yet tested on a Mac) with Retina scaling. It needs the main thread.
+- **Tk (with `BUI_HOST=tk`, or where no native host works).** A stdlib `tkinter` 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:
+(Direct3D 11 on Windows, OpenGL 3.3 on Linux) instead, use one of these:
| Where | Flag |
|---|---|
@@ -128,8 +130,9 @@ Both renderers draw the same pixels. The GPU uses far less CPU per frame
[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.
-The GPU renderer is Direct3D 11: without a GPU, and on Linux and macOS,
-windows stay on the software raster.
+The GPU renderer is Direct3D 11 on Windows and OpenGL 3.3 on Linux (libGL
+is loaded at run time). Without a GPU or OpenGL, and on macOS, windows stay
+on the software raster.
`bui.host.run()` runs one loop for all windows, `bui.host.update()` processes
pending events once, and `bui.host.quit()` stops the loop.
@@ -141,6 +144,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. |
+| `gpu=True` has no effect | Run with `BUI_GPU_DEBUG=1` to see why the device failed. Machines without Direct3D 11 (Windows) or OpenGL 3.3 (Linux) stay on the software raster. |
| Monospace/serif text uses the UI font | Install a TrueType font family (DejaVu, Liberation or Noto). The UI font itself (Inter) is embedded. |
| 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/javascript.md b/docs/javascript.md
index 68f8b63..67edaa3 100644
--- a/docs/javascript.md
+++ b/docs/javascript.md
@@ -2,7 +2,7 @@
BUI runs from JavaScript through a native addon built with napi-rs, much as
[GPUIX](https://www.npmjs.com/package/@gpuix/react) drives GPUI. You get native
-windows drawn on the CPU or with Direct3D 11, HTML elements, CSS and Tailwind
+windows drawn on the CPU or the GPU (Direct3D 11 / OpenGL), HTML elements, CSS and Tailwind
classes, and the same engine as the Rust crate. There's no browser and no
Electron. It works on **Node.js** and **Bun**, and `bui build` turns an app
into a **single executable of about 5 MB**: BUI with an embedded QuickJS
@@ -14,8 +14,9 @@ engine ([Standalone apps](#standalone-apps)).
| [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react) (`bindings/react`) | A React 19.3 renderer; React's hooks by React's names, backed by signals |
**Platforms:** prebuilt for Windows x64. On Linux, build the addon from
-source (see [Building](#building)); windows are native X11 windows. macOS has
-no native window host yet, so there use `headless: true`. A browser
+source (see [Building](#building)); windows are native X11 windows, on the CPU or
+with OpenGL. On macOS use `headless: true`: macOS only allows windows on the
+main thread, and BUI runs on a UI thread of its own in Node. A browser
(WebAssembly) build is planned.
## Plain JavaScript
diff --git a/docs/publishing.md b/docs/publishing.md
index d2ffbd2..5646292 100644
--- a/docs/publishing.md
+++ b/docs/publishing.md
@@ -91,9 +91,9 @@ No API tokens are stored anywhere.
`libx11-dev` / `libX11-devel`, BUI uses its native X11 window). Installing
`libX11-devel` in `[tool.cibuildwheel.linux] before-all` would give the
wheels the native host.
-- macOS has no native window host yet: its wheels use the stdlib Tk window,
- so the Python needs `tkinter` (for example from python.org or
- `brew install python-tk`).
+- macOS: the native Cocoa window host is new and hasn't been run on a Mac
+ yet. With `BUI_HOST=tk` the wheels use the stdlib Tk window instead, which
+ needs `tkinter` (for example from python.org or `brew install python-tk`).
- MSVC builds work (the Rust crate and the CMake build use Visual Studio's
toolchain), but the published Windows wheels are built with MinGW.
- No `musllinux` or 32-bit wheels yet (skipped in `[tool.cibuildwheel]`).
diff --git a/docs/qt.md b/docs/qt.md
index a4cf3eb..5deb073 100644
--- a/docs/qt.md
+++ b/docs/qt.md
@@ -65,7 +65,7 @@ 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
+draw them on the GPU (Direct3D 11 on Windows, OpenGL on Linux). The pixels are the same and the CPU cost
is much lower. See [getting-started.md](getting-started.md#gpu-rendering).
## How it maps
@@ -76,7 +76,7 @@ is much lower. See [getting-started.md](getting-started.md#gpu-rendering).
| `QVBoxLayout` / `QHBoxLayout` | Tk's packer in C, with Qt semantics: stretch factors, expanding size policies, spacing between items only, margins on top-level layouts only |
| `QGridLayout` / `QFormLayout` | Tk's gridder in C (`setColumnStretch` maps to column weights) |
| Signals | Plain Python (`Signal` / `pyqtSignal`). Slots that take fewer arguments than the signal sends get fewer. |
-| `QApplication.exec()` | `bui.host.run()`: a native window on Windows and Linux, a Tk-hosted window on macOS |
+| `QApplication.exec()` | `bui.host.run()`: a native window (Win32, X11, Cocoa), or a Tk-hosted window with `BUI_HOST=tk` |
| `QTimer`, `QPropertyAnimation` | Window timers; animations step at 120 Hz with easing curves |
## Supported classes
diff --git a/docs/rust.md b/docs/rust.md
index 088f21c..adcf809 100644
--- a/docs/rust.md
+++ b/docs/rust.md
@@ -577,7 +577,7 @@ 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,
+`BUI_GPU=1` / `0` overrides both. It is Direct3D 11 on Windows and OpenGL 3.3 on Linux. 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
@@ -630,9 +630,9 @@ The `gdi-text` feature uses Windows' GDI engine and system fonts.
over a form field does not cover the field.
- **Images**: PNG only, nearest-neighbour scaling. `video`, `audio`,
`iframe` show a placeholder.
-- **Windows** are native on Windows (Win32) and Linux (X11); macOS has no
- window host yet, so there use `Application::headless()`. The GPU renderer
- is Windows only.
+- **Windows** are native on Windows (Win32), Linux (X11) and macOS (Cocoa,
+ new and not yet tested on a Mac; it needs the main thread). The GPU
+ renderer runs on Windows and Linux.
- `text-align: justify` aligns left. Table columns are sized from their
widest single-line content, a simpler version of browsers' auto layout.
diff --git a/gpu/CMakeLists.txt b/gpu/CMakeLists.txt
index 4e18b22..3d4f5b8 100644
--- a/gpu/CMakeLists.txt
+++ b/gpu/CMakeLists.txt
@@ -65,4 +65,11 @@ endif()
if(WIN32)
# gpu_raster.c: GDI glyph-run text engine + native window present.
target_link_libraries(bui_gpu PUBLIC gdi32 user32)
+elseif(NOT APPLE)
+ # GPU renderer: OpenGL 3.3 (GLX windows, EGL offscreen) in gpu_gl.c instead
+ # of Direct3D 11. libGL / libEGL / libX11 are dlopen()ed at run time, never
+ # linked, so nothing GL is needed to build or import.
+ target_sources(bui_gpu PRIVATE intern/gpu_gl.c)
+ target_compile_definitions(bui_gpu PRIVATE BUI_GPU_GL=1)
+ target_link_libraries(bui_gpu PRIVATE ${CMAKE_DL_LIBS})
endif()
diff --git a/gpu/include/GPU_raster.h b/gpu/include/GPU_raster.h
index 06e9caf..7193950 100644
--- a/gpu/include/GPU_raster.h
+++ b/gpu/include/GPU_raster.h
@@ -199,13 +199,19 @@ const uint8_t *BUI_text_run_mask(const BuiTextRun *run, int *r_w, int *r_h, int
* 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). */
+/* GPU rendering (Direct3D 11 on Windows, OpenGL 3.3 on Linux). 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).
+ * `window_handle` is an HWND on Windows; on X11 it points to a
+ * BuiGpuX11Window (copied during the call). */
+typedef struct BuiGpuX11Window {
+ void *display; /* Display * the window lives on (NULL: open one) */
+ unsigned long window; /* Window */
+} BuiGpuX11Window;
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);
diff --git a/gpu/intern/gpu_d3d11.c b/gpu/intern/gpu_d3d11.c
index ef674ce..f346de9 100644
--- a/gpu/intern/gpu_d3d11.c
+++ b/gpu/intern/gpu_d3d11.c
@@ -1126,7 +1126,8 @@ int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h)
/** \} */
-#else /* !_WIN32: no GPU backend yet; every raster stays in software */
+#elif !defined(BUI_GPU_GL) /* no GPU backend here (gpu_gl.c provides one on Linux):
+ * every raster stays in software */
# include "gpu_d3d11.h"
diff --git a/gpu/intern/gpu_gl.c b/gpu/intern/gpu_gl.c
new file mode 100644
index 0000000..449f4ad
--- /dev/null
+++ b/gpu/intern/gpu_gl.c
@@ -0,0 +1,2027 @@
+/* BUI GPU renderer: OpenGL 3.3 core backend (Linux / X11) — see gpu_d3d11.h.
+ *
+ * The same renderer as gpu_d3d11.c on OpenGL: every primitive is one instance
+ * of a single uber-shader (a GLSL 330 translation of gpu/shaders/bui_ui.hlsl),
+ * drawn into a persistent framebuffer object so damage-region redraws work
+ * like the software raster; present blits that frame to the window. Text
+ * masks share one R8 atlas, images one BGRA atlas, and Slug glyph outlines
+ * live in RGBA32F / RG32UI textures addressed linearly, exactly as on D3D.
+ *
+ * Contexts (after Blender's GHOST_ContextGLX / GHOST_ContextEGL):
+ * - a window: GLX on the X11 window given as a BuiGpuX11Window (the kit's
+ * Display, so events and GL share one connection);
+ * - offscreen (NULL handle: tests, BUI_raster_pixels): EGL (surfaceless
+ * platform, else the default display), else a GLX pbuffer.
+ * libGL / libEGL / libX11 are loaded with dlopen on first use, never linked:
+ * without them bui_gpu_create returns NULL and the software raster draws.
+ * The context is created on the calling thread (no worker thread as on D3D);
+ * bui_gpu_state is 1 right away, so the raster still switches over at its
+ * next poll, the same "pending" handoff the D3D device uses.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#if defined(BUI_GPU_GL) && !defined(_WIN32)
+
+# include <dlfcn.h>
+# include <stddef.h>
+# include <stdint.h>
+# include <stdio.h>
+# include <stdlib.h>
+# include <string.h>
+
+# include "GPU_raster.h"
+# include "gpu_d3d11.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Vendored GL / GLX / EGL / Xlib declarations
+ *
+ * Only what this file uses, so the build needs no GL headers and the binary
+ * no GL libraries.
+ * \{ */
+
+typedef unsigned int GLenum;
+typedef unsigned int GLuint;
+typedef unsigned int GLbitfield;
+typedef int GLint;
+typedef int GLsizei;
+typedef float GLfloat;
+typedef unsigned char GLubyte;
+typedef unsigned char GLboolean;
+typedef char GLchar;
+typedef ptrdiff_t GLsizeiptr;
+typedef ptrdiff_t GLintptr;
+
+# define GL_NO_ERROR 0
+# define GL_FALSE 0
+# define GL_TRIANGLES 0x0004
+# define GL_TRIANGLE_STRIP 0x0005
+# define GL_ONE 1
+# define GL_ONE_MINUS_SRC_ALPHA 0x0303
+# define GL_CULL_FACE 0x0B44
+# define GL_DEPTH_TEST 0x0B71
+# define GL_DITHER 0x0BD0
+# define GL_BLEND 0x0BE2
+# define GL_SCISSOR_TEST 0x0C11
+# define GL_UNPACK_ROW_LENGTH 0x0CF2
+# define GL_UNPACK_ALIGNMENT 0x0CF5
+# define GL_PACK_ROW_LENGTH 0x0D02
+# define GL_PACK_ALIGNMENT 0x0D05
+# define GL_MAX_TEXTURE_SIZE 0x0D33
+# define GL_TEXTURE_2D 0x0DE1
+# define GL_UNSIGNED_BYTE 0x1401
+# define GL_UNSIGNED_INT 0x1405
+# define GL_FLOAT 0x1406
+# define GL_RED 0x1903
+# define GL_RGBA 0x1908
+# define GL_VENDOR 0x1F00
+# define GL_RENDERER 0x1F01
+# define GL_VERSION 0x1F02
+# define GL_NEAREST 0x2600
+# define GL_TEXTURE_MAG_FILTER 0x2800
+# define GL_TEXTURE_MIN_FILTER 0x2801
+# define GL_TEXTURE_WRAP_S 0x2802
+# define GL_TEXTURE_WRAP_T 0x2803
+# define GL_COLOR_BUFFER_BIT 0x4000
+# define GL_RGBA8 0x8058
+# define GL_BGRA 0x80E1
+# define GL_CLAMP_TO_EDGE 0x812F
+# define GL_RG_INTEGER 0x8228
+# define GL_R8 0x8229
+# define GL_RG32UI 0x823C
+# define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
+# define GL_TEXTURE0 0x84C0
+# define GL_RGBA32F 0x8814
+# define GL_ARRAY_BUFFER 0x8892
+# define GL_STREAM_DRAW 0x88E0
+# define GL_FRAGMENT_SHADER 0x8B30
+# define GL_VERTEX_SHADER 0x8B31
+# define GL_COMPILE_STATUS 0x8B81
+# define GL_LINK_STATUS 0x8B82
+# define GL_INFO_LOG_LENGTH 0x8B84
+# define GL_READ_FRAMEBUFFER 0x8CA8
+# define GL_DRAW_FRAMEBUFFER 0x8CA9
+# define GL_FRAMEBUFFER_COMPLETE 0x8CD5
+# define GL_COLOR_ATTACHMENT0 0x8CE0
+# define GL_FRAMEBUFFER 0x8D40
+# define GL_FRAMEBUFFER_SRGB 0x8DB9
+# define GL_CONTEXT_LOST 0x0507
+
+/* GL entry points: return type, name, parameters */
+# define GL_FUNCS(F) \
+ F(const GLubyte *, glGetString, (GLenum)) \
+ F(GLenum, glGetError, (void)) \
+ F(void, glGetIntegerv, (GLenum, GLint *)) \
+ F(void, glEnable, (GLenum)) \
+ F(void, glDisable, (GLenum)) \
+ F(void, glBlendFunc, (GLenum, GLenum)) \
+ F(void, glViewport, (GLint, GLint, GLsizei, GLsizei)) \
+ F(void, glClearColor, (GLfloat, GLfloat, GLfloat, GLfloat)) \
+ F(void, glClear, (GLbitfield)) \
+ F(void, glFlush, (void)) \
+ F(void, glPixelStorei, (GLenum, GLint)) \
+ F(void, glReadPixels, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *)) \
+ F(void, glGenTextures, (GLsizei, GLuint *)) \
+ F(void, glDeleteTextures, (GLsizei, const GLuint *)) \
+ F(void, glBindTexture, (GLenum, GLuint)) \
+ F(void, glActiveTexture, (GLenum)) \
+ F(void, glTexParameteri, (GLenum, GLenum, GLint)) \
+ F(void, glTexImage2D, \
+ (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *)) \
+ F(void, glTexSubImage2D, \
+ (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *)) \
+ F(void, glGenBuffers, (GLsizei, GLuint *)) \
+ F(void, glDeleteBuffers, (GLsizei, const GLuint *)) \
+ F(void, glBindBuffer, (GLenum, GLuint)) \
+ F(void, glBufferData, (GLenum, GLsizeiptr, const void *, GLenum)) \
+ F(void, glGenVertexArrays, (GLsizei, GLuint *)) \
+ F(void, glDeleteVertexArrays, (GLsizei, const GLuint *)) \
+ F(void, glBindVertexArray, (GLuint)) \
+ F(void, glEnableVertexAttribArray, (GLuint)) \
+ F(void, glVertexAttribPointer, (GLuint, GLint, GLenum, GLboolean, GLsizei, const void *)) \
+ F(void, glVertexAttribDivisor, (GLuint, GLuint)) \
+ F(GLuint, glCreateShader, (GLenum)) \
+ F(void, glShaderSource, (GLuint, GLsizei, const GLchar *const *, const GLint *)) \
+ F(void, glCompileShader, (GLuint)) \
+ F(void, glGetShaderiv, (GLuint, GLenum, GLint *)) \
+ F(void, glGetShaderInfoLog, (GLuint, GLsizei, GLsizei *, GLchar *)) \
+ F(void, glDeleteShader, (GLuint)) \
+ F(GLuint, glCreateProgram, (void)) \
+ F(void, glAttachShader, (GLuint, GLuint)) \
+ F(void, glLinkProgram, (GLuint)) \
+ F(void, glGetProgramiv, (GLuint, GLenum, GLint *)) \
+ F(void, glGetProgramInfoLog, (GLuint, GLsizei, GLsizei *, GLchar *)) \
+ F(void, glDeleteProgram, (GLuint)) \
+ F(void, glUseProgram, (GLuint)) \
+ F(GLint, glGetUniformLocation, (GLuint, const GLchar *)) \
+ F(void, glUniform1i, (GLint, GLint)) \
+ F(void, glUniform2f, (GLint, GLfloat, GLfloat)) \
+ F(void, glGenFramebuffers, (GLsizei, GLuint *)) \
+ F(void, glDeleteFramebuffers, (GLsizei, const GLuint *)) \
+ F(void, glBindFramebuffer, (GLenum, GLuint)) \
+ F(void, glFramebufferTexture2D, (GLenum, GLenum, GLenum, GLuint, GLint)) \
+ F(GLenum, glCheckFramebufferStatus, (GLenum)) \
+ F(void, glBlitFramebuffer, \
+ (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum)) \
+ F(void, glDrawArrays, (GLenum, GLint, GLsizei)) \
+ F(void, glDrawArraysInstanced, (GLenum, GLint, GLsizei, GLsizei))
+
+# define GLF_DECL(ret, name, args) ret(*name) args;
+typedef struct GLFuncs {
+ GL_FUNCS(GLF_DECL)
+} GLFuncs;
+# undef GLF_DECL
+
+/* Xlib (opaque) */
+typedef void XDisplay;
+typedef unsigned long XID;
+typedef int (*XErrHandler)(XDisplay *, void *);
+
+/* GLX */
+typedef void *GLXFBConfig;
+typedef void *GLXContext;
+typedef void (*ProcFn)(void);
+# define GLX_DOUBLEBUFFER 5
+# define GLX_RED_SIZE 8
+# define GLX_GREEN_SIZE 9
+# define GLX_BLUE_SIZE 10
+# define GLX_X_VISUAL_TYPE 0x22
+# define GLX_TRUE_COLOR 0x8002
+# define GLX_VISUAL_ID 0x800B
+# define GLX_DRAWABLE_TYPE 0x8010
+# define GLX_RENDER_TYPE 0x8011
+# define GLX_X_RENDERABLE 0x8012
+# define GLX_WINDOW_BIT 0x1
+# define GLX_PBUFFER_BIT 0x4
+# define GLX_RGBA_BIT 0x1
+# define GLX_WIDTH 0x801D
+# define GLX_HEIGHT 0x801E
+# define GLX_PBUFFER_HEIGHT 0x8040
+# define GLX_PBUFFER_WIDTH 0x8041
+# define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
+# define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
+# define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
+# define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x1
+
+/* EGL */
+typedef void *EGLDisplay;
+typedef void *EGLConfig;
+typedef void *EGLContext;
+typedef void *EGLSurface;
+typedef int32_t EGLint;
+typedef unsigned int EGLBoolean;
+typedef unsigned int EGLenum;
+# define EGL_ALPHA_SIZE 0x3021
+# define EGL_BLUE_SIZE 0x3022
+# define EGL_GREEN_SIZE 0x3023
+# define EGL_RED_SIZE 0x3024
+# define EGL_SURFACE_TYPE 0x3033
+# define EGL_NONE 0x3038
+# define EGL_RENDERABLE_TYPE 0x3040
+# define EGL_EXTENSIONS 0x3055
+# define EGL_HEIGHT 0x3056
+# define EGL_WIDTH 0x3057
+# define EGL_OPENGL_API 0x30A2
+# define EGL_CONTEXT_MAJOR_VERSION 0x3098
+# define EGL_CONTEXT_MINOR_VERSION 0x30FB
+# define EGL_CONTEXT_OPENGL_PROFILE_MASK 0x30FD
+# define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT 0x1
+# define EGL_OPENGL_BIT 0x8
+# define EGL_PBUFFER_BIT 0x1
+# define EGL_PLATFORM_SURFACELESS_MESA 0x31DD
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Run-time loading
+ * \{ */
+
+/* BUI_GPU_DEBUG=1: why the GPU path wasn't taken, and what it runs on */
+static int debug_on(void)
+{
+ const char *dbg = getenv("BUI_GPU_DEBUG");
+ return dbg && dbg[0] == '1';
+}
+
+static int fail(const char *what)
+{
+ if (debug_on()) {
+ fprintf(stderr, "bui gpu (gl): %s failed\n", what);
+ }
+ return 0;
+}
+
+static void *open_lib(const char *const *names)
+{
+ for (; *names; names++) {
+ void *h = dlopen(*names, RTLD_NOW | RTLD_LOCAL);
+ if (h) {
+ return h;
+ }
+ }
+ return NULL;
+}
+
+# define X11_FUNCS(F) \
+ F(XDisplay *, XOpenDisplay, (const char *)) \
+ F(int, XCloseDisplay, (XDisplay *)) \
+ F(int, XDefaultScreen, (XDisplay *)) \
+ F(void *, XDefaultVisual, (XDisplay *, int)) \
+ F(unsigned long, XVisualIDFromVisual, (void *)) \
+ F(int, XFree, (void *)) \
+ F(int, XSync, (XDisplay *, int)) \
+ F(XErrHandler, XSetErrorHandler, (XErrHandler))
+
+# define GLX_FUNCS(F) \
+ F(int, glXQueryVersion, (XDisplay *, int *, int *)) \
+ F(const char *, glXQueryExtensionsString, (XDisplay *, int)) \
+ F(GLXFBConfig *, glXChooseFBConfig, (XDisplay *, int, const int *, int *)) \
+ F(int, glXGetFBConfigAttrib, (XDisplay *, GLXFBConfig, int, int *)) \
+ F(int, glXMakeContextCurrent, (XDisplay *, XID, XID, GLXContext)) \
+ F(void, glXDestroyContext, (XDisplay *, GLXContext)) \
+ F(void, glXSwapBuffers, (XDisplay *, XID)) \
+ F(GLXContext, glXGetCurrentContext, (void)) \
+ F(XID, glXCreatePbuffer, (XDisplay *, GLXFBConfig, const int *)) \
+ F(void, glXDestroyPbuffer, (XDisplay *, XID)) \
+ F(void, glXQueryDrawable, (XDisplay *, XID, int, unsigned int *)) \
+ F(ProcFn, glXGetProcAddressARB, (const GLubyte *))
+
+# define EGL_FUNCS(F) \
+ F(ProcFn, eglGetProcAddress, (const char *)) \
+ F(EGLDisplay, eglGetDisplay, (void *)) \
+ F(EGLBoolean, eglInitialize, (EGLDisplay, EGLint *, EGLint *)) \
+ F(EGLBoolean, eglBindAPI, (EGLenum)) \
+ F(EGLBoolean, eglChooseConfig, (EGLDisplay, const EGLint *, EGLConfig *, EGLint, EGLint *)) \
+ F(EGLContext, eglCreateContext, (EGLDisplay, EGLConfig, EGLContext, const EGLint *)) \
+ F(EGLBoolean, eglDestroyContext, (EGLDisplay, EGLContext)) \
+ F(EGLBoolean, eglMakeCurrent, (EGLDisplay, EGLSurface, EGLSurface, EGLContext)) \
+ F(EGLContext, eglGetCurrentContext, (void)) \
+ F(EGLSurface, eglCreatePbufferSurface, (EGLDisplay, EGLConfig, const EGLint *)) \
+ F(EGLBoolean, eglDestroySurface, (EGLDisplay, EGLSurface)) \
+ F(const char *, eglQueryString, (EGLDisplay, EGLint))
+
+# define PTR_DECL(ret, name, args) static ret(*p_##name) args;
+X11_FUNCS(PTR_DECL)
+GLX_FUNCS(PTR_DECL)
+EGL_FUNCS(PTR_DECL)
+# undef PTR_DECL
+
+static void *g_libgl = NULL; /* libGL / libOpenGL: fallback for GL entry points */
+
+# define PTR_LOAD(ret, name, args) \
+ if (!(p_##name = (ret(*) args)dlsym(lib, #name))) { \
+ return fail("resolving " #name); \
+ }
+
+static int x11_load(void)
+{
+ static int state = 0; /* 0 untried, 1 loaded, -1 unavailable */
+ if (state == 0) {
+ static const char *const names[] = {"libX11.so.6", "libX11.so", NULL};
+ void *lib = open_lib(names);
+ state = -1;
+ if (!lib) {
+ return fail("loading libX11");
+ }
+ X11_FUNCS(PTR_LOAD)
+ state = 1;
+ }
+ return state > 0;
+}
+
+static int glx_load(void)
+{
+ static int state = 0;
+ if (state == 0) {
+ static const char *const names[] = {"libGL.so.1", "libGL.so", "libGLX.so.0", NULL};
+ void *lib = open_lib(names);
+ state = -1;
+ if (!lib) {
+ return fail("loading libGL");
+ }
+ if (!g_libgl) {
+ g_libgl = lib;
+ }
+ GLX_FUNCS(PTR_LOAD)
+ state = 1;
+ }
+ return state > 0;
+}
+
+static int egl_load(void)
+{
+ static int state = 0;
+ if (state == 0) {
+ static const char *const names[] = {"libEGL.so.1", "libEGL.so", NULL};
+ void *lib = open_lib(names);
+ state = -1;
+ if (!lib) {
+ return fail("loading libEGL");
+ }
+ EGL_FUNCS(PTR_LOAD)
+ if (!g_libgl) {
+ static const char *const gl_names[] = {"libOpenGL.so.0", "libGL.so.1", NULL};
+ g_libgl = open_lib(gl_names);
+ }
+ state = 1;
+ }
+ return state > 0;
+}
+
+# undef PTR_LOAD
+
+static int has_ext(const char *list, const char *name)
+{
+ const size_t n = strlen(name);
+ for (const char *p = list; p && (p = strstr(p, name)) != NULL; p += n) {
+ if ((p == list || p[-1] == ' ') && (p[n] == ' ' || p[n] == '\0')) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/* Xlib errors (BadMatch from a mismatched config, a destroyed window) end the
+ * process with the default handler: trap them around GLX calls, as GHOST
+ * does. */
+static int g_xerr = 0;
+static int xerr_handler(XDisplay *dpy, void *ev)
+{
+ (void)dpy;
+ (void)ev;
+ g_xerr = 1;
+ return 0;
+}
+
+static XErrHandler trap_begin(XDisplay *dpy)
+{
+ p_XSync(dpy, 0);
+ g_xerr = 0;
+ return p_XSetErrorHandler(xerr_handler);
+}
+
+/* 1 when an X error happened since trap_begin */
+static int trap_end(XDisplay *dpy, XErrHandler old)
+{
+ p_XSync(dpy, 0);
+ p_XSetErrorHandler(old);
+ return g_xerr;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Shaders (GLSL 330 translation of gpu/shaders/bui_ui.hlsl)
+ *
+ * The frame is stored top row first: vertices map pixel y straight to NDC
+ * (no flip), so gl_FragCoord is the same top-left-origin pixel center as
+ * HLSL's SV_Position and every formula below is the HLSL one unchanged.
+ * Present flips the frame onto the window.
+ * \{ */
+
+static const char *const k_vs_quad =
+ "#version 330 core\n"
+ "uniform vec2 to_ndc;\n"
+ "layout(location = 0) in vec4 a_rect;\n"
+ "layout(location = 1) in vec4 a_bounds;\n"
+ "layout(location = 2) in vec4 a_c0;\n"
+ "layout(location = 3) in vec4 a_c1;\n"
+ "layout(location = 4) in vec4 a_c2;\n"
+ "layout(location = 5) in vec4 a_c3;\n"
+ "layout(location = 6) in vec4 a_p;\n"
+ "layout(location = 7) in vec4 a_uv;\n"
+ "flat out vec4 v_rect, v_c0, v_c1, v_c2, v_c3, v_p, v_uv;\n"
+ "void main()\n"
+ "{\n"
+ " vec2 t = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));\n"
+ " vec2 xy = mix(a_bounds.xy, a_bounds.zw, t);\n"
+ " gl_Position = vec4(xy.x * to_ndc.x - 1.0, xy.y * to_ndc.y - 1.0, 0.0, 1.0);\n"
+ " v_rect = a_rect;\n"
+ " v_c0 = a_c0;\n"
+ " v_c1 = a_c1;\n"
+ " v_c2 = a_c2;\n"
+ " v_c3 = a_c3;\n"
+ " v_p = a_p;\n"
+ " v_uv = a_uv;\n"
+ "}\n";
+
+static const char *const k_fs_quad =
+ "#version 330 core\n"
+ "#define K_RECT 0\n"
+ "#define K_WIDGET 1\n"
+ "#define K_ELLIPSE 2\n"
+ "#define K_LINE 3\n"
+ "#define K_MASK 4\n"
+ "#define K_IMAGE 5\n"
+ "#define K_SHADOW 6\n"
+ "#define K_GRADIENT 7\n"
+ "#define K_HSV 8\n"
+ "#define K_SPHERE 9\n"
+ "#define K_SLUG 10\n"
+ "#define W_SHADE_H 1u\n"
+ "#define W_CHECKER 2u\n"
+ "#define W_LEGACY 4u\n"
+ "#define W_INNER 8u\n"
+ "uniform sampler2D mask_tex;\n"
+ "uniform sampler2D rgba_tex;\n"
+ "uniform sampler2D curve_tex;\n" /* Slug: (p1, p2), (p3, -) per curve */
+ "uniform usampler2D band_tex;\n" /* Slug: band headers (count, at), entries (curve) */
+ "flat in vec4 v_rect, v_c0, v_c1, v_c2, v_c3, v_p, v_uv;\n"
+ "layout(location = 0) out vec4 frag;\n"
+ "float sat(float x) { return clamp(x, 0.0, 1.0); }\n"
+ "vec2 sat(vec2 x) { return clamp(x, 0.0, 1.0); }\n"
+ "vec3 sat(vec3 x) { return clamp(x, 0.0, 1.0); }\n"
+ /* rounded box with a per-corner radius mask (gpu_raster.c sd_widget_box) */
+ "float sd_box(vec2 s, vec2 c, vec2 hb, float rad, uint corners)\n"
+ "{\n"
+ " vec2 p = s - c;\n"
+ " uint bit = p.y < 0.0 ? (p.x < 0.0 ? 1u : 2u) : (p.x < 0.0 ? 8u : 4u);\n"
+ " float r = (corners & bit) != 0u ? rad : 0.0;\n"
+ " vec2 q = abs(p) - (hb - r);\n"
+ " if (q.x <= 0.0 || q.y <= 0.0) {\n"
+ " return max(q.x, q.y) - r;\n"
+ " }\n"
+ " return length(q) - r;\n"
+ "}\n"
+ /* source-over of a straight color into a premultiplied accumulator */
+ "void over(inout vec4 acc, vec4 c, float cov)\n"
+ "{\n"
+ " float a = sat(c.a * cov);\n"
+ " acc.rgb = c.rgb * a + acc.rgb * (1.0 - a);\n"
+ " acc.a = a + acc.a * (1.0 - a);\n"
+ "}\n"
+ "vec4 premul(vec4 c, float cov)\n"
+ "{\n"
+ " float a = sat(c.a * cov);\n"
+ " return vec4(c.rgb * a, a);\n"
+ "}\n"
+ "vec3 hsv_to_rgb(float h, float s, float v)\n"
+ "{\n"
+ " h = h - floor(h);\n"
+ " float h6 = h * 6.0;\n"
+ " vec3 rgb = sat(vec3(abs(h6 - 3.0) - 1.0, 2.0 - abs(h6 - 2.0), 2.0 - abs(h6 - 4.0)));\n"
+ " return ((rgb - 1.0) * s + 1.0) * v;\n"
+ "}\n"
+ /* Slug glyph coverage, ported from Eric Lengyel's reference shaders
+ * (https://github.com/EricLengyel/Slug, MIT license):
+ * "Slug shader code Copyright 2017 by Eric Lengyel." */
+ "ivec2 slug_loc(uint i)\n"
+ "{\n"
+ " return ivec2(int(i & 4095u), int(i >> 12u));\n"
+ "}\n"
+ "uint slug_root_code(float y1, float y2, float y3)\n"
+ "{\n"
+ " uint i1 = floatBitsToUint(y1) >> 31u;\n"
+ " uint i2 = floatBitsToUint(y2) >> 30u;\n"
+ " uint i3 = floatBitsToUint(y3) >> 29u;\n"
+ " uint shift = (i2 & 2u) | (i1 & ~2u);\n"
+ " shift = (i3 & 4u) | (shift & ~4u);\n"
+ " return (0x2E74u >> shift) & 0x0101u;\n"
+ "}\n"
+ "vec2 slug_solve_h(vec4 p12, vec2 p3)\n"
+ "{\n"
+ " vec2 a = p12.xy - p12.zw * 2.0 + p3;\n"
+ " vec2 b = p12.xy - p12.zw;\n"
+ " float ra = 1.0 / a.y, rb = 0.5 / b.y;\n"
+ " float d = sqrt(max(b.y * b.y - a.y * p12.y, 0.0));\n"
+ " float t1 = (b.y - d) * ra, t2 = (b.y + d) * ra;\n"
+ " if (abs(a.y) < 1.0 / 65536.0) {\n"
+ " t1 = p12.y * rb;\n"
+ " t2 = t1;\n"
+ " }\n"
+ " return vec2((a.x * t1 - b.x * 2.0) * t1 + p12.x, (a.x * t2 - b.x * 2.0) * t2 + p12.x);\n"
+ "}\n"
+ "vec2 slug_solve_v(vec4 p12, vec2 p3)\n"
+ "{\n"
+ " vec2 a = p12.xy - p12.zw * 2.0 + p3;\n"
+ " vec2 b = p12.xy - p12.zw;\n"
+ " float ra = 1.0 / a.x, rb = 0.5 / b.x;\n"
+ " float d = sqrt(max(b.x * b.x - a.x * p12.x, 0.0));\n"
+ " float t1 = (b.x - d) * ra, t2 = (b.x + d) * ra;\n"
+ " if (abs(a.x) < 1.0 / 65536.0) {\n"
+ " t1 = p12.x * rb;\n"
+ " t2 = t1;\n"
+ " }\n"
+ " return vec2((a.y * t1 - b.y * 2.0) * t1 + p12.y, (a.y * t2 - b.y * 2.0) * t2 + p12.y);\n"
+ "}\n"
+ /* rc: sample position (font units); ppu: pixels per font unit;
+ * bt: band transform (y scale, y offset, x scale, x offset);
+ * at: first band header; nh, nv: band counts. */
+ "float slug_coverage(vec2 rc, float ppu, vec4 bt, uint at, int nh, int nv)\n"
+ "{\n"
+ " ivec2 bi = clamp(ivec2(int(rc.y * bt.x + bt.y), int(rc.x * bt.z + bt.w)), ivec2(0, 0),\n"
+ " ivec2(nh - 1, nv - 1));\n"
+ " float xcov = 0.0, xwgt = 0.0;\n"
+ " uvec2 hb = texelFetch(band_tex, slug_loc(at + uint(bi.x)), 0).xy;\n"
+ " for (uint i = 0u; i < hb.x; i++) {\n"
+ " ivec2 cl = slug_loc(texelFetch(band_tex, slug_loc(hb.y + i), 0).x);\n"
+ " vec4 p12 = texelFetch(curve_tex, cl, 0) - rc.xyxy;\n"
+ " vec2 p3 = texelFetch(curve_tex, ivec2(cl.x + 1, cl.y), 0).xy - rc;\n"
+ " if (max(max(p12.x, p12.z), p3.x) * ppu < -0.5) {\n"
+ " break;\n"
+ " }\n"
+ " uint code = slug_root_code(p12.y, p12.w, p3.y);\n"
+ " if (code != 0u) {\n"
+ " vec2 r = slug_solve_h(p12, p3) * ppu;\n"
+ " if ((code & 1u) != 0u) {\n"
+ " xcov += sat(r.x + 0.5);\n"
+ " xwgt = max(xwgt, sat(1.0 - abs(r.x) * 2.0));\n"
+ " }\n"
+ " if (code > 1u) {\n"
+ " xcov -= sat(r.y + 0.5);\n"
+ " xwgt = max(xwgt, sat(1.0 - abs(r.y) * 2.0));\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " float ycov = 0.0, ywgt = 0.0;\n"
+ " uvec2 vb = texelFetch(band_tex, slug_loc(at + uint(nh) + uint(bi.y)), 0).xy;\n"
+ " for (uint j = 0u; j < vb.x; j++) {\n"
+ " ivec2 cl = slug_loc(texelFetch(band_tex, slug_loc(vb.y + j), 0).x);\n"
+ " vec4 p12 = texelFetch(curve_tex, cl, 0) - rc.xyxy;\n"
+ " vec2 p3 = texelFetch(curve_tex, ivec2(cl.x + 1, cl.y), 0).xy - rc;\n"
+ " if (max(max(p12.y, p12.w), p3.y) * ppu < -0.5) {\n"
+ " break;\n"
+ " }\n"
+ " uint code = slug_root_code(p12.x, p12.z, p3.x);\n"
+ " if (code != 0u) {\n"
+ " vec2 r = slug_solve_v(p12, p3) * ppu;\n"
+ " if ((code & 1u) != 0u) {\n"
+ " ycov -= sat(r.x + 0.5);\n"
+ " ywgt = max(ywgt, sat(1.0 - abs(r.x) * 2.0));\n"
+ " }\n"
+ " if (code > 1u) {\n"
+ " ycov += sat(r.y + 0.5);\n"
+ " ywgt = max(ywgt, sat(1.0 - abs(r.y) * 2.0));\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " float cov = max(abs(xcov * xwgt + ycov * ywgt) / max(xwgt + ywgt, 1.0 / 65536.0),\n"
+ " min(abs(xcov), abs(ycov)));\n"
+ " return sat(cov);\n"
+ "}\n"
+ "vec4 shade(vec2 s)\n"
+ "{\n"
+ " int kind = int(v_p.x);\n"
+ " vec4 R = v_rect;\n"
+ " if (kind == K_RECT) {\n"
+ " vec2 px = s - 0.5;\n"
+ " vec2 lo = max(R.xy, px), hi = min(R.xy + R.zw, px + 1.0);\n"
+ " vec2 cv = sat(hi - lo);\n"
+ " return premul(v_c0, cv.x * cv.y);\n"
+ " }\n"
+ " if (kind == K_WIDGET) {\n"
+ " float x = R.x, y = R.y, w = R.z, h = R.w;\n"
+ " vec2 hb = vec2(w, h) * 0.5, c = R.xy + hb;\n"
+ " float rad = v_p.y, radi = v_p.z, px1 = v_p.w;\n"
+ " uint corners = uint(v_uv.x), flags = uint(v_uv.y);\n"
+ " float ow = v_uv.z;\n"
+ " vec4 acc = vec4(0.0);\n"
+ " float d = sd_box(s, c, hb, rad, corners);\n"
+ " float co = sat(0.5 - d);\n"
+ " if (v_c3.a > 0.0 && s.y > c.y) {\n"
+ " float de = sd_box(s - vec2(0.0, px1), c, hb, rad, corners);\n"
+ " float ec = sat(0.5 - de) - co;\n"
+ " if (ec > 0.0) {\n"
+ " over(acc, v_c3, ec);\n"
+ " }\n"
+ " }\n"
+ " if (co > 0.0) {\n"
+ " float ci, band, t;\n"
+ " if ((flags & W_LEGACY) != 0u) {\n"
+ " ci = co;\n"
+ " band = ow > 0.0 ? co - sat(0.5 - (d + ow)) : 0.0;\n"
+ " t = sat((s.y - y) / h);\n"
+ " }\n"
+ " else {\n"
+ " float di = sd_box(s, c, hb - px1, radi, corners);\n"
+ " ci = min(co, sat(0.5 - di));\n"
+ " band = co - ci;\n"
+ " t = (flags & W_SHADE_H) != 0u ? sat((s.x - (x + px1)) / max(1.0, w - 2.0 * px1)) :\n"
+ " sat((s.y - (y + px1)) / max(1.0, h - 2.0 * px1));\n"
+ " }\n"
+ " if ((flags & W_INNER) != 0u && ci > 0.0) {\n"
+ " if ((flags & W_CHECKER) != 0u) {\n"
+ " int cell = (int((s.x - x) / 8.0) + int((s.y - y) / 8.0)) & 1;\n"
+ " float g = cell != 0 ? 160.0 / 255.0 : 100.0 / 255.0;\n"
+ " over(acc, vec4(g, g, g, 1.0), ci);\n"
+ " }\n"
+ " over(acc, mix(v_c0, v_c1, t), ci);\n"
+ " }\n"
+ " if (v_c2.a > 0.0 && band > 0.0) {\n"
+ " over(acc, v_c2, band);\n"
+ " }\n"
+ " }\n"
+ " return acc;\n"
+ " }\n"
+ " if (kind == K_ELLIPSE) {\n"
+ " float lw = v_p.y;\n"
+ " vec2 dd = s - R.xy;\n"
+ " float dist;\n"
+ " if (abs(R.z - R.w) < 1e-3) {\n"
+ " dist = length(dd) - R.z;\n"
+ " }\n"
+ " else {\n"
+ " vec2 n = dd / R.zw;\n"
+ " float k = length(n);\n"
+ " float g = length(n / R.zw);\n"
+ " dist = g > 0.0 ? (k - 1.0) * k / g : -min(R.z, R.w);\n"
+ " }\n"
+ " float cov = lw > 0.0 ? sat(lw * 0.5 - abs(dist) + 0.5) : sat(0.5 - dist);\n"
+ " return premul(v_c0, cov);\n"
+ " }\n"
+ " if (kind == K_LINE) {\n"
+ " vec2 a = R.xy, vv = R.zw - R.xy;\n"
+ " vec2 wv = s - a;\n"
+ " float t = sat(dot(wv, vv) / dot(vv, vv));\n"
+ " float d = length(wv - vv * t) - v_p.y;\n"
+ " return premul(v_c0, sat(0.5 - d));\n"
+ " }\n"
+ " if (kind == K_MASK) {\n"
+ " ivec2 texel = ivec2(v_uv.xy) + ivec2(floor(s) - R.xy);\n"
+ " float cov = texelFetch(mask_tex, texel, 0).r;\n"
+ " return premul(v_c0, cov);\n"
+ " }\n"
+ " if (kind == K_SLUG) {\n"
+ /* rect: pen x, baseline y, pixels per font unit, italic shear */
+ " float ey = (R.y - s.y) / R.z;\n"
+ " float ex = (s.x - R.x) / R.z - R.w * ey;\n"
+ " float cov = slug_coverage(vec2(ex, ey), R.z, v_c1, uint(v_uv.x), int(v_uv.y), int(v_uv.z));\n"
+ /* same lift as the CPU glyph cache (gamma 1/1.45, like GDI's grayscale AA) */
+ " return premul(v_c0, pow(cov, 1.0 / 1.45));\n"
+ " }\n"
+ " if (kind == K_IMAGE) {\n"
+ " vec2 isz = v_uv.zw;\n"
+ " ivec2 sp = clamp(ivec2((s - R.xy) * isz / R.zw), ivec2(0, 0), ivec2(isz) - 1);\n"
+ " vec4 c = texelFetch(rgba_tex, ivec2(v_uv.xy) + sp, 0);\n"
+ " return premul(c, v_p.y);\n"
+ " }\n"
+ " if (kind == K_SHADOW) {\n"
+ " float rad = v_p.y, size = v_p.z, alpha = v_p.w;\n"
+ " vec2 hb = R.zw * 0.5;\n"
+ " vec2 c = R.xy + hb;\n"
+ " float d = sd_box(s, c + vec2(0.0, size * 0.25), hb, rad, 15u);\n"
+ " float dbox = sd_box(s, c, hb, rad, 15u);\n"
+ " if (dbox <= -0.5 || d >= size) {\n"
+ " return vec4(0.0);\n"
+ " }\n"
+ " float t = 1.0 - sat(d / size);\n"
+ " t = t * t * (3.0 - 2.0 * t);\n"
+ " return vec4(0.0, 0.0, 0.0, sat(t * alpha * sat(0.5 + dbox)));\n"
+ " }\n"
+ " if (kind == K_GRADIENT) {\n"
+ " vec2 uv = sat((s - R.xy) / R.zw);\n"
+ " vec4 left = mix(v_c0, v_c3, uv.y), right = mix(v_c1, v_c2, uv.y);\n"
+ " return premul(mix(left, right, uv.x), 1.0);\n"
+ " }\n"
+ " if (kind == K_HSV) {\n"
+ " vec2 dd = s - R.xy;\n"
+ " float dist = length(dd);\n"
+ " float cov = sat(R.z - dist + 0.5);\n"
+ " float hue = atan(dd.x, -dd.y) * 0.15915494309189535 + 0.5;\n"
+ " return premul(vec4(hsv_to_rgb(hue, min(dist / R.z, 1.0), R.w), 1.0), cov);\n"
+ " }\n"
+ " if (kind == K_SPHERE) {\n"
+ " vec2 n2 = vec2(s.x - R.x, -(s.y - R.y)) / R.z;\n"
+ " float d2 = dot(n2, n2);\n"
+ " float cov = sat((1.0 - sqrt(d2)) * R.z + 0.5);\n"
+ " vec3 n = vec3(n2, sqrt(max(0.0, 1.0 - d2)));\n"
+ " float diff = max(0.0, dot(n, v_c1.xyz));\n"
+ " float spec = max(0.0, dot(n, v_c2.xyz));\n"
+ " spec = pow(spec, 16.0);\n" /* the software raster squares 2x then takes ^4 */
+ " return premul(vec4(v_c0.rgb * (0.12 + 0.88 * diff) + 0.6 * spec, v_c0.a), cov);\n"
+ " }\n"
+ " return vec4(0.0);\n"
+ "}\n"
+ "void main()\n"
+ "{\n"
+ " frag = shade(gl_FragCoord.xy);\n" /* pixel center, top-left origin (see above) */
+ "}\n";
+
+/* per-vertex colored triangles (the BuiGpuSink seam), clipped per vertex */
+static const char *const k_vs_tri =
+ "#version 330 core\n"
+ "uniform vec2 to_ndc;\n"
+ "layout(location = 0) in vec2 a_pos;\n"
+ "layout(location = 1) in vec4 a_color;\n"
+ "layout(location = 2) in vec4 a_clip;\n"
+ "out vec4 v_color;\n"
+ "flat out vec4 v_clip;\n"
+ "void main()\n"
+ "{\n"
+ " gl_Position = vec4(a_pos.x * to_ndc.x - 1.0, a_pos.y * to_ndc.y - 1.0, 0.0, 1.0);\n"
+ " v_color = a_color;\n"
+ " v_clip = a_clip;\n"
+ "}\n";
+
+static const char *const k_fs_tri =
+ "#version 330 core\n"
+ "in vec4 v_color;\n"
+ "flat in vec4 v_clip;\n"
+ "layout(location = 0) out vec4 frag;\n"
+ "void main()\n"
+ "{\n"
+ " vec2 p = gl_FragCoord.xy;\n"
+ " if (p.x < v_clip.x || p.y < v_clip.y || p.x >= v_clip.z || p.y >= v_clip.w) {\n"
+ " discard;\n"
+ " }\n"
+ " float a = clamp(v_color.a, 0.0, 1.0);\n"
+ " frag = vec4(v_color.rgb * a, a);\n"
+ "}\n";
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name State
+ * \{ */
+
+# define SHELVES 128
+
+typedef struct Atlas {
+ int size;
+ int bpp; /* 1 (R8) or 4 (BGRA8) */
+ GLuint tex;
+ int shelf_y[SHELVES], shelf_h[SHELVES], shelf_x[SHELVES];
+ int nshelves, next_y;
+} Atlas;
+
+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
+
+# define SLUG_W 4096
+# define SLUG_H 64
+# define SLUG_MAP 8192 /* power of two */
+# define SLUG_MAP_FILL 6000
+# define SLUG_MAX_BANDS 16
+
+typedef struct SlugGlyph {
+ uint32_t key; /* (face + 1) << 16 | glyph; 0 = empty */
+ int ok;
+ float bbox[4], band[4];
+ int loc[4];
+} SlugGlyph;
+
+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;
+
+enum { API_GLX = 1, API_EGL = 2 };
+
+struct BuiGpu {
+ int state; /* 1 ready (creation is synchronous; failures return NULL) */
+
+ /* context */
+ int api;
+ XDisplay *xdpy;
+ int own_xdpy;
+ XID draw; /* GLX drawable: the window or the pbuffer */
+ XID pbuf; /* GLX pbuffer (offscreen) */
+ int onscreen;
+ GLXContext glx;
+ EGLDisplay edpy;
+ EGLContext egl;
+ EGLSurface esurf;
+ GLFuncs f;
+
+ GLuint prog_quad, prog_tri;
+ GLint ndc_quad, ndc_tri;
+ GLuint vao_quad, vao_tri;
+ GLuint ib, tb;
+ int max_tex;
+
+ GLuint fbo, target;
+ int tw, th;
+ int w, h; /* frame size */
+
+ Atlas mask, rgba;
+ Slot *mask_map, *img_map;
+ int mask_n, img_n;
+ unsigned mask_gen;
+
+ int slug; /* -1: off (unavailable), 0: not created yet, 1: ready */
+ GLuint curve_tex, band_tex;
+ SlugGlyph *slug_map;
+ int slug_n, curve_next, band_next;
+ unsigned slug_gen;
+
+ BuiGpuInst *inst;
+ int n_inst, cap_inst;
+ TriV *tv;
+ int n_tv, cap_tv;
+ Batch *b;
+ int n_b, cap_b;
+
+ int dmg[16][4];
+ int n_dmg, dmg_full;
+};
+
+# define GL(fn) (g->f.fn)
+
+/* Makes this renderer's context current on the calling thread. */
+static int make_current(BuiGpu *g)
+{
+ if (g->api == API_GLX) {
+ if (p_glXGetCurrentContext() == g->glx) {
+ return 1;
+ }
+ return p_glXMakeContextCurrent(g->xdpy, g->draw, g->draw, g->glx) != 0;
+ }
+ if (g->api == API_EGL) {
+ if (p_eglGetCurrentContext() == g->egl) {
+ return 1;
+ }
+ return p_eglMakeCurrent(g->edpy, g->esurf, g->esurf, g->egl) != 0;
+ }
+ return 0;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Context creation
+ * \{ */
+
+static ProcFn get_proc(BuiGpu *g, const char *name)
+{
+ ProcFn fn = NULL;
+ if (g->api == API_GLX) {
+ fn = p_glXGetProcAddressARB((const GLubyte *)name);
+ }
+ else {
+ fn = p_eglGetProcAddress(name);
+ }
+ if (!fn && g_libgl) {
+ fn = (ProcFn)dlsym(g_libgl, name);
+ }
+ return fn;
+}
+
+static int gl_resolve(BuiGpu *g)
+{
+# define GLF_LOAD(ret, name, args) \
+ if (!(g->f.name = (ret(*) args)get_proc(g, #name))) { \
+ return fail("resolving " #name); \
+ }
+ GL_FUNCS(GLF_LOAD)
+# undef GLF_LOAD
+ return 1;
+}
+
+/* GLX: a core 3.3 context on `window` (0: on a 1x1 pbuffer). */
+static int glx_create(BuiGpu *g, XDisplay *dpy, XID window)
+{
+ if (!x11_load() || !glx_load()) {
+ return 0;
+ }
+ if (!dpy) {
+ dpy = p_XOpenDisplay(NULL);
+ if (!dpy) {
+ return fail("XOpenDisplay");
+ }
+ g->own_xdpy = 1;
+ }
+ g->xdpy = dpy;
+ int major = 0, minor = 0;
+ if (!p_glXQueryVersion(dpy, &major, &minor) || major < 1 || (major == 1 && minor < 3)) {
+ return fail("GLX 1.3");
+ }
+ const int scr = p_XDefaultScreen(dpy);
+ const char *ext = p_glXQueryExtensionsString(dpy, scr);
+ if (!has_ext(ext, "GLX_ARB_create_context") ||
+ !has_ext(ext, "GLX_ARB_create_context_profile"))
+ {
+ return fail("GLX_ARB_create_context_profile");
+ }
+ typedef GLXContext (*CreateCtxFn)(XDisplay *, GLXFBConfig, GLXContext, int, const int *);
+ CreateCtxFn create = (CreateCtxFn)p_glXGetProcAddressARB(
+ (const GLubyte *)"glXCreateContextAttribsARB");
+ if (!create) {
+ return fail("glXCreateContextAttribsARB");
+ }
+ const int cfg_attr[] = {GLX_X_RENDERABLE,
+ 1,
+ GLX_DRAWABLE_TYPE,
+ window ? GLX_WINDOW_BIT : GLX_PBUFFER_BIT,
+ GLX_RENDER_TYPE,
+ GLX_RGBA_BIT,
+ GLX_X_VISUAL_TYPE,
+ GLX_TRUE_COLOR,
+ GLX_RED_SIZE,
+ 8,
+ GLX_GREEN_SIZE,
+ 8,
+ GLX_BLUE_SIZE,
+ 8,
+ GLX_DOUBLEBUFFER,
+ window ? 1 : 0,
+ 0};
+ int n = 0;
+ GLXFBConfig *cfgs = p_glXChooseFBConfig(dpy, scr, cfg_attr, &n);
+ if (!cfgs || n <= 0) {
+ if (cfgs) {
+ p_XFree(cfgs);
+ }
+ return fail("glXChooseFBConfig");
+ }
+ /* the kit's windows use the default visual: take the config made for it */
+ GLXFBConfig cfg = cfgs[0];
+ if (window) {
+ const unsigned long want = p_XVisualIDFromVisual(p_XDefaultVisual(dpy, scr));
+ for (int i = 0; i < n; i++) {
+ int vid = 0;
+ if (p_glXGetFBConfigAttrib(dpy, cfgs[i], GLX_VISUAL_ID, &vid) == 0 &&
+ (unsigned long)vid == want)
+ {
+ cfg = cfgs[i];
+ break;
+ }
+ }
+ }
+ const int ctx_attr[] = {GLX_CONTEXT_MAJOR_VERSION_ARB,
+ 3,
+ GLX_CONTEXT_MINOR_VERSION_ARB,
+ 3,
+ GLX_CONTEXT_PROFILE_MASK_ARB,
+ GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
+ 0};
+ XErrHandler old = trap_begin(dpy);
+ g->glx = create(dpy, cfg, NULL, 1, ctx_attr);
+ if (g->glx && !window) {
+ const int pb_attr[] = {GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, 0};
+ g->pbuf = p_glXCreatePbuffer(dpy, cfg, pb_attr);
+ }
+ g->draw = window ? window : g->pbuf;
+ int ok = g->glx && g->draw && p_glXMakeContextCurrent(dpy, g->draw, g->draw, g->glx);
+ if (trap_end(dpy, old)) {
+ ok = 0;
+ }
+ p_XFree(cfgs);
+ if (!ok) {
+ return fail("GLX context");
+ }
+ g->api = API_GLX;
+ g->onscreen = window != 0;
+ if (window) { /* present doesn't wait for vblank, like the D3D Present(0) */
+ if (has_ext(ext, "GLX_EXT_swap_control")) {
+ typedef void (*SwapEXT)(XDisplay *, XID, int);
+ SwapEXT fn = (SwapEXT)p_glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalEXT");
+ if (fn) {
+ old = trap_begin(dpy);
+ fn(dpy, window, 0);
+ trap_end(dpy, old);
+ }
+ }
+ else if (has_ext(ext, "GLX_MESA_swap_control")) {
+ typedef int (*SwapMESA)(unsigned);
+ SwapMESA fn = (SwapMESA)p_glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalMESA");
+ if (fn) {
+ fn(0);
+ }
+ }
+ }
+ return 1;
+}
+
+/* EGL on one display: a core 3.3 context, surfaceless or on a 1x1 pbuffer. */
+static int egl_try(BuiGpu *g, EGLDisplay dpy)
+{
+ EGLint major = 0, minor = 0;
+ if (!dpy || !p_eglInitialize(dpy, &major, &minor)) {
+ return 0;
+ }
+ if (major < 1 || (major == 1 && minor < 4) || !p_eglBindAPI(EGL_OPENGL_API)) {
+ return 0;
+ }
+ const int surfaceless = has_ext(p_eglQueryString(dpy, EGL_EXTENSIONS),
+ "EGL_KHR_surfaceless_context");
+ const EGLint cfg_attr[] = {EGL_SURFACE_TYPE,
+ surfaceless ? 0 : EGL_PBUFFER_BIT,
+ EGL_RENDERABLE_TYPE,
+ EGL_OPENGL_BIT,
+ EGL_RED_SIZE,
+ 8,
+ EGL_GREEN_SIZE,
+ 8,
+ EGL_BLUE_SIZE,
+ 8,
+ EGL_NONE};
+ EGLConfig cfg = NULL;
+ EGLint n = 0;
+ if (!p_eglChooseConfig(dpy, cfg_attr, &cfg, 1, &n) || n < 1) {
+ return 0;
+ }
+ const EGLint ctx_attr[] = {EGL_CONTEXT_MAJOR_VERSION,
+ 3,
+ EGL_CONTEXT_MINOR_VERSION,
+ 3,
+ EGL_CONTEXT_OPENGL_PROFILE_MASK,
+ EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
+ EGL_NONE};
+ EGLContext ctx = p_eglCreateContext(dpy, cfg, NULL, ctx_attr);
+ if (!ctx) {
+ return 0;
+ }
+ EGLSurface surf = NULL;
+ if (!surfaceless) {
+ const EGLint pb_attr[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
+ surf = p_eglCreatePbufferSurface(dpy, cfg, pb_attr);
+ if (!surf) {
+ p_eglDestroyContext(dpy, ctx);
+ return 0;
+ }
+ }
+ if (!p_eglMakeCurrent(dpy, surf, surf, ctx)) {
+ if (surf) {
+ p_eglDestroySurface(dpy, surf);
+ }
+ p_eglDestroyContext(dpy, ctx);
+ return 0;
+ }
+ /* the display stays initialized: EGL displays are per process and
+ * terminating one would pull it from under other users */
+ g->api = API_EGL;
+ g->edpy = dpy;
+ g->egl = ctx;
+ g->esurf = surf;
+ return 1;
+}
+
+static int egl_create(BuiGpu *g)
+{
+ if (!egl_load()) {
+ return 0;
+ }
+ /* BUI_GPU_EGL=default|surfaceless picks one; else headless first */
+ const char *pick = getenv("BUI_GPU_EGL");
+ const int want_default = pick && !strcmp(pick, "default");
+ const int want_surfaceless = pick && !strcmp(pick, "surfaceless");
+ const char *cext = p_eglQueryString(NULL, EGL_EXTENSIONS); /* client extensions */
+ if (!want_default && has_ext(cext, "EGL_MESA_platform_surfaceless")) {
+ typedef EGLDisplay (*GetPlatformFn)(EGLenum, void *, const EGLint *);
+ GetPlatformFn get = NULL;
+ if (has_ext(cext, "EGL_EXT_platform_base")) {
+ get = (GetPlatformFn)p_eglGetProcAddress("eglGetPlatformDisplayEXT");
+ }
+ if (get && egl_try(g, get(EGL_PLATFORM_SURFACELESS_MESA, NULL, NULL))) {
+ return 1;
+ }
+ }
+ if (!want_surfaceless && egl_try(g, p_eglGetDisplay(NULL))) {
+ return 1;
+ }
+ return fail("EGL context");
+}
+
+static GLuint compile(BuiGpu *g, GLenum type, const char *src)
+{
+ const GLuint sh = GL(glCreateShader)(type);
+ GL(glShaderSource)(sh, 1, &src, NULL);
+ GL(glCompileShader)(sh);
+ GLint ok = 0;
+ GL(glGetShaderiv)(sh, GL_COMPILE_STATUS, &ok);
+ if (!ok) {
+ if (debug_on()) {
+ char log[2048] = {0};
+ GL(glGetShaderInfoLog)(sh, sizeof(log) - 1, NULL, log);
+ fprintf(stderr, "bui gpu (gl): shader:\n%s\n", log);
+ }
+ GL(glDeleteShader)(sh);
+ return 0;
+ }
+ return sh;
+}
+
+static GLuint program(BuiGpu *g, const char *vs_src, const char *fs_src)
+{
+ const GLuint vs = compile(g, GL_VERTEX_SHADER, vs_src);
+ const GLuint fs = vs ? compile(g, GL_FRAGMENT_SHADER, fs_src) : 0;
+ if (!fs) {
+ if (vs) {
+ GL(glDeleteShader)(vs);
+ }
+ return 0;
+ }
+ const GLuint p = GL(glCreateProgram)();
+ GL(glAttachShader)(p, vs);
+ GL(glAttachShader)(p, fs);
+ GL(glLinkProgram)(p);
+ GL(glDeleteShader)(vs);
+ GL(glDeleteShader)(fs);
+ GLint ok = 0;
+ GL(glGetProgramiv)(p, GL_LINK_STATUS, &ok);
+ if (!ok) {
+ if (debug_on()) {
+ char log[2048] = {0};
+ GL(glGetProgramInfoLog)(p, sizeof(log) - 1, NULL, log);
+ fprintf(stderr, "bui gpu (gl): link:\n%s\n", log);
+ }
+ GL(glDeleteProgram)(p);
+ return 0;
+ }
+ return p;
+}
+
+static GLuint tex_create(BuiGpu *g, GLint ifmt, int w, int h, GLenum fmt, GLenum type)
+{
+ GLuint t = 0;
+ GL(glGenTextures)(1, &t);
+ GL(glBindTexture)(GL_TEXTURE_2D, t);
+ /* nearest, no mips: texelFetch needs a complete texture */
+ GL(glTexParameteri)(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ GL(glTexParameteri)(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ GL(glTexParameteri)(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ GL(glTexParameteri)(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ while (GL(glGetError)() != GL_NO_ERROR) {
+ }
+ GL(glTexImage2D)(GL_TEXTURE_2D, 0, ifmt, w, h, 0, fmt, type, NULL);
+ if (GL(glGetError)() != GL_NO_ERROR) {
+ GL(glDeleteTextures)(1, &t);
+ return 0;
+ }
+ return t;
+}
+
+static int atlas_create(BuiGpu *g, Atlas *a, int size, int bpp)
+{
+ memset(a, 0, sizeof(*a));
+ a->size = size;
+ a->bpp = bpp;
+ a->tex = bpp == 1 ? tex_create(g, GL_R8, size, size, GL_RED, GL_UNSIGNED_BYTE) :
+ tex_create(g, GL_RGBA8, size, size, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV);
+ return a->tex != 0;
+}
+
+static int device_init(BuiGpu *g)
+{
+ if (!gl_resolve(g)) {
+ return 0;
+ }
+ const char *ver = (const char *)GL(glGetString)(GL_VERSION);
+ int major = 0, minor = 0;
+ if (!ver || sscanf(ver, "%d.%d", &major, &minor) != 2 || major < 3 ||
+ (major == 3 && minor < 3))
+ {
+ return fail("OpenGL 3.3");
+ }
+ if (debug_on()) {
+ fprintf(stderr, "bui gpu (gl): %s, %s | %s | %s\n", g->api == API_GLX ? "GLX" : "EGL",
+ (const char *)GL(glGetString)(GL_VENDOR), (const char *)GL(glGetString)(GL_RENDERER),
+ ver);
+ }
+ GL(glGetIntegerv)(GL_MAX_TEXTURE_SIZE, &g->max_tex);
+ if (g->max_tex < 2048) {
+ return fail("2048 px textures");
+ }
+ g->prog_quad = program(g, k_vs_quad, k_fs_quad);
+ g->prog_tri = program(g, k_vs_tri, k_fs_tri);
+ if (!g->prog_quad || !g->prog_tri) {
+ return fail("shaders");
+ }
+ g->ndc_quad = GL(glGetUniformLocation)(g->prog_quad, "to_ndc");
+ g->ndc_tri = GL(glGetUniformLocation)(g->prog_tri, "to_ndc");
+ GL(glUseProgram)(g->prog_quad);
+ const char *samplers[4] = {"mask_tex", "rgba_tex", "curve_tex", "band_tex"};
+ for (int i = 0; i < 4; i++) {
+ GL(glUniform1i)(GL(glGetUniformLocation)(g->prog_quad, samplers[i]), i);
+ }
+ GL(glUseProgram)(0);
+
+ GL(glGenBuffers)(1, &g->ib);
+ GL(glGenBuffers)(1, &g->tb);
+ GL(glGenVertexArrays)(1, &g->vao_quad);
+ GL(glGenVertexArrays)(1, &g->vao_tri);
+ /* instances: 8 float4 attributes, one step per instance (pointers are set
+ * per batch: GL 3.3 has no base instance) */
+ GL(glBindVertexArray)(g->vao_quad);
+ GL(glBindBuffer)(GL_ARRAY_BUFFER, g->ib);
+ for (GLuint k = 0; k < 8; k++) {
+ GL(glEnableVertexAttribArray)(k);
+ GL(glVertexAttribDivisor)(k, 1);
+ }
+ GL(glBindVertexArray)(g->vao_tri);
+ GL(glBindBuffer)(GL_ARRAY_BUFFER, g->tb);
+ for (GLuint k = 0; k < 3; k++) {
+ GL(glEnableVertexAttribArray)(k);
+ }
+ GL(glVertexAttribPointer)(0, 2, GL_FLOAT, GL_FALSE, sizeof(TriV), (const void *)offsetof(TriV, x));
+ GL(glVertexAttribPointer)(1, 4, GL_FLOAT, GL_FALSE, sizeof(TriV), (const void *)offsetof(TriV, c));
+ GL(glVertexAttribPointer)(2, 4, GL_FLOAT, GL_FALSE, sizeof(TriV),
+ (const void *)offsetof(TriV, clip));
+ GL(glBindVertexArray)(0);
+
+ GL(glDisable)(GL_DEPTH_TEST);
+ GL(glDisable)(GL_CULL_FACE);
+ GL(glDisable)(GL_SCISSOR_TEST);
+ GL(glDisable)(GL_DITHER);
+ GL(glDisable)(GL_FRAMEBUFFER_SRGB);
+ GL(glEnable)(GL_BLEND);
+ GL(glBlendFunc)(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); /* premultiplied, color and alpha */
+ GL(glGetError)(); /* GL_FRAMEBUFFER_SRGB may be unknown: not an error that matters */
+
+ if (!atlas_create(g, &g->mask, 2048, 1)) {
+ return fail("atlas");
+ }
+ return 1;
+}
+
+static void context_free(BuiGpu *g)
+{
+ /* destroying the context frees its objects; the window may already be gone,
+ * so nothing is drawn or made current here */
+ if (g->xdpy && (g->glx || g->pbuf)) {
+ XErrHandler old = trap_begin(g->xdpy);
+ if (g->glx && p_glXGetCurrentContext() == g->glx) {
+ p_glXMakeContextCurrent(g->xdpy, 0, 0, NULL);
+ }
+ if (g->glx) {
+ p_glXDestroyContext(g->xdpy, g->glx);
+ }
+ if (g->pbuf) {
+ p_glXDestroyPbuffer(g->xdpy, g->pbuf);
+ }
+ trap_end(g->xdpy, old);
+ }
+ if (g->egl) {
+ if (p_eglGetCurrentContext() == g->egl) {
+ p_eglMakeCurrent(g->edpy, NULL, NULL, NULL);
+ }
+ if (g->esurf) {
+ p_eglDestroySurface(g->edpy, g->esurf);
+ }
+ p_eglDestroyContext(g->edpy, g->egl);
+ }
+ if (g->own_xdpy && g->xdpy) {
+ p_XCloseDisplay(g->xdpy);
+ }
+ g->glx = NULL;
+ g->egl = NULL;
+ g->pbuf = 0;
+ g->xdpy = NULL;
+ g->api = 0;
+}
+
+BuiGpu *bui_gpu_create(void *handle)
+{
+ BuiGpu *g = (BuiGpu *)calloc(1, sizeof(BuiGpu));
+ if (!g) {
+ return NULL;
+ }
+ g->mask_map = (Slot *)calloc(MASK_MAP, sizeof(Slot));
+ g->img_map = (Slot *)calloc(IMG_MAP, sizeof(Slot));
+ int ok = g->mask_map && g->img_map;
+ if (ok) {
+ if (handle) { /* a window: GLX on the host's connection */
+ const BuiGpuX11Window *xw = (const BuiGpuX11Window *)handle;
+ ok = xw->window && glx_create(g, xw->display, (XID)xw->window);
+ }
+ else { /* offscreen: EGL, else a GLX pbuffer */
+ ok = egl_create(g);
+ if (!ok) {
+ context_free(g);
+ ok = glx_create(g, NULL, 0);
+ }
+ }
+ }
+ ok = ok && device_init(g);
+ if (!ok) {
+ bui_gpu_free(g);
+ return NULL;
+ }
+ g->state = 1;
+ return g;
+}
+
+int bui_gpu_state(BuiGpu *g, int wait)
+{
+ (void)wait; /* created synchronously: never pending */
+ return g->state;
+}
+
+void bui_gpu_free(BuiGpu *g)
+{
+ if (!g) {
+ return;
+ }
+ context_free(g);
+ free(g->inst);
+ free(g->tv);
+ free(g->b);
+ free(g->mask_map);
+ free(g->img_map);
+ free(g->slug_map);
+ free(g);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Atlases (shelf packing, as gpu_d3d11.c)
+ * \{ */
+
+static void atlas_clear(Atlas *a)
+{
+ a->nshelves = 0;
+ a->next_y = 0;
+}
+
+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;
+ 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)
+{
+ if (!make_current(g)) {
+ return;
+ }
+ GL(glBindTexture)(GL_TEXTURE_2D, a->tex);
+ GL(glPixelStorei)(GL_UNPACK_ALIGNMENT, 1);
+ GL(glPixelStorei)(GL_UNPACK_ROW_LENGTH, pitch / a->bpp);
+ if (a->bpp == 1) {
+ GL(glTexSubImage2D)(GL_TEXTURE_2D, 0, x, y, w, h, GL_RED, GL_UNSIGNED_BYTE, data);
+ }
+ else { /* 0xAARRGGBB words: BGRA bytes, on any endianness */
+ GL(glTexSubImage2D)(GL_TEXTURE_2D, 0, x, y, w, h, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, data);
+ }
+ GL(glPixelStorei)(GL_UNPACK_ROW_LENGTH, 0);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \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) {
+ 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);
+ 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;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Slug glyphs (same data layout as gpu_d3d11.c)
+ * \{ */
+
+int bui_gpu_slug_on(BuiGpu *g)
+{
+ if (g->slug == 0) {
+ g->slug = -1;
+ if (g->max_tex >= SLUG_W && make_current(g) &&
+ (g->curve_tex = tex_create(g, GL_RGBA32F, SLUG_W, SLUG_H, GL_RGBA, GL_FLOAT)) != 0 &&
+ (g->band_tex = tex_create(g, GL_RG32UI, SLUG_W, SLUG_H, GL_RG_INTEGER, GL_UNSIGNED_INT)) !=
+ 0 &&
+ (g->slug_map = (SlugGlyph *)calloc(SLUG_MAP, sizeof(SlugGlyph))) != NULL)
+ {
+ g->slug = 1;
+ }
+ }
+ return g->slug > 0;
+}
+
+static void slug_reset(BuiGpu *g)
+{
+ flush(g);
+ memset(g->slug_map, 0, sizeof(SlugGlyph) * SLUG_MAP);
+ g->slug_n = g->curve_next = g->band_next = 0;
+}
+
+/* Uploads `count` texels at linear index `at`, row by row. */
+static void slug_upload(BuiGpu *g, GLuint tex, int band, int at, const void *data, int count,
+ int texel)
+{
+ if (!make_current(g)) {
+ return;
+ }
+ GL(glBindTexture)(GL_TEXTURE_2D, tex);
+ GL(glPixelStorei)(GL_UNPACK_ALIGNMENT, 4);
+ GL(glPixelStorei)(GL_UNPACK_ROW_LENGTH, 0);
+ const char *p = (const char *)data;
+ while (count > 0) {
+ const int x = at % SLUG_W, y = at / SLUG_W;
+ const int n = count < SLUG_W - x ? count : SLUG_W - x;
+ if (band) {
+ GL(glTexSubImage2D)(GL_TEXTURE_2D, 0, x, y, n, 1, GL_RG_INTEGER, GL_UNSIGNED_INT, p);
+ }
+ else {
+ GL(glTexSubImage2D)(GL_TEXTURE_2D, 0, x, y, n, 1, GL_RGBA, GL_FLOAT, p);
+ }
+ p += (size_t)n * texel;
+ at += n;
+ count -= n;
+ }
+}
+
+typedef struct SlugSort {
+ float key;
+ uint32_t curve;
+} SlugSort;
+
+static int slug_cmp(const void *a, const void *b)
+{
+ const float ka = ((const SlugSort *)a)->key, kb = ((const SlugSort *)b)->key;
+ return ka < kb ? 1 : ka > kb ? -1 : 0; /* descending */
+}
+
+static float min3(float a, float b, float c)
+{
+ return a < b ? (a < c ? a : c) : (b < c ? b : c);
+}
+static float max3(float a, float b, float c)
+{
+ return a > b ? (a > c ? a : c) : (b > c ? b : c);
+}
+
+static int slug_build(BuiGpu *g, SlugGlyph *sg, const float *cv, int n, const float bb[4])
+{
+ const int nb = n < 8 ? 1 : (n / 4 < SLUG_MAX_BANDS ? n / 4 : SLUG_MAX_BANDS);
+ const float w = bb[2] - bb[0] > 1.0f ? bb[2] - bb[0] : 1.0f;
+ const float h = bb[3] - bb[1] > 1.0f ? bb[3] - bb[1] : 1.0f;
+ const float hs = (float)nb / h, vs = (float)nb / w;
+ const float eps = 1.0f / 1024.0f * (w > h ? w : h);
+
+ const int max_entries = 2 * nb * n;
+ const int need_band = 2 * nb + max_entries, need_curve = 2 * n;
+ if (need_curve > SLUG_W * SLUG_H / 4 || need_band > SLUG_W * SLUG_H / 4) {
+ return 0;
+ }
+ if (g->curve_next + need_curve > SLUG_W * SLUG_H || g->band_next + need_band > SLUG_W * SLUG_H ||
+ g->slug_n >= SLUG_MAP_FILL)
+ {
+ return -1;
+ }
+ float *ct = (float *)malloc(sizeof(float) * 8 * (size_t)n);
+ uint32_t *bt = (uint32_t *)malloc(sizeof(uint32_t) * 2 * (size_t)need_band);
+ SlugSort *tmp = (SlugSort *)malloc(sizeof(SlugSort) * (size_t)n);
+ if (!ct || !bt || !tmp) {
+ free(ct);
+ free(bt);
+ free(tmp);
+ return 0;
+ }
+ const int cbase = g->curve_next;
+ for (int i = 0; i < n; i++) {
+ const float *q = cv + 6 * i;
+ float *t = ct + 8 * i;
+ t[0] = q[0];
+ t[1] = q[1];
+ t[2] = q[2];
+ t[3] = q[3];
+ t[4] = q[4];
+ t[5] = q[5];
+ t[6] = t[7] = 0.0f;
+ }
+ const int bbase = g->band_next;
+ int at = 2 * nb;
+ for (int dir = 0; dir < 2; dir++) {
+ for (int b = 0; b < nb; b++) {
+ const float s = dir == 0 ? hs : vs, o = dir == 0 ? bb[1] : bb[0];
+ const float lo = o + (float)b / s - eps, hi = o + (float)(b + 1) / s + eps;
+ int m = 0;
+ for (int i = 0; i < n; i++) {
+ const float *q = cv + 6 * i;
+ const float a0 = dir == 0 ? q[1] : q[0], a1 = dir == 0 ? q[3] : q[2],
+ a2 = dir == 0 ? q[5] : q[4];
+ const float amin = min3(a0, a1, a2), amax = max3(a0, a1, a2);
+ if (amax < lo || amin > hi || (a0 == a1 && a1 == a2)) {
+ continue;
+ }
+ tmp[m].key = dir == 0 ? max3(q[0], q[2], q[4]) : max3(q[1], q[3], q[5]);
+ tmp[m].curve = (uint32_t)(cbase + 2 * i);
+ m++;
+ }
+ qsort(tmp, (size_t)m, sizeof(SlugSort), slug_cmp);
+ const int hdr = dir * nb + b;
+ bt[2 * hdr] = (uint32_t)m;
+ bt[2 * hdr + 1] = (uint32_t)(bbase + at);
+ for (int k = 0; k < m; k++) {
+ bt[2 * (at + k)] = tmp[k].curve;
+ bt[2 * (at + k) + 1] = 0;
+ }
+ at += m;
+ }
+ }
+ slug_upload(g, g->curve_tex, 0, cbase, ct, 2 * n, 16);
+ slug_upload(g, g->band_tex, 1, bbase, bt, at, 8);
+ g->curve_next += 2 * n;
+ g->band_next += at;
+ free(ct);
+ free(bt);
+ free(tmp);
+ memcpy(sg->bbox, bb, sizeof(float[4]));
+ sg->band[0] = hs;
+ sg->band[1] = -bb[1] * hs;
+ sg->band[2] = vs;
+ sg->band[3] = -bb[0] * vs;
+ sg->loc[0] = bbase;
+ sg->loc[1] = nb;
+ sg->loc[2] = nb;
+ sg->loc[3] = 0;
+ sg->ok = 1;
+ return 1;
+}
+
+int bui_gpu_slug_glyph(BuiGpu *g, int face, int glyph, unsigned gen, float r_bbox[4],
+ float r_band[4], int r_loc[4])
+{
+ if (g->slug <= 0 || face < 0 || face > 0x7ffe || glyph < 0 || glyph > 0xffff) {
+ return 0;
+ }
+ if (gen != g->slug_gen) {
+ g->slug_gen = gen;
+ slug_reset(g);
+ }
+ const uint32_t key = ((uint32_t)(face + 1) << 16) | (uint32_t)glyph;
+ uint32_t idx = (key * 2654435761u) >> 19 & (SLUG_MAP - 1);
+ SlugGlyph *sg;
+ for (;;) {
+ sg = &g->slug_map[idx];
+ if (sg->key == 0 || sg->key == key) {
+ break;
+ }
+ idx = (idx + 1) & (SLUG_MAP - 1);
+ }
+ if (sg->key == 0) {
+ float *cv = NULL;
+ int n = 0;
+ float bb[4];
+ sg->ok = 0;
+ if (bui_text_glyph_outline(face, glyph, &cv, &n, bb)) {
+ int got = slug_build(g, sg, cv, n, bb);
+ if (got < 0) {
+ slug_reset(g);
+ free(cv);
+ return bui_gpu_slug_glyph(g, face, glyph, gen, r_bbox, r_band, r_loc);
+ }
+ }
+ free(cv);
+ sg->key = key;
+ g->slug_n++;
+ }
+ if (!sg->ok) {
+ return 0;
+ }
+ memcpy(r_bbox, sg->bbox, sizeof(float[4]));
+ memcpy(r_band, sg->band, sizeof(float[4]));
+ memcpy(r_loc, sg->loc, sizeof(int[4]));
+ 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 && (!make_current(g) || !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 */
+ }
+ 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;
+ }
+ int *r = g->dmg[g->n_dmg++];
+ r[0] = x;
+ r[1] = y;
+ r[2] = x + w;
+ r[3] = y + h;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Drawing + present
+ * \{ */
+
+static int ensure_target(BuiGpu *g)
+{
+ if (g->target && g->tw == g->w && g->th == g->h) {
+ return 1;
+ }
+ if (g->target) {
+ GL(glDeleteTextures)(1, &g->target);
+ g->target = 0;
+ }
+ if (!g->fbo) {
+ GL(glGenFramebuffers)(1, &g->fbo);
+ }
+ if (g->w > g->max_tex || g->h > g->max_tex) {
+ return 0;
+ }
+ g->target = tex_create(g, GL_RGBA8, g->w, g->h, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV);
+ if (!g->target) {
+ return 0;
+ }
+ GL(glBindFramebuffer)(GL_FRAMEBUFFER, g->fbo);
+ GL(glFramebufferTexture2D)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g->target, 0);
+ if (GL(glCheckFramebufferStatus)(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
+ GL(glDeleteTextures)(1, &g->target);
+ g->target = 0;
+ return 0;
+ }
+ g->tw = g->w;
+ g->th = g->h;
+ GL(glViewport)(0, 0, g->tw, g->th);
+ GL(glClearColor)(0, 0, 0, 1);
+ GL(glClear)(GL_COLOR_BUFFER_BIT);
+ g->dmg_full = 1;
+ return 1;
+}
+
+static void flush(BuiGpu *g)
+{
+ if (g->n_b == 0) {
+ return;
+ }
+ if (!make_current(g) || !ensure_target(g)) {
+ g->n_b = g->n_inst = g->n_tv = 0;
+ return;
+ }
+ GL(glBindFramebuffer)(GL_FRAMEBUFFER, g->fbo);
+ GL(glViewport)(0, 0, g->tw, g->th);
+ /* orphaned each flush: draws already queued keep their data */
+ if (g->n_inst) {
+ GL(glBindBuffer)(GL_ARRAY_BUFFER, g->ib);
+ GL(glBufferData)(GL_ARRAY_BUFFER, (GLsizeiptr)(sizeof(BuiGpuInst) * (size_t)g->n_inst),
+ g->inst, GL_STREAM_DRAW);
+ }
+ if (g->n_tv) {
+ GL(glBindBuffer)(GL_ARRAY_BUFFER, g->tb);
+ GL(glBufferData)(GL_ARRAY_BUFFER, (GLsizeiptr)(sizeof(TriV) * (size_t)g->n_tv), g->tv,
+ GL_STREAM_DRAW);
+ }
+ const GLuint tex[4] = {g->mask.tex, g->rgba.tex, g->curve_tex, g->band_tex};
+ for (int i = 0; i < 4; i++) {
+ GL(glActiveTexture)(GL_TEXTURE0 + (GLenum)i);
+ GL(glBindTexture)(GL_TEXTURE_2D, tex[i]);
+ }
+ GL(glActiveTexture)(GL_TEXTURE0);
+ const float sx = 2.0f / (float)g->tw, sy = 2.0f / (float)g->th;
+
+ 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;
+ if (!b->tri) {
+ GL(glUseProgram)(g->prog_quad);
+ GL(glUniform2f)(g->ndc_quad, sx, sy);
+ GL(glBindVertexArray)(g->vao_quad);
+ GL(glBindBuffer)(GL_ARRAY_BUFFER, g->ib);
+ }
+ else {
+ GL(glUseProgram)(g->prog_tri);
+ GL(glUniform2f)(g->ndc_tri, sx, sy);
+ GL(glBindVertexArray)(g->vao_tri);
+ }
+ }
+ if (!b->tri) {
+ const size_t base = sizeof(BuiGpuInst) * (size_t)b->first;
+ for (GLuint k = 0; k < 8; k++) {
+ GL(glVertexAttribPointer)(k, 4, GL_FLOAT, GL_FALSE, sizeof(BuiGpuInst),
+ (const void *)(base + 16 * k));
+ }
+ GL(glDrawArraysInstanced)(GL_TRIANGLE_STRIP, 0, 4, b->count);
+ }
+ else {
+ GL(glDrawArrays)(GL_TRIANGLES, b->first, b->count);
+ }
+ }
+ GL(glBindVertexArray)(0);
+ g->n_b = g->n_inst = g->n_tv = 0;
+}
+
+int bui_gpu_present(BuiGpu *g, int full)
+{
+ (void)full;
+ flush(g);
+ if (!g->target || !make_current(g)) {
+ g->n_dmg = g->dmg_full = 0;
+ return g->target != 0;
+ }
+ if (g->onscreen) {
+ /* the back buffer is undefined after a swap (no GLX dirty-rect present):
+ * blit the whole frame, flipped (it is stored top row first), anchored
+ * to the window's top edge */
+ unsigned int dh = 0;
+ p_glXQueryDrawable(g->xdpy, g->draw, GLX_HEIGHT, &dh);
+ const int top = dh > 0 ? (int)dh : g->th;
+ GL(glBindFramebuffer)(GL_READ_FRAMEBUFFER, g->fbo);
+ GL(glBindFramebuffer)(GL_DRAW_FRAMEBUFFER, 0);
+ GL(glBlitFramebuffer)(0, 0, g->tw, g->th, 0, top, g->tw, top - g->th, GL_COLOR_BUFFER_BIT,
+ GL_NEAREST);
+ GL(glBindFramebuffer)(GL_FRAMEBUFFER, g->fbo);
+ p_glXSwapBuffers(g->xdpy, g->draw);
+ }
+ else {
+ GL(glFlush)();
+ }
+ g->n_dmg = g->dmg_full = 0;
+ return GL(glGetError)() != GL_CONTEXT_LOST;
+}
+
+int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h)
+{
+ flush(g);
+ if (!g->target || g->tw != w || g->th != h || !make_current(g)) {
+ return 0;
+ }
+ GL(glBindFramebuffer)(GL_FRAMEBUFFER, g->fbo);
+ GL(glPixelStorei)(GL_PACK_ALIGNMENT, 4);
+ GL(glPixelStorei)(GL_PACK_ROW_LENGTH, 0);
+ /* rows come back top first (that is how the frame is stored), as
+ * 0xAARRGGBB words */
+ GL(glReadPixels)(0, 0, w, h, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, dst);
+ const size_t n = (size_t)w * h;
+ for (size_t i = 0; i < n; i++) {
+ dst[i] &= 0xFFFFFFu; /* 0x00RRGGBB like the raster */
+ }
+ return 1;
+}
+
+/** \} */
+
+#endif /* BUI_GPU_GL */
diff --git a/gpu/tests/test_gpu_parity.c b/gpu/tests/test_gpu_parity.c
index 2aa7b55..181b88f 100644
--- a/gpu/tests/test_gpu_parity.c
+++ b/gpu/tests/test_gpu_parity.c
@@ -144,13 +144,11 @@ static int compare(const uint32_t *a, const uint32_t *b, const char *label, int
return bad <= W * H / 500; /* < 0.2% (edge rounding) */
}
+/* BUI_gpu_slug() reads BUI_SLUG once and caches it, so setting the variable
+ * here would leave every pass on its first value: switch it directly. */
static void set_slug(int on)
{
-#ifdef _WIN32
- _putenv(on ? "BUI_SLUG=1" : "BUI_SLUG=0");
-#else
- setenv("BUI_SLUG", on ? "1" : "0", 1);
-#endif
+ BUI_gpu_set_slug(on);
}
int main(void)
diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txt
index 53c12f2..004806a 100644
--- a/kit/CMakeLists.txt
+++ b/kit/CMakeLists.txt
@@ -38,6 +38,14 @@ if(NOT MSVC)
endif()
if(WIN32)
target_link_libraries(bui_kit PRIVATE user32 gdi32)
+elseif(APPLE)
+ # Native windows on macOS: an AppKit host after Blender's GHOST Cocoa backend.
+ # Objective-C (enable_language(OBJC) is in the top-level CMakeLists.txt) with
+ # manual retain/release, as GHOST; kit_window_null.c compiles to nothing.
+ target_sources(bui_kit PRIVATE intern/kit_window_cocoa.m)
+ set_source_files_properties(intern/kit_window_cocoa.m PROPERTIES COMPILE_OPTIONS "-fno-objc-arc")
+ target_compile_definitions(bui_kit PRIVATE BUI_WINDOW_COCOA)
+ target_link_libraries(bui_kit PUBLIC "-framework Cocoa" "-framework CoreGraphics" objc)
elseif(UNIX AND NOT APPLE)
# Native windows on X11 (Wayland sessions run it through XWayland).
# Only the headers are needed: libX11 is dlopen()ed at run time, so builds
diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h
index 71d575e..a5d08d0 100644
--- a/kit/include/BUI_kit.h
+++ b/kit/include/BUI_kit.h
@@ -336,7 +336,8 @@ void BK_menu_row_rect(BKNode *menu, int i, int r_rect[4]);
* "alpha", "hex", "dropper". */
BKNode *BK_picker_part(BKNode *picker, const char *name);
-/* -- native window host (Win32; BK_window_supported() is 0 elsewhere) -----------------
+/* -- native window host (Win32, X11, macOS Cocoa; BK_window_supported() is 0 elsewhere,
+ * and on macOS off the main thread: AppKit is main-thread only) -----------------------
* The window owns a raster, drives the context (input -> render -> present
* without leaving C) and installs the host services (cursor, warp,
* clipboard, tooltip timer); BKHost.emit set before is kept for callbacks. */
@@ -374,7 +375,7 @@ int BK_window_timer(BKWindow *win, int ms); /* one-shot; returns its id */
* `vsync`, consecutive frames are paced to the display's refresh. */
void BK_window_request_frame(BKWindow *win, int vsync);
void BK_window_cancel_timer(BKWindow *win, int id);
-void *BK_window_handle(BKWindow *win); /* HWND */
+void *BK_window_handle(BKWindow *win); /* HWND / X11 Window / NSWindow * */
/* Window-manager requests (Tk's wm): "pos" (x, y), "minsize"/"maxsize" (w, h),
* "resizable" (w, h), "topmost" (a), "alpha" (a), "override" (a), "state"
* (0 normal, 1 iconic, 2 withdrawn, 3 zoomed), "lift", "lower", "focus". */
diff --git a/kit/intern/kit_window_cocoa.m b/kit/intern/kit_window_cocoa.m
new file mode 100644
index 0000000..995eb53
--- /dev/null
+++ b/kit/intern/kit_window_cocoa.m
@@ -0,0 +1,1862 @@
+/* Native window host (macOS, Cocoa). Other platforms: kit_window_win32.c,
+ * kit_window_x11.c, kit_window_null.c.
+ *
+ * The same BK_window_* API as kit_window_x11.c, on AppKit, ported from
+ * Blender's GHOST Cocoa backend (intern/ghost/intern/GHOST_SystemCocoa.mm,
+ * GHOST_WindowCocoa.mm, GHOST_WindowViewCocoa.hh): NSApplication setup, the
+ * nextEventMatchingMask loop, key / modifier / mouse / scroll conversion,
+ * Retina backing scale, the window delegate, NSCursor, NSPasteboard and
+ * pointer warping. Redraw requests coalesce into one render per loop turn
+ * and the damaged rectangles of the CPU raster are invalidated on an NSView
+ * whose drawRect: draws the raster as a CGImage at the backing scale.
+ * Timers, the cross-thread wake (a CFRunLoopSource) and frame pacing run in
+ * the loop, like the X11 host.
+ *
+ * Units: like Win32 / X11, the kit sees pixels. A window of logical size
+ * w x h has w * scale / px points (px = backingScaleFactor, scale = the UI
+ * scale = px unless BUI_UI_SCALE is set), so the raster is w * scale pixels
+ * wide and mouse positions are points * px. Screen-level geometry in wm /
+ * wm_get ("pos", "screen", "pointer") is in points, top-left origin of the
+ * primary screen, as Tk reports it on macOS.
+ *
+ * Memory: manual retain / release (compiled with -fno-objc-arc), as GHOST.
+ *
+ * Threads: AppKit only works on the main thread. BK_window_supported() is 0
+ * on any other thread (hosts then fall back to Tk / headless), and every
+ * BK_window_* call except BK_window_wake / BK_window_quit must come from the
+ * main thread.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include "kit_intern.h"
+
+#ifdef BUI_WINDOW_COCOA
+
+# import <Cocoa/Cocoa.h>
+# include <CoreGraphics/CoreGraphics.h>
+
+# include <float.h>
+# include <math.h>
+# include <pthread.h>
+# include <stdio.h>
+# include <stdlib.h>
+# include <string.h>
+# include <time.h>
+
+# define MAX_TIMERS 64
+
+/* Our NSEventTypeApplicationDefined events (loop nudges), told apart from
+ * other code's (Tk posts its own) by subtype and data1. */
+# define BK_NUDGE_SUBTYPE ((short)0x4255)
+# define BK_NUDGE_DATA ((NSInteger)0x42554921)
+
+/* Trackpad scrolling: points of precise scroll per wheel notch. */
+# define BK_SCROLL_STEP 12.0
+
+/* Mac virtual key codes (HIToolbox/Events.h kVK_*), the ones GHOST's
+ * convertKey maps; spelled out so this file needs no Carbon header. */
+enum {
+ BK_kVK_Return = 0x24,
+ BK_kVK_Tab = 0x30,
+ BK_kVK_Delete = 0x33, /* backspace */
+ BK_kVK_Escape = 0x35,
+ BK_kVK_F17 = 0x40,
+ BK_kVK_KeypadDecimal = 0x41,
+ BK_kVK_KeypadMultiply = 0x43,
+ BK_kVK_KeypadPlus = 0x45,
+ BK_kVK_KeypadDivide = 0x4B,
+ BK_kVK_KeypadEnter = 0x4C,
+ BK_kVK_KeypadMinus = 0x4E,
+ BK_kVK_F18 = 0x4F,
+ BK_kVK_F19 = 0x50,
+ BK_kVK_KeypadEquals = 0x51,
+ BK_kVK_Keypad0 = 0x52,
+ BK_kVK_Keypad1 = 0x53,
+ BK_kVK_Keypad2 = 0x54,
+ BK_kVK_Keypad3 = 0x55,
+ BK_kVK_Keypad4 = 0x56,
+ BK_kVK_Keypad5 = 0x57,
+ BK_kVK_Keypad6 = 0x58,
+ BK_kVK_Keypad7 = 0x59,
+ BK_kVK_F20 = 0x5A,
+ BK_kVK_Keypad8 = 0x5B,
+ BK_kVK_Keypad9 = 0x5C,
+ BK_kVK_F5 = 0x60,
+ BK_kVK_F6 = 0x61,
+ BK_kVK_F7 = 0x62,
+ BK_kVK_F3 = 0x63,
+ BK_kVK_F8 = 0x64,
+ BK_kVK_F9 = 0x65,
+ BK_kVK_F11 = 0x67,
+ BK_kVK_F13 = 0x69,
+ BK_kVK_F16 = 0x6A,
+ BK_kVK_F14 = 0x6B,
+ BK_kVK_F10 = 0x6D,
+ BK_kVK_F12 = 0x6F,
+ BK_kVK_F15 = 0x71,
+ BK_kVK_Help = 0x72, /* Insert on PC keyboards */
+ BK_kVK_Home = 0x73,
+ BK_kVK_PageUp = 0x74,
+ BK_kVK_ForwardDelete = 0x75,
+ BK_kVK_F4 = 0x76,
+ BK_kVK_End = 0x77,
+ BK_kVK_F2 = 0x78,
+ BK_kVK_PageDown = 0x79,
+ BK_kVK_F1 = 0x7A,
+ BK_kVK_LeftArrow = 0x7B,
+ BK_kVK_RightArrow = 0x7C,
+ BK_kVK_DownArrow = 0x7D,
+ BK_kVK_UpArrow = 0x7E,
+};
+
+typedef struct BKCocoaTimer {
+ int ident; /* > 0 user timer, -1 the tooltip timer, 0 free */
+ double due;
+} BKCocoaTimer;
+
+@class BUIKitView;
+@class BUIKitWindowDelegate;
+
+struct BKWindow {
+ NSWindow *nswin; /* retained; nil once closed */
+ BUIKitView *view; /* the content view (owned by nswin) */
+ BUIKitWindowDelegate *delegate; /* retained */
+ BKContext *ctx;
+ BKHost prev; /* the host's own callbacks (emit) */
+ BuiRaster *raster;
+ BKWindowCallbacks cb;
+ int render_pending, frames, cursor, tip_id, next_timer, full;
+ int want_frame, frame_vsync;
+ double frame_start; /* when the last animation frame began */
+ double next_frame; /* frame pacing: no render before this (ms) */
+ float scale; /* UI scale (BK_set_scale, wm_get "scale") */
+ float px; /* backing pixels per point (2 on Retina) */
+ int w, h; /* view size in pixels */
+ int min_w, min_h, max_w, max_h; /* content size limits (logical px; 0 = none) */
+ int fixed_w, fixed_h; /* axes the user may not resize (Tk's resizable) */
+ int override, disabled, shown;
+ NSWindowStyleMask style; /* framed style ("override" 0 restores it) */
+ NSEventModifierFlags flags; /* modifiers at the last flagsChanged */
+ double scroll_x, scroll_y; /* trackpad scroll not yet sent (points) */
+ BKCocoaTimer timers[MAX_TIMERS];
+ struct BKWindow *next;
+};
+
+static BKWindow *g_windows = NULL;
+static int g_open = 0, g_quit = 0, g_keep_alive = 0;
+static int (*g_stop)(void) = NULL;
+static int g_app_ready = 0;
+static int g_turn_depth = 0;
+static int g_nudge_pending = 0;
+static int g_cursor_hidden = 0;
+static int g_ignore_momentum = 0;
+static double g_warp_time = -1.0; /* systemUptime of the last warp */
+static NSEvent *g_keyup_done = nil; /* key-up handled before sendEvent (not retained) */
+static NSMutableArray *g_dead = nil; /* closed windows, released between turns */
+static id g_app_delegate = nil;
+static void (*g_wake_cb)(void) = NULL;
+static CFRunLoopSourceRef g_wake_src = NULL;
+static int g_wake_pending = 0; /* atomic */
+
+static void request_close(BKWindow *win);
+static void close_window(BKWindow *win);
+static void update_size(BKWindow *win);
+static void on_backing_changed(BKWindow *win);
+static void render_window(BKWindow *win);
+static void apply_cursor(BKWindow *win);
+static void show_cursor(int visible);
+static void post_nudge(void);
+static void handle_key(BUIKitView *v, NSEvent *ev, int press);
+static void handle_flags(BUIKitView *v, NSEventModifierFlags flags);
+
+static double now_ms(void)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
+
+/* BUI_UI_SCALE, else the backing scale (Win32's dpi / 96). */
+static float env_scale(void)
+{
+ const char *env = getenv("BUI_UI_SCALE");
+ return (env && atof(env) > 0) ? (float)atof(env) : 0.0f;
+}
+
+static float ui_scale(float px)
+{
+ const float env = env_scale();
+ return env > 0.0f ? env : BK_MAX(1.0f, px);
+}
+
+/* Height of the primary screen: flips Cocoa's bottom-left screen origin to
+ * the top-left one of Quartz (GHOST_SystemCocoa::setMouseCursorPosition). */
+static CGFloat primary_height(void)
+{
+ NSScreen *primary = [[NSScreen screens] firstObject];
+ return primary ? NSMaxY([primary frame]) : 0.0;
+}
+
+/* -- the AppKit classes -------------------------------------------------------------- */
+
+/* GHOST's BlenderWindow: borderless ("override") windows still take keys. */
+@interface BUIKitNSWindow : NSWindow
+@end
+
+@implementation BUIKitNSWindow
+- (BOOL)canBecomeKeyWindow
+{
+ return YES;
+}
+- (BOOL)canBecomeMainWindow
+{
+ return YES;
+}
+@end
+
+/* GHOST_WindowViewCocoa.hh: the view takes the input and draws the frame. */
+@interface BUIKitView : NSView {
+@public
+ BKWindow *bk; /* NULL once the window closed */
+ NSTrackingArea *tracking;
+}
+@end
+
+/* GHOST_WindowCocoa.mm BlenderWindowDelegate. */
+@interface BUIKitWindowDelegate : NSObject <NSWindowDelegate> {
+@public
+ BKWindow *bk;
+}
+@end
+
+/* GHOST_SystemCocoa.mm CocoaAppDelegate. */
+@interface BUIKitAppDelegate : NSObject <NSApplicationDelegate>
+@end
+
+static BUIKitView *view_of(NSWindow *w)
+{
+ NSView *cv = [w contentView];
+ return [cv isKindOfClass:[BUIKitView class]] ? (BUIKitView *)cv : nil;
+}
+
+static int mods_of(NSEventModifierFlags f)
+{
+ /* Command is Ctrl, as Blender's macOS keymaps use it for Ctrl's shortcuts */
+ int m = 0;
+ if (f & NSEventModifierFlagShift) {
+ m |= BK_SHIFT;
+ }
+ if (f & (NSEventModifierFlagControl | NSEventModifierFlagCommand)) {
+ m |= BK_CTRL;
+ }
+ if (f & NSEventModifierFlagOption) {
+ m |= BK_ALT;
+ }
+ if ([NSEvent pressedMouseButtons] & 1) {
+ m |= BK_BUTTON1;
+ }
+ return m;
+}
+
+/* An event's position in the view, in raster pixels (y down). */
+static void event_px(BKWindow *win, NSEvent *ev, int *r_x, int *r_y)
+{
+ const NSPoint p = [win->view convertPoint:[ev locationInWindow] fromView:nil];
+ *r_x = (int)floor(p.x * win->px);
+ *r_y = (int)floor(p.y * win->px);
+}
+
+static CGColorSpaceRef srgb(void)
+{
+ static CGColorSpaceRef cs = NULL;
+ if (!cs) {
+ cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ }
+ return cs;
+}
+
+@implementation BUIKitView
+
+- (void)dealloc
+{
+ [tracking release];
+ [super dealloc];
+}
+
+- (BOOL)isFlipped
+{
+ return YES; /* y down, like the raster */
+}
+
+- (BOOL)isOpaque
+{
+ return YES;
+}
+
+- (BOOL)acceptsFirstResponder
+{
+ return YES;
+}
+
+- (BOOL)acceptsFirstMouse:(NSEvent *)event
+{
+ return YES;
+}
+
+/* Enter / exit and cursor updates over the whole view. */
+- (void)updateTrackingAreas
+{
+ if (tracking) {
+ [self removeTrackingArea:tracking];
+ [tracking release];
+ tracking = nil;
+ }
+ tracking = [[NSTrackingArea alloc]
+ initWithRect:NSZeroRect
+ options:(NSTrackingMouseEnteredAndExited | NSTrackingCursorUpdate |
+ NSTrackingActiveAlways | NSTrackingInVisibleRect)
+ owner:self
+ userInfo:nil];
+ [self addTrackingArea:tracking];
+ [super updateTrackingAreas];
+}
+
+- (void)cursorUpdate:(NSEvent *)event
+{
+ if (bk) {
+ apply_cursor(bk);
+ }
+ else {
+ [super cursorUpdate:event];
+ }
+}
+
+/* The raster as a CGImage: 0x00RRGGBB words are little-endian XRGB. */
+- (void)drawRect:(NSRect)dirty
+{
+ CGContextRef cg = [[NSGraphicsContext currentContext] CGContext];
+ if (!cg) {
+ return;
+ }
+ const NSRect b = [self bounds];
+ BuiRaster *r = bk ? bk->raster : NULL;
+ const int iw = r ? BUI_raster_width(r) : 0, ih = r ? BUI_raster_height(r) : 0;
+ const CGFloat px = bk ? bk->px : 1.0;
+ const CGFloat wpt = iw / px, hpt = ih / px;
+ if (!r || iw <= 1 || ih <= 1 || wpt < b.size.width || hpt < b.size.height) {
+ CGContextSetRGBFillColor(cg, 0.188, 0.188, 0.188, 1.0); /* Blender's background */
+ CGContextFillRect(cg, NSRectToCGRect(dirty));
+ }
+ if (!r || iw <= 1 || ih <= 1) {
+ return;
+ }
+ CGDataProviderRef prov = CGDataProviderCreateWithData(
+ NULL, BUI_raster_pixels(r), (size_t)iw * (size_t)ih * 4, NULL);
+ CGImageRef img = CGImageCreate((size_t)iw,
+ (size_t)ih,
+ 8,
+ 32,
+ (size_t)iw * 4,
+ srgb(),
+ (CGBitmapInfo)kCGImageAlphaNoneSkipFirst |
+ kCGBitmapByteOrder32Little,
+ prov,
+ NULL,
+ false,
+ kCGRenderingIntentDefault);
+ CGDataProviderRelease(prov);
+ if (!img) {
+ return;
+ }
+ /* AppKit clips to the invalidated rects (the raster's damage), so drawing
+ * the whole image only updates those */
+ CGContextSaveGState(cg);
+ CGContextSetInterpolationQuality(cg, kCGInterpolationNone);
+ CGContextSetBlendMode(cg, kCGBlendModeCopy);
+ CGContextTranslateCTM(cg, 0, hpt); /* the view is flipped; images draw y up */
+ CGContextScaleCTM(cg, 1.0, -1.0);
+ CGContextDrawImage(cg, CGRectMake(0, 0, wpt, hpt), img);
+ CGContextRestoreGState(cg);
+ CGImageRelease(img);
+}
+
+/* -- mouse (GHOST_SystemCocoa::handleMouseEvent) -- */
+
+- (void)mouseDown:(NSEvent *)ev
+{
+ if (!bk || bk->disabled) {
+ return;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ [[self window] makeFirstResponder:self];
+ BK_press(bk->ctx, x, y, mods_of([ev modifierFlags]) | BK_BUTTON1);
+}
+
+- (void)mouseUp:(NSEvent *)ev
+{
+ if (!bk || bk->disabled) {
+ return;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ BK_release(bk->ctx, x, y, mods_of([ev modifierFlags]) & ~BK_BUTTON1);
+}
+
+- (void)rightMouseDown:(NSEvent *)ev
+{
+ if (!bk || bk->disabled) {
+ return;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ BK_context_menu(bk->ctx, x, y, mods_of([ev modifierFlags]));
+}
+
+- (void)rightMouseUp:(NSEvent *)ev
+{
+ if (!bk || bk->disabled) {
+ return;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ BK_button(bk->ctx, x, y, 3, 1, mods_of([ev modifierFlags]) & ~BK_BUTTON1);
+}
+
+/* GHOST convertButton: buttonNumber 2 is the middle button. */
+- (void)otherMouseDown:(NSEvent *)ev
+{
+ if (!bk || bk->disabled || [ev buttonNumber] != 2) {
+ return;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ BK_button(bk->ctx, x, y, 2, 0, mods_of([ev modifierFlags]));
+}
+
+- (void)otherMouseUp:(NSEvent *)ev
+{
+ if (!bk || bk->disabled || [ev buttonNumber] != 2) {
+ return;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ BK_button(bk->ctx, x, y, 2, 1, mods_of([ev modifierFlags]) & ~BK_BUTTON1);
+}
+
+- (void)motion:(NSEvent *)ev
+{
+ if (!bk || bk->disabled) {
+ return;
+ }
+ /* GHOST: after a warp, moves stamped (just) before it still carry the old
+ * position; skip them or a continuous drag jumps */
+ if ([ev timestamp] < g_warp_time + 0.003) {
+ return;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ BK_motion(bk->ctx, x, y, mods_of([ev modifierFlags]));
+}
+
+- (void)mouseMoved:(NSEvent *)ev
+{
+ [self motion:ev];
+}
+
+- (void)mouseDragged:(NSEvent *)ev
+{
+ [self motion:ev];
+}
+
+- (void)rightMouseDragged:(NSEvent *)ev
+{
+ [self motion:ev];
+}
+
+- (void)otherMouseDragged:(NSEvent *)ev
+{
+ [self motion:ev];
+}
+
+- (void)mouseExited:(NSEvent *)ev
+{
+ if (!bk) {
+ return;
+ }
+ if ([NSEvent pressedMouseButtons] == 0) { /* a drag keeps the pointer (capture) */
+ show_cursor(1);
+ [[NSCursor arrowCursor] set];
+ BK_motion(bk->ctx, -100000, -100000, 0);
+ }
+}
+
+/* GHOST_SystemCocoa::handleMouseEvent NSEventTypeScrollWheel: wheels give
+ * one notch per event; trackpads (events with a phase) give precise deltas,
+ * summed here into notches. Horizontal scrolling is Shift+wheel, as the X11
+ * host maps buttons 6 / 7. */
+- (void)scrollWheel:(NSEvent *)ev
+{
+ if (!bk || bk->disabled) {
+ return;
+ }
+ const NSEventPhase momentum = [ev momentumPhase], phase = [ev phase];
+ /* GHOST: momentum scrolling after a key press would turn into another
+ * action (e.g. Ctrl+scroll); ignore it */
+ if (momentum != NSEventPhaseNone) {
+ if (g_ignore_momentum) {
+ return;
+ }
+ }
+ else {
+ g_ignore_momentum = 0;
+ }
+ int x, y;
+ event_px(bk, ev, &x, &y);
+ const int mods = mods_of([ev modifierFlags]) & ~BK_BUTTON1;
+ if (phase == NSEventPhaseNone && momentum == NSEventPhaseNone) {
+ const CGFloat dx = [ev deltaX], dy = [ev deltaY];
+ if (dx != 0.0) {
+ /* macOS turns Shift+wheel into horizontal deltas: Shift+wheel again */
+ BK_wheel(bk->ctx, x, y, dx > 0.0 ? 1 : -1, mods | BK_SHIFT);
+ }
+ if (dy != 0.0 && bk) {
+ BK_wheel(bk->ctx, x, y, dy > 0.0 ? 1 : -1, mods);
+ }
+ return;
+ }
+ if (phase == NSEventPhaseBegan) {
+ bk->scroll_x = bk->scroll_y = 0.0;
+ }
+ /* 10.7+ precise deltas, in points (GHOST: scrollingDeltaX / Y) */
+ CGFloat dx = [ev scrollingDeltaX], dy = [ev scrollingDeltaY];
+ if (![ev hasPreciseScrollingDeltas]) {
+ dx *= BK_SCROLL_STEP; /* line deltas */
+ dy *= BK_SCROLL_STEP;
+ }
+ bk->scroll_x += dx;
+ bk->scroll_y += dy;
+ for (int i = 0; i < 8 && bk && fabs(bk->scroll_y) >= BK_SCROLL_STEP; i++) {
+ const int d = bk->scroll_y > 0.0 ? 1 : -1;
+ bk->scroll_y -= d * BK_SCROLL_STEP;
+ BK_wheel(bk->ctx, x, y, d, mods);
+ }
+ for (int i = 0; i < 8 && bk && fabs(bk->scroll_x) >= BK_SCROLL_STEP; i++) {
+ const int d = bk->scroll_x > 0.0 ? 1 : -1;
+ bk->scroll_x -= d * BK_SCROLL_STEP;
+ BK_wheel(bk->ctx, x, y, d, mods | BK_SHIFT);
+ }
+}
+
+/* -- keys (GHOST_WindowViewCocoa.hh keyDown: / HANDLE_KEY_EVENT) -- */
+
+/* Handling keyDown: here (not calling super) also keeps AppKit from beeping. */
+- (void)keyDown:(NSEvent *)ev
+{
+ handle_key(self, ev, 1);
+}
+
+- (void)keyUp:(NSEvent *)ev
+{
+ if (ev != g_keyup_done) {
+ handle_key(self, ev, 0);
+ }
+}
+
+- (void)flagsChanged:(NSEvent *)ev
+{
+ handle_flags(self, [ev modifierFlags]);
+}
+
+@end
+
+@implementation BUIKitWindowDelegate
+
+/* GHOST: let the host decide; we close the window ourselves when it agrees. */
+- (BOOL)windowShouldClose:(NSWindow *)sender
+{
+ if (bk) {
+ request_close(bk);
+ }
+ return NO;
+}
+
+- (void)windowDidResize:(NSNotification *)notification
+{
+ if (bk) {
+ update_size(bk);
+ }
+}
+
+/* GHOST: macOS sends no resize when switching between zoomed and full-screen. */
+- (void)windowDidEnterFullScreen:(NSNotification *)notification
+{
+ if (bk) {
+ update_size(bk);
+ }
+}
+
+- (void)windowDidExitFullScreen:(NSNotification *)notification
+{
+ if (bk) {
+ update_size(bk);
+ }
+}
+
+/* GHOST: GHOST_kEventNativeResolutionChange (moved to a screen with another
+ * backing scale). */
+- (void)windowDidChangeBackingProperties:(NSNotification *)notification
+{
+ if (bk) {
+ on_backing_changed(bk);
+ }
+}
+
+- (void)windowDidBecomeKey:(NSNotification *)notification
+{
+ if (bk) {
+ bk->flags = [NSEvent modifierFlags]; /* modifiers may have changed elsewhere */
+ }
+}
+
+- (void)windowDidDeminiaturize:(NSNotification *)notification
+{
+ if (bk) {
+ bk->full = 1;
+ bk->render_pending = 1;
+ }
+}
+
+@end
+
+@implementation BUIKitAppDelegate
+
+/* GHOST's CocoaAppDelegate: Cmd+Q asks every window to close as its close
+ * button would (on_close may refuse); the loop ends when none is left. */
+- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
+{
+ BKWindow *next;
+ for (BKWindow *w = g_windows; w; w = next) {
+ next = w->next;
+ if (w->nswin) {
+ request_close(w);
+ }
+ }
+ if (g_open == 0) {
+ g_quit = 1;
+ post_nudge();
+ }
+ return NSTerminateCancel;
+}
+
+- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app
+{
+ return YES;
+}
+
+@end
+
+/* -- NSApplication (GHOST_SystemCocoa::init) ------------------------------------------ */
+
+static NSMenuItem *menu_add(NSMenu *menu, NSString *title, SEL action, NSString *key,
+ NSEventModifierFlags mask)
+{
+ NSMenuItem *item = [menu addItemWithTitle:title action:action keyEquivalent:key];
+ [item setKeyEquivalentModifierMask:mask];
+ return item;
+}
+
+static int app_init(void)
+{
+ if (g_app_ready) {
+ return 1;
+ }
+ if (!pthread_main_np()) {
+ return 0;
+ }
+ @autoreleasepool {
+ const BOOL created = (NSApp == nil);
+ [NSApplication sharedApplication]; /* initializes NSApp */
+ if (created) {
+ /* a plain executable (python, node, a C program) is no app bundle:
+ * become a regular app, with a Dock icon, a menu bar and key focus */
+ [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
+ }
+ if ([NSApp mainMenu] == nil) {
+ NSString *name = [[NSProcessInfo processInfo] processName];
+ NSMenu *bar = [[NSMenu alloc] init];
+ NSMenu *app_menu = [[NSMenu alloc] initWithTitle:name];
+ menu_add(app_menu, [@"Hide " stringByAppendingString:name], @selector(hide:), @"h",
+ NSEventModifierFlagCommand);
+ menu_add(app_menu, @"Hide Others", @selector(hideOtherApplications:), @"h",
+ NSEventModifierFlagOption | NSEventModifierFlagCommand);
+ [app_menu addItemWithTitle:@"Show All"
+ action:@selector(unhideAllApplications:)
+ keyEquivalent:@""];
+ [app_menu addItem:[NSMenuItem separatorItem]];
+ menu_add(app_menu, [@"Quit " stringByAppendingString:name], @selector(terminate:), @"q",
+ NSEventModifierFlagCommand);
+ NSMenuItem *item = [[NSMenuItem alloc] init];
+ [item setSubmenu:app_menu];
+ [bar addItem:item];
+ [item release];
+ [app_menu release];
+
+ NSMenu *window_menu = [[NSMenu alloc] initWithTitle:@"Window"];
+ menu_add(window_menu, @"Minimize", @selector(performMiniaturize:), @"m",
+ NSEventModifierFlagCommand);
+ [window_menu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""];
+ menu_add(window_menu, @"Enter Full Screen", @selector(toggleFullScreen:), @"f",
+ NSEventModifierFlagControl | NSEventModifierFlagCommand);
+ menu_add(window_menu, @"Close", @selector(performClose:), @"w",
+ NSEventModifierFlagCommand);
+ item = [[NSMenuItem alloc] init];
+ [item setSubmenu:window_menu];
+ [bar addItem:item];
+ [item release];
+
+ [NSApp setMainMenu:bar];
+ [NSApp setWindowsMenu:window_menu];
+ [window_menu release];
+ [bar release];
+ }
+ if ([NSApp delegate] == nil) {
+ g_app_delegate = [[BUIKitAppDelegate alloc] init]; /* kept: NSApp doesn't retain it */
+ [NSApp setDelegate:g_app_delegate];
+ }
+ /* GHOST: no automatic window tabbing */
+ [NSWindow setAllowsAutomaticWindowTabbing:NO];
+ if (created) {
+ /* whoever made NSApp (e.g. Tk) already finished launching it */
+ [NSApp finishLaunching];
+ }
+ g_dead = [[NSMutableArray alloc] init];
+ }
+ g_app_ready = 1;
+ return 1;
+}
+
+/* Native windows need the main thread and a window-server (GUI) session. */
+int BK_window_supported(void)
+{
+ if (!pthread_main_np()) {
+ return 0;
+ }
+ static int session = -1;
+ if (session < 0) {
+ CFDictionaryRef d = CGSessionCopyCurrentDictionary(); /* NULL over plain ssh */
+ session = d != NULL;
+ if (d) {
+ CFRelease(d);
+ }
+ }
+ return session;
+}
+
+/* -- host callbacks -------------------------------------------------------------------- */
+
+static void host_request(void *data)
+{
+ BKWindow *win = (BKWindow *)data;
+ if (win->nswin) {
+ win->render_pending = 1;
+ }
+}
+
+/* GHOST_WindowCocoa::getStandardCursor */
+static NSCursor *ns_cursor(int c)
+{
+ switch (c) {
+ case BK_CURSOR_EW:
+ return [NSCursor resizeLeftRightCursor];
+ case BK_CURSOR_NS:
+ return [NSCursor resizeUpDownCursor];
+ case BK_CURSOR_TEXT:
+ return [NSCursor IBeamCursor];
+ case BK_CURSOR_CROSSHAIR:
+ return [NSCursor crosshairCursor];
+ case BK_CURSOR_HAND:
+ return [NSCursor pointingHandCursor];
+ case BK_CURSOR_MOVE:
+ return [NSCursor openHandCursor];
+ }
+ return [NSCursor arrowCursor];
+}
+
+/* GHOST_WindowCocoa::loadCursor: hide / unhide are counted, keep them paired. */
+static void show_cursor(int visible)
+{
+ if (visible && g_cursor_hidden) {
+ [NSCursor unhide];
+ g_cursor_hidden = 0;
+ }
+ else if (!visible && !g_cursor_hidden) {
+ [NSCursor hide];
+ g_cursor_hidden = 1;
+ }
+}
+
+static void apply_cursor(BKWindow *win)
+{
+ show_cursor(win->cursor != BK_CURSOR_NONE);
+ if (win->cursor != BK_CURSOR_NONE) {
+ [ns_cursor(win->cursor) set];
+ }
+}
+
+static int pointer_inside(BKWindow *win)
+{
+ const NSPoint p = [win->view convertPoint:[win->nswin mouseLocationOutsideOfEventStream]
+ fromView:nil];
+ return NSPointInRect(p, [win->view bounds]);
+}
+
+/* GHOST_WindowCocoa::setWindowCursorShape */
+static void host_set_cursor(void *data, int c)
+{
+ BKWindow *win = (BKWindow *)data;
+ win->cursor = BK_CLAMP(c, 0, 7);
+ if (!win->nswin) {
+ return;
+ }
+ @autoreleasepool {
+ /* like a window cursor elsewhere: only while the pointer is over the view
+ * (or dragging from it); cursorUpdate: applies it on entry */
+ if (pointer_inside(win) || [NSEvent pressedMouseButtons] != 0) {
+ apply_cursor(win);
+ }
+ }
+}
+
+/* GHOST_SystemCocoa::setMouseCursorPosition: Quartz takes global top-left
+ * coordinates; CGAssociateMouseAndMouseCursorPosition drops the 500 ms of
+ * suppressed mouse events after a synthetic move. */
+static void host_warp(void *data, int x, int y)
+{
+ BKWindow *win = (BKWindow *)data;
+ if (!win->nswin) {
+ return;
+ }
+ @autoreleasepool {
+ const NSPoint in_view = NSMakePoint(x / win->px, y / win->px);
+ const NSPoint in_window = [win->view convertPoint:in_view toView:nil];
+ const NSRect on_screen = [win->nswin
+ convertRectToScreen:NSMakeRect(in_window.x, in_window.y, 0, 0)];
+ CGWarpMouseCursorPosition(
+ CGPointMake(on_screen.origin.x, primary_height() - on_screen.origin.y));
+ CGAssociateMouseAndMouseCursorPosition(true);
+ g_warp_time = [[NSProcessInfo processInfo] systemUptime];
+ }
+}
+
+/* GHOST_SystemCocoa::getClipboard */
+static char *host_clipboard_get(void *data)
+{
+ char *out = NULL;
+ @autoreleasepool {
+ NSString *s = [[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];
+ const char *u = s ? [s UTF8String] : NULL;
+ if (u) {
+ out = strdup(u);
+ }
+ }
+ return out;
+}
+
+/* GHOST_SystemCocoa::putClipboard */
+static void host_clipboard_set(void *data, const char *text)
+{
+ @autoreleasepool {
+ NSPasteboard *pb = [NSPasteboard generalPasteboard];
+ [pb declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil];
+ NSString *s = [NSString stringWithUTF8String:text ? text : ""];
+ if (s) {
+ [pb setString:s forType:NSPasteboardTypeString];
+ }
+ }
+}
+
+static BKCocoaTimer *timer_slot(BKWindow *win, int ident)
+{
+ for (int i = 0; i < MAX_TIMERS; i++) {
+ if (win->timers[i].ident == ident) {
+ return &win->timers[i];
+ }
+ }
+ for (int i = 0; i < MAX_TIMERS; i++) {
+ if (win->timers[i].ident == 0) {
+ return &win->timers[i];
+ }
+ }
+ return NULL;
+}
+
+static void host_schedule(void *data, int ms, int timer)
+{
+ BKWindow *win = (BKWindow *)data;
+ win->tip_id = timer;
+ BKCocoaTimer *t = timer_slot(win, -1);
+ if (t) {
+ t->ident = -1;
+ t->due = now_ms() + ms;
+ }
+}
+
+static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, double b)
+{
+ BKWindow *win = (BKWindow *)data;
+ if (win->prev.emit) {
+ win->prev.emit(win->prev.data, node, kind, ref, a, b);
+ }
+}
+
+/* -- rendering ----------------------------------------------------------------------- */
+
+/* The display's refresh interval (ProMotion: 120 Hz). */
+static double refresh_ms(void)
+{
+ static double ms = 0.0;
+ if (ms > 0.0) {
+ return ms;
+ }
+ double hz = 0.0;
+# if defined(MAC_OS_VERSION_12_0) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_12_0
+ if (@available(macOS 12.0, *)) {
+ hz = (double)[[NSScreen mainScreen] maximumFramesPerSecond];
+ }
+# endif
+ if (hz <= 1.0) {
+ CGDisplayModeRef mode = CGDisplayCopyDisplayMode(CGMainDisplayID());
+ if (mode) {
+ hz = CGDisplayModeGetRefreshRate(mode); /* 0 on some built-in panels */
+ CGDisplayModeRelease(mode);
+ }
+ }
+ ms = 1000.0 / (hz > 1.0 ? hz : 60.0);
+ return ms;
+}
+
+/* Invalidate the damaged rectangles (pixels -> points) and draw them now. */
+static void present(BKWindow *win, int all)
+{
+ BUIKitView *v = win->view;
+ if (!v) {
+ return;
+ }
+ const CGFloat px = win->px;
+ if (all) {
+ [v setNeedsDisplay:YES];
+ }
+ else {
+ const int(*rects)[4];
+ const int n = BUI_raster_damage(win->raster, &rects);
+ for (int i = 0; i < n; i++) {
+ const CGFloat x0 = floor(rects[i][0] / px), y0 = floor(rects[i][1] / px);
+ const CGFloat x1 = ceil((rects[i][0] + rects[i][2]) / px);
+ const CGFloat y1 = ceil((rects[i][1] + rects[i][3]) / px);
+ [v setNeedsDisplayInRect:NSMakeRect(x0, y0, x1 - x0, y1 - y0)];
+ }
+ }
+ [v displayIfNeeded];
+}
+
+static void do_render(BKWindow *win)
+{
+ const int w = BK_MAX(1, win->w), h = BK_MAX(1, win->h);
+ const int resized = BUI_raster_width(win->raster) != w || BUI_raster_height(win->raster) != h;
+ const int regions = BK_render(win->ctx, win->raster, w, h, win->full || resized);
+ if (regions || resized || win->full) {
+ present(win, resized || win->full);
+ win->frames++;
+ }
+ win->full = 0;
+}
+
+static void render_window(BKWindow *win)
+{
+ const double t0 = now_ms();
+ if (win->want_frame && win->cb.on_frame) {
+ /* render_pending is still set: edits made here join this frame */
+ win->want_frame = 0;
+ win->frame_start = t0;
+ win->cb.on_frame(win->cb.data, win);
+ if (!win->nswin) {
+ return; /* closed by the callback */
+ }
+ }
+ win->render_pending = 0;
+ @autoreleasepool {
+ do_render(win);
+ }
+ int paced = 0;
+ if (win->want_frame) { /* the host asked for the next frame */
+ bk_frame_ms = now_ms() - win->frame_start;
+ bk_frame_budget_ms = win->frame_vsync ? refresh_ms() : 0.0;
+ win->render_pending = 1;
+ paced = win->frame_vsync;
+ }
+ else {
+ bk_frame_ms = 0.0; /* the animation ended */
+ }
+ if (BK_animating(win->ctx)) {
+ win->render_pending = 1;
+ paced = 1;
+ }
+ /* the next frame one refresh after this one began: early frames wait,
+ * late ones start right away (Win32's DwmFlush pacing) */
+ win->next_frame = paced ? t0 + refresh_ms() : 0.0;
+}
+
+/* -- input mapping (GHOST_SystemCocoa::handleKeyEvent / convertKey) ------------------- */
+
+/* Keys without text, by key code: X keysym names, as Tk and BUI use them. */
+static const char *special_keysym(unsigned short code)
+{
+ switch (code) {
+ case BK_kVK_Return: return "Return";
+ case BK_kVK_Tab: return "Tab";
+ case BK_kVK_Delete: return "BackSpace";
+ case BK_kVK_ForwardDelete: return "Delete";
+ case BK_kVK_Escape: return "Escape";
+ case BK_kVK_Help: return "Insert";
+ case BK_kVK_Home: return "Home";
+ case BK_kVK_End: return "End";
+ case BK_kVK_PageUp: return "Prior";
+ case BK_kVK_PageDown: return "Next";
+ case BK_kVK_LeftArrow: return "Left";
+ case BK_kVK_RightArrow: return "Right";
+ case BK_kVK_UpArrow: return "Up";
+ case BK_kVK_DownArrow: return "Down";
+ case BK_kVK_KeypadEnter: return "KP_Enter";
+ case BK_kVK_F1: return "F1";
+ case BK_kVK_F2: return "F2";
+ case BK_kVK_F3: return "F3";
+ case BK_kVK_F4: return "F4";
+ case BK_kVK_F5: return "F5";
+ case BK_kVK_F6: return "F6";
+ case BK_kVK_F7: return "F7";
+ case BK_kVK_F8: return "F8";
+ case BK_kVK_F9: return "F9";
+ case BK_kVK_F10: return "F10";
+ case BK_kVK_F11: return "F11";
+ case BK_kVK_F12: return "F12";
+ case BK_kVK_F13: return "F13";
+ case BK_kVK_F14: return "F14";
+ case BK_kVK_F15: return "F15";
+ case BK_kVK_F16: return "F16";
+ case BK_kVK_F17: return "F17";
+ case BK_kVK_F18: return "F18";
+ case BK_kVK_F19: return "F19";
+ case BK_kVK_F20: return "F20";
+ }
+ return NULL;
+}
+
+/* Keypad keys: X's KP_ keysyms, with their text (as XLookupString gives). */
+static const char *keypad_keysym(unsigned short code)
+{
+ switch (code) {
+ case BK_kVK_Keypad0: return "KP_0";
+ case BK_kVK_Keypad1: return "KP_1";
+ case BK_kVK_Keypad2: return "KP_2";
+ case BK_kVK_Keypad3: return "KP_3";
+ case BK_kVK_Keypad4: return "KP_4";
+ case BK_kVK_Keypad5: return "KP_5";
+ case BK_kVK_Keypad6: return "KP_6";
+ case BK_kVK_Keypad7: return "KP_7";
+ case BK_kVK_Keypad8: return "KP_8";
+ case BK_kVK_Keypad9: return "KP_9";
+ case BK_kVK_KeypadDecimal: return "KP_Decimal";
+ case BK_kVK_KeypadMultiply: return "KP_Multiply";
+ case BK_kVK_KeypadPlus: return "KP_Add";
+ case BK_kVK_KeypadMinus: return "KP_Subtract";
+ case BK_kVK_KeypadDivide: return "KP_Divide";
+ case BK_kVK_KeypadEquals: return "KP_Equal";
+ }
+ return NULL;
+}
+
+static int is_text_char(unichar c)
+{
+ /* control characters and AppKit's function-key range (0xF700..0xF8FF) */
+ return c >= 0x20 && c != 0x7f && !(c >= 0xF700 && c <= 0xF8FF);
+}
+
+static void copy_utf8(char *dst, size_t size, NSString *s)
+{
+ const char *u = s ? [s UTF8String] : NULL;
+ dst[0] = 0;
+ if (u) {
+ strncpy(dst, u, size - 1);
+ dst[size - 1] = 0;
+ }
+}
+
+static void handle_key(BUIKitView *v, NSEvent *ev, int press)
+{
+ BKWindow *win = v ? v->bk : NULL;
+ if (!win || win->disabled) {
+ return;
+ }
+ g_ignore_momentum = 1; /* GHOST: a key press ends momentum scrolling */
+ @autoreleasepool {
+ const NSEventModifierFlags f = [ev modifierFlags];
+ const int mods = mods_of(f);
+ const unsigned short code = [ev keyCode];
+ char ks_buf[32], text[32];
+ text[0] = 0;
+ const char *ks = special_keysym(code);
+ const int special = ks != NULL;
+ if (!ks) {
+ ks = keypad_keysym(code);
+ }
+ if (!ks) {
+ /* the character ignoring modifiers except Shift, as convertKey uses it
+ * (letters and punctuation follow the keyboard layout) */
+ NSString *ign = [ev charactersIgnoringModifiers];
+ ks = "";
+ if ([ign length] > 0) {
+ const unichar c = [ign characterAtIndex:0];
+ if (c == ' ') {
+ ks = "space";
+ }
+ else if (c == '-') {
+ ks = "minus";
+ }
+ else if (is_text_char(c)) {
+ copy_utf8(ks_buf, sizeof(ks_buf), ign);
+ ks = ks_buf;
+ }
+ }
+ }
+ if (!press) {
+ BK_key_release(win->ctx, ks, mods);
+ }
+ else {
+ /* GHOST: no text with Command held, nor for arrows / F-keys */
+ if (!special && !(f & NSEventModifierFlagCommand)) {
+ NSString *chars = [ev characters]; /* empty for dead keys */
+ if ([chars length] > 0 && is_text_char([chars characterAtIndex:0])) {
+ copy_utf8(text, sizeof(text), chars);
+ }
+ }
+ BK_key(win->ctx, text, ks, mods);
+ }
+ }
+}
+
+/* GHOST_SystemCocoa::handleKeyEvent NSEventTypeFlagsChanged: modifier
+ * presses / releases as keys (Command is Tk's Meta_L). */
+static void handle_flags(BUIKitView *v, NSEventModifierFlags flags)
+{
+ static const struct {
+ NSEventModifierFlags bit;
+ const char *keysym;
+ } keys[] = {{NSEventModifierFlagShift, "Shift_L"},
+ {NSEventModifierFlagControl, "Control_L"},
+ {NSEventModifierFlagOption, "Alt_L"},
+ {NSEventModifierFlagCommand, "Meta_L"}};
+ BKWindow *win = v ? v->bk : NULL;
+ if (!win) {
+ return;
+ }
+ const NSEventModifierFlags old = win->flags;
+ win->flags = flags;
+ g_ignore_momentum = 1;
+ if (win->disabled) {
+ return;
+ }
+ const int mods = mods_of(flags);
+ for (int i = 0; i < 4 && v->bk; i++) {
+ if ((flags ^ old) & keys[i].bit) {
+ if (flags & keys[i].bit) {
+ BK_key(v->bk->ctx, "", keys[i].keysym, mods);
+ }
+ else {
+ BK_key_release(v->bk->ctx, keys[i].keysym, mods);
+ }
+ }
+ }
+}
+
+/* -- windows --------------------------------------------------------------------------- */
+
+/* The view's size in pixels (GHOST_WindowCocoa::updateDrawingSize). */
+static void update_size(BKWindow *win)
+{
+ if (!win->view) {
+ return;
+ }
+ const NSRect b = [win->view convertRectToBacking:[win->view bounds]];
+ const int w = (int)lround(b.size.width), h = (int)lround(b.size.height);
+ if (w != win->w || h != win->h) {
+ win->w = w;
+ win->h = h;
+ win->render_pending = 1;
+ }
+ /* GHOST: live resize is a modal loop that doesn't return to ours; draw now */
+ if ([win->view inLiveResize] && win->render_pending) {
+ render_window(win);
+ }
+}
+
+static void on_backing_changed(BKWindow *win)
+{
+ const float px = (float)[win->nswin backingScaleFactor];
+ if (px > 0.0f && px != win->px) {
+ win->px = px;
+ if (env_scale() <= 0.0f) {
+ win->scale = ui_scale(px);
+ BK_set_scale(win->scale);
+ if (win->ctx->root) {
+ BK_node_relayout(win->ctx->root);
+ }
+ }
+ }
+ win->full = 1;
+ win->render_pending = 1;
+ update_size(win);
+}
+
+static void request_close(BKWindow *win)
+{
+ if (!win->cb.on_close || win->cb.on_close(win->cb.data, win)) {
+ close_window(win);
+ }
+}
+
+/* Close (GHOST_WindowCocoa::~GHOST_WindowCocoa). AppKit may still be inside
+ * this window's methods (we can be called from its delegate or view), so
+ * the window and delegate are released between loop turns. */
+static void close_window(BKWindow *win)
+{
+ if (!win->nswin) {
+ return;
+ }
+ NSWindow *nw = win->nswin;
+ win->nswin = nil;
+ if (win->view) {
+ win->view->bk = NULL;
+ win->view = nil;
+ }
+ if (win->delegate) {
+ win->delegate->bk = NULL;
+ }
+ [nw setDelegate:nil];
+ if (win->cursor == BK_CURSOR_NONE) {
+ show_cursor(1);
+ }
+ [nw orderOut:nil];
+ [nw close];
+ [g_dead addObject:nw];
+ [nw release];
+ if (win->delegate) {
+ [g_dead addObject:win->delegate];
+ [win->delegate release];
+ win->delegate = nil;
+ }
+ g_open--;
+ /* GHOST: make the front-most remaining window key */
+ NSArray *left = [NSApp orderedWindows];
+ for (NSUInteger i = 0; i < [left count]; i++) {
+ NSWindow *o = [left objectAtIndex:i];
+ if (o != nw && [o isVisible] && view_of(o)) {
+ [o makeKeyWindow];
+ break;
+ }
+ }
+}
+
+BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height)
+{
+ if (!BK_window_supported() || !app_init()) {
+ return NULL;
+ }
+ BKWindow *win = (BKWindow *)calloc(1, sizeof(BKWindow));
+ win->ctx = ctx;
+ win->prev = ctx->host;
+ win->raster = BUI_raster_create(1, 1);
+ win->next_timer = 1;
+ @autoreleasepool {
+ NSScreen *screen = [NSScreen mainScreen];
+ win->px = screen ? (float)[screen backingScaleFactor] : 1.0f;
+ if (win->px <= 0.0f) {
+ win->px = 1.0f;
+ }
+ win->scale = ui_scale(win->px);
+ BK_set_scale(win->scale);
+ const CGFloat k = win->scale / win->px; /* logical px -> points */
+ const NSRect rect = NSMakeRect(0, 0, BK_MAX(1.0, width * k), BK_MAX(1.0, height * k));
+ /* GHOST_WindowCocoa::GHOST_WindowCocoa */
+ const NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
+ NSWindowStyleMaskMiniaturizable |
+ NSWindowStyleMaskResizable;
+ BUIKitNSWindow *nw = [[BUIKitNSWindow alloc] initWithContentRect:rect
+ styleMask:style
+ backing:NSBackingStoreBuffered
+ defer:NO];
+ if (!nw) {
+ BUI_raster_free(win->raster);
+ free(win);
+ return NULL;
+ }
+ [nw setReleasedWhenClosed:NO]; /* released by close_window */
+ win->style = style;
+ BUIKitView *view = [[BUIKitView alloc] initWithFrame:rect];
+ view->bk = win;
+ [nw setContentView:view];
+ [nw setInitialFirstResponder:view];
+ [nw makeFirstResponder:view];
+ [view release]; /* the window keeps it */
+ win->view = view;
+ BUIKitWindowDelegate *delegate = [[BUIKitWindowDelegate alloc] init];
+ delegate->bk = win;
+ [nw setDelegate:delegate];
+ win->delegate = delegate;
+ [nw setAcceptsMouseMovedEvents:YES];
+ [nw setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
+ [nw center];
+ win->nswin = nw;
+ const float px = (float)[nw backingScaleFactor];
+ if (px > 0.0f && px != win->px) { /* it opened on another screen */
+ win->px = px;
+ win->scale = ui_scale(px);
+ BK_set_scale(win->scale);
+ }
+ win->flags = [NSEvent modifierFlags];
+ }
+ win->next = g_windows;
+ g_windows = win;
+ g_open++;
+ BK_window_set_title(win, title);
+ update_size(win);
+ 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);
+ return win;
+}
+
+void BK_window_free(BKWindow *win)
+{
+ if (!win) {
+ return;
+ }
+ @autoreleasepool {
+ close_window(win);
+ }
+ for (BKWindow **p = &g_windows; *p; p = &(*p)->next) {
+ if (*p == win) {
+ *p = win->next;
+ break;
+ }
+ }
+ if (win->ctx) {
+ BK_context_set_host(win->ctx, &win->prev);
+ }
+ BUI_raster_free(win->raster);
+ free(win);
+}
+
+void BK_window_set_callbacks(BKWindow *win, const BKWindowCallbacks *cb)
+{
+ win->cb = *cb;
+}
+
+void BK_window_show(BKWindow *win)
+{
+ if (!win->nswin) {
+ return;
+ }
+ @autoreleasepool {
+ if (!win->shown) {
+ win->shown = 1;
+ [NSApp activateIgnoringOtherApps:YES]; /* started from a terminal: come to the front */
+ }
+ [win->nswin makeKeyAndOrderFront:nil];
+ }
+ win->full = 1;
+ win->render_pending = 1;
+}
+
+void BK_window_close(BKWindow *win)
+{
+ @autoreleasepool {
+ close_window(win);
+ }
+}
+
+int BK_window_is_open(BKWindow *win)
+{
+ return win && win->nswin != nil;
+}
+
+/* GHOST_WindowCocoa::setTitle */
+void BK_window_set_title(BKWindow *win, const char *title)
+{
+ if (!win->nswin) {
+ return;
+ }
+ @autoreleasepool {
+ NSString *t = [NSString stringWithUTF8String:title ? title : ""];
+ [win->nswin setTitle:t ? t : @""];
+ }
+}
+
+/* Content size limits in points; fixed axes are pinned (Tk's resizable). */
+static void apply_limits(BKWindow *win)
+{
+ const CGFloat k = win->scale / win->px;
+ const NSSize cur = [win->view bounds].size;
+ NSSize mn = NSMakeSize(win->min_w * k, win->min_h * k);
+ NSSize mx = NSMakeSize(win->max_w ? win->max_w * k : FLT_MAX,
+ win->max_h ? win->max_h * k : FLT_MAX);
+ if (win->fixed_w) {
+ mn.width = mx.width = cur.width;
+ }
+ if (win->fixed_h) {
+ mn.height = mx.height = cur.height;
+ }
+ [win->nswin setContentMinSize:mn];
+ [win->nswin setContentMaxSize:mx];
+}
+
+/* GHOST_WindowCocoa::setClientSize */
+void BK_window_set_size(BKWindow *win, int width, int height)
+{
+ if (!win->nswin) {
+ return;
+ }
+ @autoreleasepool {
+ const CGFloat k = win->scale / win->px;
+ [win->nswin setContentSize:NSMakeSize(BK_MAX(1.0, width * k), BK_MAX(1.0, height * k))];
+ if (win->fixed_w || win->fixed_h) {
+ apply_limits(win);
+ }
+ update_size(win);
+ }
+ win->render_pending = 1;
+}
+
+void BK_window_get_size(BKWindow *win, int *w, int *h)
+{
+ *w = win->nswin ? win->w : 0;
+ *h = win->nswin ? win->h : 0;
+}
+
+BuiRaster *BK_window_raster(BKWindow *win)
+{
+ return win->raster;
+}
+
+void BK_window_set_gpu(BKWindow *win, int on)
+{
+ (void)win;
+ (void)on; /* the GPU renderer is Direct3D 11: the Cocoa host presents the CPU raster */
+}
+
+int BK_window_gpu(BKWindow *win)
+{
+ return 0;
+}
+
+int BK_window_frames(BKWindow *win)
+{
+ return win->frames;
+}
+
+void BK_window_render_now(BKWindow *win)
+{
+ if (win->nswin) {
+ win->full = 1;
+ render_window(win);
+ }
+}
+
+int BK_window_timer(BKWindow *win, int ms)
+{
+ const int ident = win->next_timer++;
+ BKCocoaTimer *t = timer_slot(win, ident);
+ if (t) {
+ t->ident = ident;
+ t->due = now_ms() + BK_MAX(0, ms);
+ }
+ return ident;
+}
+
+void BK_window_cancel_timer(BKWindow *win, int ident)
+{
+ for (int i = 0; i < MAX_TIMERS; i++) {
+ if (win->timers[i].ident == ident) {
+ win->timers[i].ident = 0;
+ }
+ }
+}
+
+void BK_window_request_frame(BKWindow *win, int vsync)
+{
+ win->want_frame = 1;
+ win->frame_vsync = vsync;
+ win->render_pending = 1;
+}
+
+void *BK_window_handle(BKWindow *win)
+{
+ return (void *)win->nswin; /* NSWindow * */
+}
+
+/* Window-manager requests (Tk's wm), after GHOST_WindowCocoa::setState /
+ * setOrder. Positions are in points, top-left origin. */
+void BK_window_wm(BKWindow *win, const char *key, double a, double b)
+{
+ NSWindow *nw = win->nswin;
+ if (!nw) {
+ return;
+ }
+ @autoreleasepool {
+ if (!strcmp(key, "pos")) {
+ [nw setFrameTopLeftPoint:NSMakePoint(a, primary_height() - b)];
+ }
+ else if (!strcmp(key, "minsize") || !strcmp(key, "maxsize")) {
+ const int mini = key[1] == 'i';
+ *(mini ? &win->min_w : &win->max_w) = (int)a;
+ *(mini ? &win->min_h : &win->max_h) = (int)b;
+ apply_limits(win);
+ }
+ else if (!strcmp(key, "resizable")) {
+ win->fixed_w = a == 0.0;
+ win->fixed_h = b == 0.0;
+ if (win->fixed_w && win->fixed_h) {
+ win->style &= ~NSWindowStyleMaskResizable;
+ }
+ else {
+ win->style |= NSWindowStyleMaskResizable;
+ }
+ if (!win->override) {
+ [nw setStyleMask:win->style];
+ }
+ apply_limits(win);
+ }
+ else if (!strcmp(key, "topmost")) {
+ [nw setLevel:a ? NSFloatingWindowLevel : NSNormalWindowLevel];
+ }
+ else if (!strcmp(key, "alpha")) {
+ [nw setAlphaValue:BK_CLAMP(a, 0.0, 1.0)];
+ }
+ else if (!strcmp(key, "override")) {
+ win->override = a != 0.0;
+ [nw setStyleMask:win->override ? NSWindowStyleMaskBorderless : win->style];
+ update_size(win);
+ }
+ else if (!strcmp(key, "state")) {
+ switch (BK_CLAMP((int)a, 0, 3)) {
+ case 1:
+ [nw miniaturize:nil];
+ break;
+ case 2:
+ [nw orderOut:nil];
+ break;
+ case 3:
+ if (![nw isVisible]) {
+ [nw makeKeyAndOrderFront:nil];
+ }
+ if (![nw isZoomed]) {
+ [nw zoom:nil];
+ }
+ break;
+ default:
+ if ([nw isMiniaturized]) {
+ [nw deminiaturize:nil];
+ }
+ else if ([nw isZoomed]) {
+ [nw zoom:nil];
+ }
+ if (![nw isVisible]) {
+ [nw makeKeyAndOrderFront:nil];
+ }
+ break;
+ }
+ }
+ else if (!strcmp(key, "lift")) {
+ [nw orderFront:nil];
+ }
+ else if (!strcmp(key, "lower")) {
+ [nw orderBack:nil];
+ }
+ else if (!strcmp(key, "disabled")) { /* modal dialogs disable their parent */
+ win->disabled = a != 0.0;
+ }
+ else if (!strcmp(key, "focus")) {
+ [NSApp activateIgnoringOtherApps:YES];
+ [nw makeKeyAndOrderFront:nil];
+ }
+ }
+}
+
+int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b)
+{
+ *r_a = *r_b = 0.0;
+ if (!pthread_main_np()) {
+ return 0;
+ }
+ int ok = 0;
+ @autoreleasepool {
+ if (!strcmp(key, "screen")) {
+ NSScreen *s = (win && win->nswin && [win->nswin screen]) ? [win->nswin screen] :
+ [NSScreen mainScreen];
+ if (s) {
+ *r_a = [s frame].size.width;
+ *r_b = [s frame].size.height;
+ }
+ ok = 1;
+ }
+ else if (!strcmp(key, "scale")) {
+ NSScreen *s = [NSScreen mainScreen];
+ *r_a = *r_b = win ? win->scale : ui_scale(s ? (float)[s backingScaleFactor] : 1.0f);
+ ok = 1;
+ }
+ else if (!strcmp(key, "pointer")) {
+ const NSPoint p = [NSEvent mouseLocation];
+ *r_a = p.x;
+ *r_b = primary_height() - p.y;
+ ok = 1;
+ }
+ else if (win && win->nswin) {
+ if (!strcmp(key, "pos")) { /* the content's top-left on screen */
+ const NSRect c = [win->nswin contentRectForFrameRect:[win->nswin frame]];
+ *r_a = c.origin.x;
+ *r_b = primary_height() - NSMaxY(c);
+ ok = 1;
+ }
+ else if (!strcmp(key, "state")) { /* GHOST_WindowCocoa::getState */
+ NSWindow *nw = win->nswin;
+ *r_a = [nw isMiniaturized] ? 1 : ![nw isVisible] ? 2 : [nw isZoomed] ? 3 : 0;
+ ok = 1;
+ }
+ }
+ }
+ return ok;
+}
+
+/* -- the loop (GHOST_SystemCocoa::processEvents) --------------------------------------- */
+
+static void run_timers(void)
+{
+ const double t = now_ms();
+ for (BKWindow *win = g_windows; win; win = win->next) {
+ for (int i = 0; i < MAX_TIMERS && win->nswin; i++) {
+ BKCocoaTimer *tm = &win->timers[i];
+ if (tm->ident != 0 && tm->due <= t) {
+ const int ident = tm->ident;
+ tm->ident = 0;
+ if (ident == -1) {
+ BK_timer(win->ctx, win->tip_id);
+ }
+ else if (win->cb.on_timer) {
+ win->cb.on_timer(win->cb.data, win, ident);
+ }
+ }
+ }
+ }
+}
+
+static void render_due(void)
+{
+ const double t = now_ms();
+ for (BKWindow *win = g_windows; win; win = win->next) {
+ if (win->nswin && win->render_pending && t >= win->next_frame) {
+ render_window(win);
+ }
+ }
+}
+
+/* Milliseconds until the next timer or frame (-1: nothing to wait for). */
+static double next_wait(void)
+{
+ double wait = -1.0;
+ const double t = now_ms();
+ for (BKWindow *win = g_windows; win; win = win->next) {
+ if (!win->nswin) {
+ continue;
+ }
+ if (win->render_pending) {
+ const double d = BK_MAX(0.0, win->next_frame - t);
+ wait = wait < 0 ? d : BK_MIN(wait, d);
+ }
+ for (int i = 0; i < MAX_TIMERS; i++) {
+ if (win->timers[i].ident != 0) {
+ const double d = BK_MAX(0.0, win->timers[i].due - t);
+ wait = wait < 0 ? d : BK_MIN(wait, d);
+ }
+ }
+ }
+ return wait;
+}
+
+/* An application-defined event that ends a wait in nextEventMatchingMask. */
+static void post_nudge(void)
+{
+ if (g_nudge_pending || NSApp == nil) {
+ return;
+ }
+ g_nudge_pending = 1;
+ @autoreleasepool {
+ NSEvent *e = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
+ location:NSZeroPoint
+ modifierFlags:0
+ timestamp:0
+ windowNumber:0
+ context:nil
+ subtype:BK_NUDGE_SUBTYPE
+ data1:BK_NUDGE_DATA
+ data2:0];
+ [NSApp postEvent:e atStart:NO];
+ }
+}
+
+static void handle_event(NSEvent *ev)
+{
+ const NSEventType type = [ev type];
+ if (type == NSEventTypeApplicationDefined && [ev subtype] == BK_NUDGE_SUBTYPE &&
+ [ev data1] == BK_NUDGE_DATA)
+ {
+ g_nudge_pending = 0;
+ return;
+ }
+ /* GHOST: Control+(Shift+)Tab never reaches the view (AppKit uses it to
+ * move between views); handle it directly */
+ if (type == NSEventTypeKeyDown && [ev keyCode] == BK_kVK_Tab &&
+ ([ev modifierFlags] & NSEventModifierFlagControl))
+ {
+ handle_key(view_of([ev window]), ev, 1);
+ return;
+ }
+ /* GHOST: NSApp swallows key-ups while Command / Option are held */
+ if (type == NSEventTypeKeyUp &&
+ ([ev modifierFlags] & (NSEventModifierFlagCommand | NSEventModifierFlagOption)))
+ {
+ handle_key(view_of([ev window]), ev, 0);
+ g_keyup_done = ev; /* in case it does reach keyUp: */
+ }
+ [NSApp sendEvent:ev];
+ g_keyup_done = nil;
+}
+
+/* One turn: events, timers, renders; blocks up to `block_ms` (-1: forever). */
+static void turn(double block_ms)
+{
+ g_turn_depth++;
+ @autoreleasepool {
+ if (g_turn_depth == 1) {
+ [g_dead removeAllObjects]; /* nothing of theirs is on the stack now */
+ }
+ g_nudge_pending = 0; /* another loop (Tk, a modal panel) may have eaten ours */
+ NSDate *until = block_ms < 0.0 ? [NSDate distantFuture] :
+ block_ms == 0.0 ? [NSDate distantPast] :
+ [NSDate dateWithTimeIntervalSinceNow:block_ms / 1000.0];
+ NSEvent *ev = [NSApp nextEventMatchingMask:NSEventMaskAny
+ untilDate:until
+ inMode:NSDefaultRunLoopMode
+ dequeue:YES];
+ for (int n = 0; ev && n < 512; n++) {
+ handle_event(ev);
+ ev = [NSApp nextEventMatchingMask:NSEventMaskAny
+ untilDate:[NSDate distantPast]
+ inMode:NSDefaultRunLoopMode
+ dequeue:YES];
+ }
+ if (ev) {
+ handle_event(ev);
+ }
+ run_timers();
+ render_due();
+ }
+ g_turn_depth--;
+}
+
+void BK_window_set_stop_check(int (*stop)(void))
+{
+ g_stop = stop;
+}
+
+/* Callable from any thread. */
+void BK_window_quit(void)
+{
+ g_quit = 1;
+ if (pthread_main_np()) {
+ post_nudge();
+ }
+ else {
+ BK_window_wake();
+ }
+}
+
+void BK_window_run(void)
+{
+ /* keep-alive loops (driven through BK_window_wake) may start before any
+ * window exists */
+ if (!BK_window_supported() || !app_init()) {
+ return;
+ }
+ g_quit = 0;
+ while ((g_open > 0 || g_keep_alive) && !g_quit) {
+ turn(next_wait());
+ if (g_stop && g_stop()) {
+ break;
+ }
+ }
+}
+
+int BK_window_pump(void)
+{
+ if (g_app_ready && pthread_main_np()) {
+ turn(0.0);
+ }
+ return g_open;
+}
+
+/* The wake: a run-loop source on the main run loop, in the common modes so
+ * it also fires inside AppKit's own loops (live resize, modal panels), as
+ * Win32's message-only window does inside modal move / resize loops. */
+static void wake_perform(void *info)
+{
+ (void)info;
+ if (__atomic_exchange_n(&g_wake_pending, 0, __ATOMIC_ACQ_REL) && g_wake_cb) {
+ g_wake_cb();
+ }
+ @autoreleasepool {
+ render_due(); /* draw what it changed even inside AppKit's loops */
+ post_nudge(); /* and let our loop recompute its wait */
+ }
+}
+
+int BK_window_wake_init(void (*cb)(void))
+{
+ g_wake_cb = cb;
+ if (!g_wake_src) {
+ CFRunLoopSourceContext c;
+ memset(&c, 0, sizeof(c));
+ c.perform = wake_perform;
+ g_wake_src = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &c);
+ if (!g_wake_src) {
+ return 0;
+ }
+ CFRunLoopAddSource(CFRunLoopGetMain(), g_wake_src, kCFRunLoopCommonModes);
+ }
+ return 1;
+}
+
+/* Thread-safe: wakes the loop, which calls the wake callback. */
+void BK_window_wake(void)
+{
+ if (g_wake_src && !__atomic_exchange_n(&g_wake_pending, 1, __ATOMIC_ACQ_REL)) {
+ CFRunLoopSourceSignal(g_wake_src);
+ CFRunLoopWakeUp(CFRunLoopGetMain());
+ }
+}
+
+void BK_window_set_keep_alive(int on)
+{
+ g_keep_alive = on;
+}
+
+#endif /* BUI_WINDOW_COCOA */
diff --git a/kit/intern/kit_window_null.c b/kit/intern/kit_window_null.c
index 115000d..5941d97 100644
--- a/kit/intern/kit_window_null.c
+++ b/kit/intern/kit_window_null.c
@@ -5,7 +5,7 @@
#include "kit_intern.h"
-#if !defined(_WIN32) && !defined(BUI_WINDOW_X11)
+#if !defined(_WIN32) && !defined(BUI_WINDOW_X11) && !defined(BUI_WINDOW_COCOA)
int BK_window_supported(void)
diff --git a/kit/intern/kit_window_x11.c b/kit/intern/kit_window_x11.c
index 2c6b43e..b84257b 100644
--- a/kit/intern/kit_window_x11.c
+++ b/kit/intern/kit_window_x11.c
@@ -3,7 +3,9 @@
* The same BK_window_* API as kit_window_win32.c, on Xlib: input events go
* straight to BK_* input (button and key mapping after Blender's
* GHOST_SystemX11), redraw requests coalesce into one render per loop turn,
- * and the damaged rectangles of the CPU raster are put with XPutImage.
+ * and the damaged rectangles of the CPU raster are put with XPutImage (or,
+ * with BUI_GPU / BK_window_set_gpu, the raster draws with OpenGL and presents
+ * through GLX on the same connection).
* Timers, the cross-thread wake (a pipe) and frame pacing run in the select()
* loop.
*
@@ -385,8 +387,27 @@ static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, d
/* -- rendering -- */
+/* Moves the window's raster to the GPU (OpenGL through GLX on our Display);
+ * BUI_raster_gpu_poll switches over at the next render, and failures leave
+ * it on the software raster. */
+static void gpu_attach(BKWindow *win)
+{
+ if (win->xid) {
+ BuiGpuX11Window target = {g_dpy, (unsigned long)win->xid};
+ BUI_raster_gpu_attach(win->raster, &target, 0);
+ }
+}
+
static void present(BKWindow *win, int all)
{
+ if (BUI_raster_is_gpu(win->raster)) {
+ BUI_raster_present_native(win->raster, NULL, all);
+ if (!BUI_raster_is_gpu(win->raster)) {
+ win->full = 1; /* device lost: the software raster redraws everything */
+ win->render_pending = 1;
+ }
+ return;
+ }
const int w = BUI_raster_width(win->raster), h = BUI_raster_height(win->raster);
if (!win->image || win->image->width != w || win->image->height != h) {
if (win->image) {
@@ -418,12 +439,16 @@ static void do_render(BKWindow *win)
{
const int w = BK_MAX(1, win->w), h = BK_MAX(1, win->h);
const int resized = BUI_raster_width(win->raster) != w || BUI_raster_height(win->raster) != h;
- const int regions = BK_render(win->ctx, win->raster, w, h, win->full || resized);
- if (regions || resized || win->full) {
- present(win, resized || win->full);
- win->frames++;
+ if (BUI_raster_gpu_poll(win->raster)) {
+ win->full = 1; /* the renderer changed: its frame starts empty */
}
+ const int full = win->full || resized;
win->full = 0;
+ const int regions = BK_render(win->ctx, win->raster, w, h, full);
+ if (regions || full) {
+ present(win, full);
+ win->frames++;
+ }
}
static double refresh_ms(void)
@@ -649,6 +674,9 @@ BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height
win->next = g_windows;
g_windows = win;
g_open++;
+ if (BUI_gpu_default()) {
+ gpu_attach(win);
+ }
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);
@@ -743,13 +771,15 @@ BuiRaster *BK_window_raster(BKWindow *win)
void BK_window_set_gpu(BKWindow *win, int on)
{
- (void)win;
- (void)on; /* the X11 host presents the CPU raster */
+ if (win && on) {
+ gpu_attach(win);
+ host_request(win);
+ }
}
int BK_window_gpu(BKWindow *win)
{
- return 0;
+ return win && BUI_raster_is_gpu(win->raster);
}
int BK_window_frames(BKWindow *win)
diff --git a/tests/window_smoke.c b/tests/window_smoke.c
index 4fff0b2..fa1b689 100644
--- a/tests/window_smoke.c
+++ b/tests/window_smoke.c
@@ -56,7 +56,7 @@ int main(void)
const int frames = BK_window_frames(win);
int w, h;
BK_window_get_size(win, &w, &h);
- printf("frames %d ticks %d size %dx%d\n", frames, g_ticks, w, h);
+ printf("frames %d ticks %d size %dx%d gpu %d\n", frames, g_ticks, w, h, BK_window_gpu(win));
BK_window_free(win);
BK_context_free(ctx);
BK_node_free(ed);